// Sefra brand v2 - cool bone, ink black, cobalt accent
// Modern grotesk (Geist), heavier grid, fewer hairlines, more confident blocks
// ────────────────────────────────────────────────────────────────

const BASEN = {
  // Cool neutral palette - no warmth
  paper: '#F4F4F1',         // cool bone background
  paperDeep: '#EAEAE4',     // slightly deeper bone
  paperRaised: '#FFFFFF',   // pure white surface
  ink: '#0F1216',           // near-black, slight cool tint
  inkSoft: '#1E2228',       // softer ink for backgrounds
  muted: '#6E7079',         // mid cool gray
  mutedDark: '#9CA0AC',     // muted on dark backgrounds
  rule: '#DBDBD5',          // hairline
  ruleSoft: '#E8E8E2',
  ruleDark: 'rgba(244,244,241,0.10)',

  // Accent - confident cobalt
  accent: '#1547F5',        // primary cobalt
  accentDeep: '#0E2FBC',    // pressed/dark variant
  accentBg: '#E8EDFF',      // pale cobalt wash
  accentInk: '#FFFFFF',     // text on accent

  // Secondary - for category color & status
  signal: '#FF4F1F',        // safety orange - used sparingly for callouts
  signalBg: '#FFE5DD',
  positive: '#16A34A',
  positiveBg: '#DCFCE7',
  warning: '#EAB308',
};

const FONTS = {
  // Geist is the new spine - clean modern grotesk, no warmth
  display: '"Geist", "Inter Tight", -apple-system, BlinkMacSystemFont, sans-serif',
  sans: '"Geist", "Inter", -apple-system, BlinkMacSystemFont, sans-serif',
  mono: '"Geist Mono", "JetBrains Mono", ui-monospace, monospace',
};

// ─── Responsive viewport hook ────────────────────────────────
// Tracks the element's own width (falls back to window) so it works
// both as a standalone page and inside fixed-width canvas artboards.
function useViewport() {
  const get = () => (typeof window !== 'undefined' ? (window.__forceWidth || window.innerWidth) : 1440);
  const [w, setW] = React.useState(get());
  React.useEffect(() => {
    const on = () => setW(get());
    window.addEventListener('resize', on);
    on();
    return () => window.removeEventListener('resize', on);
  }, []);
  return { w, isMobile: w < 760, isTablet: w >= 760 && w < 1080, isDesktop: w >= 1080 };
}

// ─── Logo: inline-SVG bird mark + wordmark (no external assets) ──
const SEFRA_BIRD_PATH = "M66.616 51.836 L67.015 51.703 L125.47 110.157 L129.997 116.016 L133.193 121.076 L135.59 125.603 L137.987 131.995 L139.851 141.582 L139.851 150.636 L139.318 154.897 L137.72 161.821 L135.856 167.147 L131.595 175.936 L123.872 189.517 L118.812 199.637 L114.818 206.561 L114.152 207.227 L70.078 207.094 L113.353 173.406 L114.285 172.207 L114.551 170.876 L114.551 166.881 L112.954 162.62 L109.625 158.759 L100.038 153.699 L92.581 150.503 L86.19 146.508 L83.526 144.378 L79.132 139.984 L77.268 137.587 L74.339 133.06 L71.942 128.266 L70.344 123.739 L70.344 122.94 L71.01 122.807 L73.14 124.405 L77.934 127.068 L99.771 136.655 L106.163 140.117 L106.562 139.984 L102.168 135.856 L96.309 131.329 L78.2 118.812 L74.206 115.35 L70.344 111.223 L66.083 105.097 L62.621 97.907 L60.757 90.983 L60.224 85.923 L60.358 82.861 L61.689 83.393 L67.814 89.518 L73.407 94.046 L96.842 110.557 L106.163 117.747 L106.695 118.013 L106.828 117.614 L102.301 112.554 L78.6 89.385 L71.409 80.597 L68.214 74.472 L65.817 66.216 L65.284 59.292 L65.551 59.026 L65.551 55.83 L66.483 51.969Z M167.014 89.385 L170.077 89.252 L174.87 90.584 L178.066 92.448 L180.995 95.643 L186.588 95.91 L189.784 96.709 L192.713 98.307 L195.509 101.369 L188.985 103.1 L183.659 106.03 L179.797 109.891 L177.4 114.152 L175.802 119.478 L175.802 137.054 L175.27 141.848 L174.205 146.642 L172.607 151.701 L169.145 159.424 L165.683 164.751 L162.487 168.745 L155.163 175.536 L148.239 180.063 L141.848 183.259 L135.989 185.656 L132.794 186.721 L131.728 186.721 L131.595 186.055 L134.791 180.729 L140.117 170.077 L141.715 166.082 L143.845 159.158 L145.177 150.37 L145.177 142.114 L144.378 136.256 L142.248 128.533 L140.916 125.071 L138.519 120.543 L138.519 119.478 L148.106 104.299 L145.044 103.366 L141.582 101.236 L139.584 98.972 L138.519 96.842 L144.511 96.709 L147.707 96.176 L151.968 94.845 L161.022 90.85 L164.218 89.785 L166.881 89.518Z";

function BasenLogo({ size = 22, color, accent }) {
  const ink = color || BASEN.ink;
  const birdColor = accent || BASEN.accent;
  return (
    <span style={{
      display: 'inline-flex',
      alignItems: 'center',
      gap: size * 0.44,
      lineHeight: 1,
      whiteSpace: 'nowrap',
    }}>
      <svg
        viewBox="59 49 139 160"
        role="img"
        aria-label="Sefra"
        style={{ height: size * 1.55, width: 'auto', display: 'block', flexShrink: 0 }}
      >
        <path d={SEFRA_BIRD_PATH} fill={birdColor} fillRule="evenodd" />
      </svg>
      <span style={{
        fontFamily: FONTS.display,
        fontSize: size,
        fontWeight: 600,
        letterSpacing: -size * 0.025,
        color: ink,
      }}>sefra</span>
    </span>
  );
}

// ─── Eyebrow: mono, uppercase, tighter ──────────────────────
function Eyebrow({ children, color, accent = false, style = {} }) {
  return (
    <div style={{
      fontFamily: FONTS.mono,
      fontSize: 11,
      letterSpacing: 1.2,
      textTransform: 'uppercase',
      color: accent ? BASEN.accent : (color || BASEN.muted),
      fontWeight: 500,
      display: 'inline-flex',
      alignItems: 'center',
      gap: 8,
      ...style,
    }}>{accent && <span style={{
      width: 6, height: 6, background: BASEN.accent, display: 'inline-block',
    }}></span>}{children}</div>
  );
}

// ─── CTA Button - squarer, more confident ────────────────────
function Btn({ label, variant = 'solid', size = 'md', arrow = false, onClick, style = {} }) {
  const pad = size === 'sm' ? '9px 16px' : size === 'lg' ? '15px 28px' : '12px 22px';
  const fs = size === 'sm' ? 13 : size === 'lg' ? 15 : 14;
  const base = {
    fontFamily: FONTS.sans,
    fontWeight: 500,
    fontSize: fs,
    padding: pad,
    borderRadius: 4,
    display: 'inline-flex',
    alignItems: 'center',
    gap: 8,
    border: 'none',
    cursor: 'pointer',
    lineHeight: 1,
    whiteSpace: 'nowrap',
    transition: 'background 120ms ease, opacity 120ms ease',
    letterSpacing: -0.1,
    ...style,
  };
  const variants = {
    solid: { background: BASEN.ink, color: BASEN.paper },
    accent: { background: BASEN.accent, color: BASEN.accentInk },
    paper: { background: BASEN.paperRaised, color: BASEN.ink },
    ghost: { background: 'transparent', color: BASEN.ink, boxShadow: `inset 0 0 0 1px ${BASEN.ink}` },
    ghostInk: { background: 'transparent', color: BASEN.paper, boxShadow: `inset 0 0 0 1px rgba(244,244,241,0.3)` },
    ghostAccent: { background: 'transparent', color: BASEN.accent, boxShadow: `inset 0 0 0 1px ${BASEN.accent}` },
  };
  return (
    <button onClick={onClick} style={{ ...base, ...variants[variant] }}>
      {label}
      {arrow && <span style={{ display: 'inline-block', transform: 'translateY(-0.5px)', fontWeight: 400 }}>→</span>}
    </button>
  );
}

// ─── Top nav ─────────────────────────────────────────────────
function TopNav({ onDark = false, cta = 'Start for free' }) {
  const { isMobile } = useViewport();
  const ink = onDark ? BASEN.paper : BASEN.ink;
  const muted = onDark ? BASEN.mutedDark : BASEN.muted;
  const links = [
    { label: 'How it works', href: '#how-it-works' },
    { label: 'Use cases', href: '#use-cases' },
    { label: 'Pricing', href: '#pricing' },
  ];
  const goContact = () => {
    if (window.sefraStartTrial) { window.sefraStartTrial('nav'); return; }
    if (window.sefraOpenCalendly) window.sefraOpenCalendly('nav');
  };
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: isMobile ? '16px 20px' : '20px 48px',
      borderBottom: `1px solid ${onDark ? BASEN.ruleDark : BASEN.ruleSoft}`,
      gap: 16,
    }}>
      <BasenLogo size={isMobile ? 20 : 22} color={ink} />
      {!isMobile && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 32 }}>
          {links.map(l => (
            <a key={l.label} href={l.href} style={{
              fontFamily: FONTS.sans, fontSize: 13.5, color: muted, textDecoration: 'none', fontWeight: 450,
              letterSpacing: -0.1,
            }}>{l.label}</a>
          ))}
        </div>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <Btn label={cta} variant={onDark ? 'paper' : 'solid'} size="sm" arrow onClick={goContact} />
      </div>
    </div>
  );
}

// ─── Footer ──────────────────────────────────────────────────
function Footer({ onDark = false }) {
  const { isMobile } = useViewport();
  const bg = BASEN.ink;
  const ink = BASEN.paper;
  const muted = BASEN.mutedDark;
  const rule = BASEN.ruleDark;
  const linkStyle = {
    fontFamily: FONTS.sans, fontSize: 13.5, color: ink, textDecoration: 'none',
    letterSpacing: -0.1,
  };
  const nav = [
    { label: 'How it works', href: '#how-it-works' },
    { label: 'Use cases', href: '#use-cases' },
    { label: 'Pricing', href: '#pricing' },
  ];
  const reach = [
    { label: 'hello@meetsefra.com', href: 'mailto:hello@meetsefra.com' },
    { label: 'Start for free', href: '#pricing' },
  ];
  const colHeader = {
    fontFamily: FONTS.mono, fontSize: 10.5, letterSpacing: 1.4, textTransform: 'uppercase',
    color: muted, marginBottom: 22,
  };
  return (
    <div style={{ background: bg, color: ink, padding: isMobile ? '48px 20px 24px' : '72px 48px 28px' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '2fr 1fr 1fr', gap: isMobile ? 32 : 36,
        paddingBottom: isMobile ? 36 : 56,
        borderBottom: `1px solid ${rule}`,
      }}>
        <div>
          <BasenLogo size={26} color={ink} accent={BASEN.accent} />
          <div style={{
            fontFamily: FONTS.sans, fontSize: 14, lineHeight: 1.55, color: muted,
            marginTop: 18, maxWidth: 300, letterSpacing: -0.1,
          }}>
            A browser agent that runs your legacy software for you - triggered from email, Slack, or a schedule. Built for legacy claims systems first.
          </div>
          <a href="https://meetsefra.com" style={{
            display: 'inline-block', marginTop: 28,
            fontFamily: FONTS.mono, fontSize: 11, color: ink, letterSpacing: 1,
            textTransform: 'uppercase', textDecoration: 'none',
            borderBottom: `1px solid ${rule}`, paddingBottom: 3,
          }}>meetsefra.com →</a>
        </div>
        <div>
          <div style={colHeader}>Navigate</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {nav.map(l => (<a key={l.label} href={l.href} style={linkStyle}>{l.label}</a>))}
          </div>
        </div>
        <div>
          <div style={colHeader}>Get in touch</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {reach.map(l => (<a key={l.label} href={l.href} style={linkStyle}>{l.label}</a>))}
          </div>
        </div>
      </div>
      <div style={{
        paddingTop: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        gap: 12, flexWrap: 'wrap',
      }}>
        <div style={{
          fontFamily: FONTS.mono, fontSize: 11, color: muted, letterSpacing: 0.6,
        }}>
          © 2026 SEFRA, INC.
        </div>
        <div style={{
          fontFamily: FONTS.mono, fontSize: 11, color: muted, letterSpacing: 1, textTransform: 'uppercase',
        }}>
          New York
        </div>
      </div>
    </div>
  );
}

// ─── Demo form ───────────────────────────────────────────────
const FORMSPREE_ENDPOINT = 'https://formspree.io/f/mgoqqlgv';

// ─── Calendly inline embed ───────────────────────────────────
function CalendlyInline({ height = 680 }) {
  const ref = React.useRef(null);
  const { isMobile } = useViewport();
  React.useEffect(() => {
    const cfg = window.SEFRA_META || {};
    const url = cfg.calendlyUrl;
    if (!ref.current || !url) return;
    let tries = 0;
    const init = () => {
      if (window.Calendly && window.Calendly.initInlineWidget) {
        ref.current.innerHTML = '';
        window.Calendly.initInlineWidget({ url: url, parentElement: ref.current });
      } else if (tries++ < 40) {
        setTimeout(init, 150);   // wait for widget.js to load
      }
    };
    init();
  }, []);
  return (
    <div style={{
      background: BASEN.paperRaised, border: `1px solid ${BASEN.rule}`, borderRadius: 8,
      overflow: 'hidden', minHeight: isMobile ? 560 : height,
    }}>
      <div ref={ref} style={{ minWidth: 280, height: isMobile ? 560 : height }}></div>
      <noscript>
        <div style={{ padding: 24, fontFamily: FONTS.sans, fontSize: 15, color: BASEN.muted }}>
          Enable JavaScript to book, or email hello@meetsefra.com.
        </div>
      </noscript>
    </div>
  );
}

function DemoForm({ onDark = false, layout = 'inline' }) {
  const { isMobile } = useViewport();
  const stacked = layout === 'stacked' || isMobile;
  const [state, setState] = React.useState({ name: '', email: '', sent: false, sending: false, error: '' });
  const ink = onDark ? BASEN.paper : BASEN.ink;
  const muted = onDark ? BASEN.mutedDark : BASEN.muted;
  const surface = onDark ? 'rgba(244,244,241,0.06)' : BASEN.paperRaised;
  const rule = onDark ? 'rgba(244,244,241,0.18)' : BASEN.rule;

  const fieldStyle = {
    fontFamily: FONTS.sans,
    fontSize: 14,
    color: ink,
    background: surface,
    border: `1px solid ${rule}`,
    borderRadius: 4,
    padding: '13px 14px',
    outline: 'none',
    width: '100%',
    letterSpacing: -0.1,
  };

  // MEDIUM-value signal: user started filling the Talk to Sales form.
  // Fires once on first focus of either field (InitiateCheckout funnel step).
  const startedRef = React.useRef(false);
  const onFieldFocus = () => {
    if (startedRef.current) return;
    startedRef.current = true;
    const m = window.SEFRA_META || {};
    if (window.sefraTrack) window.sefraTrack('InitiateCheckout', {
      content_name: 'Talk to sales form started',
      value: typeof m.formStartValue === 'number' ? m.formStartValue : 10,
      currency: m.currency || 'USD',
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (state.sending) return;
    setState((s) => ({ ...s, sending: true, error: '' }));
    try {
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: 'POST',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: state.name,
          email: state.email,
          _subject: `New inquiry from ${state.name || 'website'} - Sefra`,
        }),
      });
      if (res.ok) {
        // Meta conversion - fires Pixel + CAPI (deduplicated by event_id)
        if (window.sefraTrack) {
          const meta = window.SEFRA_META || {};
          window.sefraTrack(
            'Lead',
            {
              content_name: 'Demo request',
              content_category: 'workers-comp-tpa',
              value: typeof meta.leadValue === 'number' ? meta.leadValue : 1,
              currency: meta.currency || 'USD',
            },
            { em: (state.email || '').trim().toLowerCase(), fn: (state.name || '').trim().toLowerCase() }
          );
        }
        setState((s) => ({ ...s, sent: true, sending: false }));
      } else {
        const data = await res.json().catch(() => null);
        const msg = data && Array.isArray(data.errors) && data.errors.length
          ? data.errors.map((er) => er.message).join(' ')
          : 'Something went wrong. Please try again.';
        setState((s) => ({ ...s, sending: false, error: msg }));
      }
    } catch (err) {
      setState((s) => ({ ...s, sending: false, error: 'Network error - please try again or email hello@meetsefra.com.' }));
    }
  };

  if (state.sent) {
    return (
      <div style={{
        background: surface, border: `1px solid ${rule}`, borderRadius: 6,
        padding: '32px 28px', textAlign: 'center',
      }}>
        <div style={{
          fontFamily: FONTS.display, fontSize: 24, color: ink, marginBottom: 8,
          fontWeight: 600, letterSpacing: -0.5,
        }}>Thanks - we'll be in touch.</div>
        <div style={{ fontFamily: FONTS.sans, fontSize: 14.5, color: muted }}>
          Expect a note from our team within one business day.
        </div>
      </div>
    );
  }

  return (
    <div>
      <form onSubmit={handleSubmit}
        style={{
          display: 'grid',
          gridTemplateColumns: stacked ? '1fr' : '1fr 1fr auto',
          gap: 8,
        }}>
        <input style={fieldStyle} name="name" placeholder="Your name" value={state.name}
          onFocus={onFieldFocus}
          onChange={(e) => setState({ ...state, name: e.target.value })} required />
        <input style={fieldStyle} name="email" type="email" placeholder="Work email" value={state.email}
          onFocus={onFieldFocus}
          onChange={(e) => setState({ ...state, email: e.target.value })} required />
        <button type="submit" disabled={state.sending} style={{
          fontFamily: FONTS.sans, fontWeight: 500, fontSize: 14, letterSpacing: -0.1,
          padding: stacked ? '15px 24px' : '13px 24px',
          background: BASEN.accent,
          color: BASEN.accentInk,
          border: 'none', borderRadius: 4, cursor: state.sending ? 'wait' : 'pointer',
          opacity: state.sending ? 0.7 : 1,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          transition: 'opacity 120ms ease',
        }}>
          {state.sending ? 'Sending…' : 'Talk to sales'}
          {!state.sending && <span>→</span>}
        </button>
      </form>
      {state.error && (
        <div style={{
          fontFamily: FONTS.sans, fontSize: 13, color: BASEN.signal,
          marginTop: 10, letterSpacing: -0.1,
        }}>{state.error}</div>
      )}
    </div>
  );
}

// ─── FAQ item ────────────────────────────────────────────────
function FAQItem({ q, a, defaultOpen = false, onDark = false }) {
  const [open, setOpen] = React.useState(defaultOpen);
  const ink = onDark ? BASEN.paper : BASEN.ink;
  const muted = onDark ? BASEN.mutedDark : BASEN.muted;
  const rule = onDark ? BASEN.ruleDark : BASEN.ruleSoft;
  return (
    <div style={{ borderTop: `1px solid ${rule}` }}>
      <button onClick={() => setOpen(!open)} style={{
        width: '100%', padding: '24px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: 'transparent', border: 'none', cursor: 'pointer', textAlign: 'left',
      }}>
        <span style={{
          fontFamily: FONTS.display, fontSize: 18, color: ink, fontWeight: 500, letterSpacing: -0.3,
        }}>{q}</span>
        <span style={{
          fontFamily: FONTS.sans, fontSize: 18, color: muted, lineHeight: 1,
          transform: open ? 'rotate(45deg)' : 'rotate(0)', transition: 'transform 180ms ease',
          display: 'inline-block', width: 24, textAlign: 'center', flexShrink: 0,
        }}>+</span>
      </button>
      {open && (
        <div style={{
          fontFamily: FONTS.sans, fontSize: 15, lineHeight: 1.65, color: muted,
          paddingBottom: 26, maxWidth: 760, letterSpacing: -0.1,
        }}>{a}</div>
      )}
    </div>
  );
}

const FAQ_ITEMS = [
  {
    q: 'How does it work without an API or integration?',
    a: "Sefra runs in a real browser and operates software the way a person does - logging in, clicking through menus, typing into fields, reading the screen. Because it works at the UI layer, it can automate legacy systems that have no API, no integration, and no modern way in.",
  },
  {
    q: 'What can trigger a run?',
    a: "An email you forward, a Slack message or slash command, a scheduled cron job, or a webhook from any system you already run. Sefra reads the request, does the task, and replies where the trigger came from with a confirmation.",
  },
  {
    q: 'Is this only for workers-comp claims systems?',
    a: "That's where we started and where we're sharpest - legacy claims portals and TPA back-office tools. But the agent works anywhere a person works in a browser: healthcare payer portals, carrier TMS systems, government filing sites, legacy ERPs. If it's old software someone clicks through, it's a fit.",
  },
  {
    q: 'What happens when the agent hits something unexpected?',
    a: "It doesn't guess. Sefra routes ambiguous or unusual cases to a human and keeps a full, replayable log of every step it took. You stay in control of the judgment calls while the repetitive work runs itself.",
  },
  {
    q: 'How do I try it?',
    a: "Start for free, point Sefra at one task, and watch it run before you pay anything. No setup project and no rip-and-replace - connect a login, kick it off, and see it work.",
  },
  {
    q: 'How is it priced?',
    a: "There's a free tier to get started. Paid plans are usage-based on the number of agent runs, with no per-seat fees and every plan on frontier models. Tell us about your workflows and we'll scope a plan that fits - book a quick call and we'll walk through it.",
  },
];

const HOW_STEPS = [
  {
    n: '01',
    eyebrow: 'Embed',
    title: 'An engineer deploys into your operation.',
    body: 'A Sefra forward-deployed engineer sits with your adjusters and managers, learns how claims actually move through your shop, and maps your systems, letter templates, and decision points firsthand. No discovery deck - they watch the real work.',
  },
  {
    n: '02',
    eyebrow: 'Build',
    title: 'Custom automation, built to your workflow.',
    body: "Instead of configuring a product, your engineer builds software around how your team already works - document intake, medical-report extraction, claim letters, bill review - starting with whatever is costing your adjusters the most time.",
  },
  {
    n: '03',
    eyebrow: 'Deploy',
    title: 'It runs inside the stack you already use.',
    body: 'What we build goes live in your existing claims system, with your templates and your rules, alongside your adjusters. Nothing about their day-to-day has to change, and every action stays audited.',
  },
  {
    n: '04',
    eyebrow: 'Iterate',
    title: 'Your engineer stays and keeps building.',
    body: "As your operation changes - new lines of business, new document types, new state rules - the same engineer keeps refining what's deployed. You get a partner who knows your shop, not a ticket queue.",
  },
];

// ─── Standalone bird mark (for ads, favicons, large display) ──
function BirdMark({ size = 64, color, style = {} }) {
  return (
    <svg
      viewBox="59 49 139 160"
      role="img"
      aria-label="Sefra"
      style={{ height: size, width: 'auto', display: 'block', ...style }}
    >
      <path d={SEFRA_BIRD_PATH} fill={color || BASEN.accent} fillRule="evenodd" />
    </svg>
  );
}

Object.assign(window, {
  BASEN, FONTS, useViewport,
  BasenLogo, BirdMark, SEFRA_BIRD_PATH, Eyebrow, Btn, TopNav, Footer,
  DemoForm, CalendlyInline, FAQItem, FAQ_ITEMS, HOW_STEPS,
});
