// PRODUCT STUDIO PAGE - /product-studio · "Built and live in days, not months"
// Copy source: James Hill's approved clean version (14 Nov 2026), replacing the
// Google Doc drafts. Step blocks follow the Camelot slide's three stages.
// Sits under For MGAs in the nav, and is also linked from For Brokers (same page).
//
// Launched Nov 2026: indexable, in sitemap.xml and llms.txt. The client quote
// section was dropped for launch (no confirmed quote); if one is confirmed,
// add a quote section back between How it works and FAQs.
//
// Section order:
//   1. Hero (+ launch video)
//   2. How Product Studio works (3 step blocks with timings)
//   3. FAQs
//   4. What it changes for your team (4 roles)
//   5. Closing CTA + booking form (#book)

const PS_FORM_ENDPOINT = 'https://formspree.io/f/mdajpovg'; // same Formspree form as /demo

const { EdCtx: PsCtx, EdTag: PsTag, EdBtn: PsBtn, EdSectionHead: PsSectionHead,
        EdChrome: PsChrome, useIsMobile: psUseIsMobile, TargetMark: PsTarget } = window;

function PsMarked({ children, mark, style, id }) {
  return (
    <section id={id} style={{ position: 'relative', overflow: 'hidden', ...style }}>
      {mark && <div style={{ position: 'absolute', inset: 0, zIndex: 0, pointerEvents: 'none' }}>{mark}</div>}
      <div style={{ position: 'relative', zIndex: 1 }}>{children}</div>
    </section>
  );
}

function PsPara({ children, max = 760, size }) {
  const ED = React.useContext(PsCtx);
  const isMobile = psUseIsMobile();
  return (
    <p style={{ ...ED.text.sans, fontSize: size || (isMobile ? 18 : 19), lineHeight: isMobile ? 1.6 : 1.65, color: ED.ink, margin: 0, maxWidth: max }}>
      {children}
    </p>
  );
}

// ─── 1. Hero ───────────────────────────────────────────────────

// Launch video (62s, 1080p H.264 + AAC music, captions burned in so it works
// with the sound off). The file is faststart (moov first) so playback can begin
// before it has fully downloaded; preload="metadata" keeps the 9 MB file off the
// initial page load. Absolute paths so the page works at any URL depth.
const PS_VIDEO = '/assets/video/product-studio-launch.mp4';
const PS_VIDEO_POSTER = '/assets/video/product-studio-launch-poster.jpg';

function PsVideoSlot({ caption }) {
  const ED = React.useContext(PsCtx);
  return (
    <figure id="demo-video" style={{ margin: 0 }}>
      <video
        controls
        playsInline
        preload="metadata"
        poster={PS_VIDEO_POSTER}
        width="1920"
        height="1080"
        aria-label="Introducing Outrun Product Studio (launch video, 62 seconds, captioned)"
        style={{ display: 'block', width: '100%', height: 'auto', aspectRatio: '16 / 9', background: ED.ink, border: `1px solid ${ED.rule}` }}
      >
        <source src={PS_VIDEO} type="video/mp4" />
        <a href={PS_VIDEO}>Watch the Product Studio launch video (MP4, 62 seconds)</a>
      </video>
      {caption && <figcaption style={{ ...ED.text.sans, fontSize: 14, color: ED.ink2, marginTop: 12 }}>{caption}</figcaption>}
    </figure>
  );
}

// Product Studio blue: the text-safe action blue from the brand guidelines,
// as used on the homepage Product Studio door (logo blue #3BA2DE is too light
// for text on white).
const PS_BLUE = '#1F74AD';

function PsHero() {
  const ED = React.useContext(PsCtx);
  const edText = ED.text;
  const isMobile = psUseIsMobile();
  // No target mark in this hero: the video is the visual (decided 16 Nov 2026).
  return (
    <PsMarked style={{ boxSizing: 'border-box', minHeight: isMobile ? 657 : 898, padding: isMobile ? '40px 24px 56px' : '72px 144px 112px', background: ED.bg }}>
      <h1 style={{ ...edText.display, fontSize: isMobile ? 'clamp(40px, 11vw, 46px)' : 119, lineHeight: isMobile ? 1.0 : 0.95, color: ED.ink, margin: 0, maxWidth: 1320, letterSpacing: '-0.04em' }}>
        <span style={{ ...edText.displayBold, color: PS_BLUE, fontStyle: 'normal' }}>Product Studio</span>.
      </h1>
      <p style={{ ...edText.sans, fontWeight: 500, fontSize: isMobile ? 18 : 29, lineHeight: isMobile ? 1.35 : 1.25, color: ED.ink, margin: isMobile ? '20px 0 0' : '24px 0 0', letterSpacing: '-0.015em', maxWidth: 1240 }}>
        Get your next product built and live in <span style={{ color: PS_BLUE, fontWeight: 600 }}>days, not months</span>.
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'minmax(0, 2fr) minmax(0, 3fr)', gap: isMobile ? 36 : 56, marginTop: isMobile ? 28 : 56, alignItems: isMobile ? 'start' : 'center' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: isMobile ? 20 : 28 }}>
          <p style={{ ...edText.sans, fontSize: isMobile ? 18 : 21, lineHeight: 1.5, color: ED.ink, margin: 0 }}>
            Product Studio builds your next product from your underwriting guide, workbooks and supporting documents, with no developer needed.
          </p>
          <p style={{ ...edText.sans, fontSize: isMobile ? 18 : 21, lineHeight: 1.5, color: ED.ink, margin: 0 }}>
            It drafts the full specification: pricing, referral, acceptance and endorsement rules. The underwriter reviews it and signs it off, and the product is built automatically.
          </p>
          <p style={{ ...edText.sans, fontSize: isMobile ? 18 : 21, lineHeight: 1.5, color: ED.ink, margin: 0 }}>
            The build is no longer the step that holds you up. As soon as the product is signed off, it&rsquo;s built and ready to trade.
          </p>
          <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', alignItems: isMobile ? 'stretch' : 'center', gap: isMobile ? 14 : 28 }}>
            <PsBtn kind="heroBlue" href="/demo">Book a demo</PsBtn>
          </div>
        </div>
        {/* Capped at 800px (about 720px on screen at the 0.9 desktop zoom) so it
            doesn't take over the hero on large monitors; anchored to the text
            column so the gap between text and video stays constant. */}
        <div style={isMobile ? undefined : { width: '100%', maxWidth: 800, justifySelf: 'start' }}>
          <PsVideoSlot />
        </div>
      </div>
    </PsMarked>
  );
}

// ─── 2. How it works ───────────────────────────────────────────
// Three boxes in the style of the Camelot slide (Oct 2026): existing
// resources feed step 1; "draft" and "signed off" hand-offs between steps;
// the underwriter's step is the emphasised box. Timings per the approved
// claims (14 Nov 2026).

function PsHow() {
  const ED = React.useContext(PsCtx);
  const edText = ED.text;
  const isMobile = psUseIsMobile();
  const GREY_SHADOW = '#C9CFD5';
  const inputs = ['Underwriting guide', 'Guidance notes', 'Workbook calculator', 'Lists & libraries', 'Templates'];
  const steps = [
    {
      title: 'Ingest, interpret and codify', who: 'Automated (AI)',
      points: [
        'Reads your product documents',
        'Codifies everything required for full product build: rules, groups, tables, fields & lists',
      ],
      figNote: <><strong style={{ fontWeight: 600, color: ED.ink }}>Around 15 minutes for a single-line product</strong>, such as professional indemnity (20-page underwriting guide).<span style={{ display: 'block', marginTop: 16 }}><strong style={{ fontWeight: 600, color: ED.ink }}>Around 45 minutes for a 15-section complex commercial combined product</strong> (100-page underwriting guide).</span></>,
    },
    {
      title: 'Review and refine', who: 'Underwriter /\noperations team', main: true,
      points: [
        'Review the complete product spec',
        'See exactly how the premium is built up from each rating factor',
        'Adjust rates and rating factors',
        'Add, edit or remove referral, endorsement and decline rules',
        'Sign off',
      ],
      figNote: <>As quick as the underwriter can review and sign off the spec, <strong style={{ fontWeight: 600, color: ED.ink }}>usually a day or two</strong>.</>,
    },
    {
      title: 'Publish and trade', who: 'Automated (non-AI)',
      points: [
        'Automatically builds the product',
        'Test the product with batch testing tools before it goes live',
      ],
      figNote: <>The automation takes around 10 minutes to build the product.<span style={{ display: 'block', marginTop: 8 }}><strong style={{ fontWeight: 600, color: ED.ink }}>No developer needed.</strong></span></>,
    },
  ];

  const box = (s) => (
    <li className="ps-step" style={{
      listStyle: 'none', boxSizing: 'border-box', background: ED.bg, display: 'flex', flexDirection: 'column',
      border: s.main ? `4px solid ${ED.ink}` : `2px solid ${PS_BLUE}`, borderRadius: 3,
      '--ps-hard-shadow': `8px 8px 0 ${s.main ? PS_BLUE : GREY_SHADOW}`,
      padding: isMobile ? '22px 20px 24px' : '24px 18px 26px',
      margin: isMobile ? '0 8px 0 0' : (s.main ? '-14px 0' : 0),
    }}>
      <h3 style={{ ...edText.sans, fontSize: isMobile ? 21 : 22, fontWeight: 600, color: PS_BLUE, lineHeight: 1.15, letterSpacing: '-0.01em', margin: 0 }}>{s.title}</h3>
      <span style={{ ...edText.sans, alignSelf: 'flex-start', background: PS_BLUE, color: '#FFFFFF', fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', whiteSpace: 'normal', padding: '5px 7px', borderRadius: 2, lineHeight: 1.2, marginTop: 18 }}>
        {s.who.split('\n').map((part, i) => (
          <React.Fragment key={i}>{i > 0 && ' '}<span style={{ whiteSpace: 'nowrap' }}>{part}</span></React.Fragment>
        ))}
      </span>
      <ul style={{ listStyle: 'none', padding: 0, margin: '24px 0 0', display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
        {s.points.map((p) => (
          <li key={p} style={{ display: 'grid', gridTemplateColumns: '16px minmax(0, 1fr)', columnGap: 4, ...edText.sans, fontSize: 16, lineHeight: 1.4, color: ED.ink }}>
            <span aria-hidden="true" style={{ fontWeight: 600 }}>+</span>
            <span>{p}</span>
          </li>
        ))}
      </ul>
      {s.figNote ? <div style={{ borderTop: `1px solid ${ED.rule}`, marginTop: 20, paddingTop: 16 }}>
        {s.fig ? (
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <span style={{ ...edText.display, fontSize: isMobile ? 48 : 52, lineHeight: 0.95, color: ED.ink, letterSpacing: '-0.04em' }}>{s.fig}</span>
            <span style={{ ...edText.med, fontSize: 17, color: ED.ink }}>{s.unit}</span>
          </div>
        ) : null}
        <p style={{ ...edText.sans, fontSize: 14, lineHeight: 1.5, color: ED.ink2, margin: s.fig ? '8px 0 0' : 0 }}>{s.figNote}</p>
      </div> : null}
    </li>
  );

  // Hand-off between steps: an arrow with its label ("draft", "signed off").
  const arrow = isMobile ? (
    <svg width="18" height="28" viewBox="0 0 18 28" style={{ display: 'block' }}>
      <line x1="9" y1="1" x2="9" y2="26" stroke={ED.ink} strokeWidth="2" strokeLinecap="round" />
      <polyline points="2,19 9,26 16,19" fill="none" stroke={ED.ink} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ) : (
    <svg width="44" height="18" viewBox="0 0 44 18" style={{ display: 'block' }}>
      <line x1="1" y1="9" x2="42" y2="9" stroke={ED.ink} strokeWidth="2" strokeLinecap="round" />
      <polyline points="35,2 42,9 35,16" fill="none" stroke={ED.ink} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
  const handoff = (label, Tag = 'li') => (
    <Tag aria-hidden="true" style={{ listStyle: 'none', display: 'flex', flexDirection: isMobile ? 'row' : 'column', alignItems: 'center', justifyContent: 'center', gap: isMobile ? 10 : 6, padding: isMobile ? '14px 0' : '0 0 0 10px' }}>
      {label ? <span style={{ ...edText.sans, fontSize: 15, fontStyle: 'italic', color: ED.ink2, whiteSpace: 'nowrap' }}>{label}</span> : null}
      {arrow}
    </Tag>
  );

  const resources = (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <div style={{ ...edText.sans, fontSize: 13, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: ED.ink2, lineHeight: 1.25 }}>Existing<br />resources</div>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: isMobile ? 'row' : 'column', flexWrap: 'wrap', gap: 8 }}>
        {inputs.map((i) => (
          <li key={i} style={{ ...edText.sans, fontSize: 15, color: ED.ink, border: `2px solid ${PS_BLUE}`, borderRadius: 3, padding: '7px 10px', background: ED.bg, whiteSpace: 'nowrap' }}>{i}</li>
        ))}
      </ul>
    </div>
  );

  return (
    <section style={{ padding: isMobile ? '56px 24px' : '96px 144px', background: ED.bgWarm, borderTop: `1px solid ${ED.rule}` }}>
      <PsSectionHead
        title={<>How <span style={{ ...edText.displayBold, color: PS_BLUE, fontStyle: 'normal' }}>Product Studio</span> works.</>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '170px 84px minmax(0, 1fr)', alignItems: 'center', gap: isMobile ? 8 : 0 }}>
        {resources}
        {handoff('', 'div')}
        {/* Hover lift: same treatment as the homepage doors (.ed-door). */}
        <style>{`
          .ps-step { box-shadow: var(--ps-hard-shadow); transition: transform 180ms ease, box-shadow 180ms ease; }
          .ps-step:hover { transform: translateY(-4px); box-shadow: var(--ps-hard-shadow), 0 22px 44px rgba(55,71,79,0.20); }
          @media (prefers-reduced-motion: reduce) { .ps-step, .ps-step:hover { transform: none; transition: none; } }
        `}</style>
        <ol style={{ padding: 0, margin: 0, display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'minmax(0, 1fr) 92px minmax(0, 1fr) 92px minmax(0, 1fr)', alignItems: 'stretch' }}>
          {box(steps[0])}
          {handoff('draft')}
          {box(steps[1])}
          {handoff('signed off')}
          {box(steps[2])}
        </ol>
      </div>
    </section>
  );
}

// ─── 5. What it changes for your team ──────────────────────────

function PsRoles() {
  const ED = React.useContext(PsCtx);
  const edText = ED.text;
  const isMobile = psUseIsMobile();
  const roles = [
    { who: 'MGA founders and CEOs', body: <>Act on an opportunity while it&rsquo;s still there, and start writing business sooner.</> },
    { who: 'Underwriters', body: <>Product Studio drafts, you decide. Nothing is built without your sign-off.</> },
    { who: 'Operations', body: <>One set of rules in one place, not a workbook and a list of exceptions.</> },
    { who: 'Capacity providers', body: <>The product quotes the way the agreed guide says, every time, and you can share a readable specification showing exactly how the guide has been implemented.</> },
  ];
  return (
    <section style={{ padding: isMobile ? '56px 24px' : '96px 144px', background: ED.bg }}>
      <PsSectionHead
        title={<>What it changes for <span style={{ ...edText.displayBold, color: ED.red, fontStyle: 'normal' }}>your team</span>.</>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: isMobile ? 12 : 16 }}>
        {roles.map((r) => (
          <div key={r.who} style={{ border: `1.5px solid ${ED.ink}`, padding: isMobile ? '24px 22px 26px' : '36px 40px 40px', background: ED.bg }}>
            <h3 style={{ ...edText.display, fontSize: isMobile ? 26 : 34, color: ED.ink, margin: 0, letterSpacing: '-0.025em', lineHeight: 1.1 }}>{r.who}</h3>
            <p style={{ ...edText.sans, fontSize: isMobile ? 16.5 : 17, lineHeight: 1.6, color: ED.ink, margin: isMobile ? '14px 0 0' : '20px 0 0' }}>{r.body}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── 6. FAQs ───────────────────────────────────────────────────

const PS_FAQS = [
  { q: 'How long does it take to get a product live?', a: <><p style={{ margin: 0 }}>For a single-line product, such as professional indemnity with a 20-page underwriting guide, Product Studio produces the first pass in around 15 minutes. For a 15-section complex commercial combined product with a 100-page underwriting guide, it takes around 45 minutes. The underwriter then reviews it, makes any changes and decides any flagged questions. That&rsquo;s usually a day or two, depending mostly on how complete the guide is. Once it&rsquo;s signed off, the product is built automatically in around 10 minutes. Your insurer approves the product as they do now. You test it with batch testing tools before it goes live, and documents follow your usual process. The build itself is no longer the step that holds you up.</p></> },
  { q: 'Which classes of business does it handle?', a: <><p style={{ margin: 0 }}>Any. That covers single-line products such as professional indemnity through to complex commercial combined products with many sections of cover. If you have an underwriting guide, rating tables and referral rules, Product Studio can work with them.</p></> },
  { q: 'How accurate is the first pass?', a: <><p style={{ margin: 0 }}>It&rsquo;s a detailed first pass, not a finished product. Product Studio drafts the pricing, referral, acceptance and endorsement rules from your guide and supporting documents. Where the guide is ambiguous or silent, it flags the question rather than guessing. Typical examples are whether discounts are added together or applied one after another, or a referral trigger with no threshold. The underwriter checks every rule and answers every flagged question before anything is built.</p></> },
  { q: 'Does Product Studio use AI?', a: <><p style={{ margin: 0 }}>Yes, to read your guide and draft the rules. That&rsquo;s the slow, manual step it replaces. The build itself doesn&rsquo;t rely on AI. Once the underwriter has signed off the specification, Product Studio builds exactly what was approved, rule by rule and table by table, in Polaris ProductWriter. AI doesn&rsquo;t make underwriting decisions at any point.</p></> },
  { q: 'Does Product Studio replace the underwriter?', a: <><p style={{ margin: 0 }}>No. It replaces the drafting, not the judgement. Today an underwriter&rsquo;s time on a new product build goes on explaining the guide, answering questions and checking someone else&rsquo;s interpretation of it. With Product Studio, that time goes on the decisions only an underwriter can make: settling the flagged questions, making changes and signing off.</p></> },
  { q: 'Who’s accountable for the rules?', a: <><p style={{ margin: 0 }}>You are, as you are today. Product Studio drafts, and the underwriter approves. Nothing is built until the specification is signed off, and the product follows exactly what was approved.</p></> },
  { q: 'Will our insurer accept a product built this way?', a: <><p style={{ margin: 0 }}>Your insurer approves the product as they do today. The difference is what they see. Product Studio produces a detailed specification that sets out how your underwriting guide has been implemented in the system, rule by rule. You can share it with your insurer as a readable document, so they can check the product does what the guide says before it goes live. The product is built in Polaris ProductWriter, the industry-owned rating engine many insurers already know.</p></> },
  { q: 'Who maintains the product once it’s live?', a: <><p style={{ margin: 0 }}>The underwriter can, without needing a developer. Changes to rates, rules and endorsements can be made either directly or through Product Studio. Because the product is built in Polaris ProductWriter, the industry-owned rating engine, your rating, rules and endorsements stay yours and stay portable.</p></> },
  { q: 'Our Excel workbook works fine. Why change?', a: <>
    <p style={{ margin: 0 }}>For many MGAs, an Excel rating workbook was the quickest route to market. It meant you could start trading without waiting months for a system build, and that was a sensible choice. But it has costs:</p>
    <ul style={{ margin: '12px 0', paddingLeft: 20 }}>
      <li>The rules often live in one person&rsquo;s head and one file.</li>
      <li>Brokers can&rsquo;t quote for themselves, so your team rekeys.</li>
      <li>Version control and audit trails depend on discipline.</li>
      <li>Your capacity provider may not be comfortable with a product rated in a spreadsheet.</li>
    </ul>
    <p style={{ margin: 0 }}>Excel is no longer the quickest route. With Product Studio, a product built properly, with brokers quoting directly and the rules in one place, can be live in days.</p>
  </> },
];

function PsFaqItem({ q, a }) {
  const ED = React.useContext(PsCtx);
  const edText = ED.text;
  const isMobile = psUseIsMobile();
  const [open, setOpen] = React.useState(false);
  return (
    <details open={open} onToggle={(e) => setOpen(e.currentTarget.open)} style={{ borderTop: `1px solid ${ED.rule}` }}>
      <summary style={{ listStyle: 'none', cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 24, padding: isMobile ? '20px 0' : '26px 0' }}>
        <span style={{ ...edText.med, fontSize: isMobile ? 18 : 20, color: ED.ink, letterSpacing: '-0.01em', lineHeight: 1.35 }}>{q}</span>
        <span aria-hidden="true" style={{ color: ED.red, fontWeight: 700, fontSize: 22, lineHeight: 1, flex: '0 0 auto', transform: open ? 'rotate(45deg)' : 'none', transition: 'transform 140ms ease' }}>+</span>
      </summary>
      <div style={{ ...edText.sans, fontSize: isMobile ? 16.5 : 17, lineHeight: 1.65, color: ED.ink, margin: 0, padding: isMobile ? '0 0 22px' : '0 48px 28px 0', maxWidth: 860 }}>{a}</div>
    </details>
  );
}

function PsFaqs() {
  const ED = React.useContext(PsCtx);
  const edText = ED.text;
  const isMobile = psUseIsMobile();
  return (
    <section style={{ padding: isMobile ? '56px 24px' : '96px 144px', background: ED.bg }}>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '320px 1fr', gap: isMobile ? 8 : 80, alignItems: 'start' }}>
        <div>
          <h2 style={{ ...edText.display, fontSize: isMobile ? 'clamp(34px, 9.5vw, 38px)' : 56, lineHeight: 1.05, color: ED.ink, margin: isMobile ? '0 0 24px' : 0, letterSpacing: '-0.03em' }}>
            Questions and <span style={{ ...edText.displayBold, color: ED.red, fontStyle: 'normal' }}>answers</span>.
          </h2>
        </div>
        <div style={{ borderBottom: `1px solid ${ED.rule}` }}>
          {PS_FAQS.map((f) => <PsFaqItem key={f.q} q={f.q} a={f.a} />)}
        </div>
      </div>
    </section>
  );
}

// ─── 7. Closing CTA + booking form ─────────────────────────────

function PsInput({ id, label, required, type = 'text', value, onChange, placeholder, autoComplete }) {
  const ED = React.useContext(PsCtx);
  const edText = ED.text;
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <label htmlFor={id} style={{ ...edText.tag, fontSize: 11, color: ED.ink2, marginBottom: 8 }}>
        {label}{required && <span style={{ color: ED.red, marginLeft: 4 }}>*</span>}
      </label>
      <input id={id} name={id} type={type} required={required} value={value} placeholder={placeholder} autoComplete={autoComplete}
        onChange={(e) => onChange(e.target.value)}
        style={{ ...edText.sans, fontSize: 17, color: ED.ink, padding: '14px 16px', borderRadius: 2, border: `1px solid ${ED.rule}`, background: ED.bg, outline: 'none', width: '100%', boxSizing: 'border-box' }} />
    </div>
  );
}

function PsForm() {
  const ED = React.useContext(PsCtx);
  const edText = ED.text;
  const isMobile = psUseIsMobile();
  const [f, setF] = React.useState({ name: '', email: '', company: '', role: '', product: '' });
  const [state, setState] = React.useState('idle'); // idle | sending | done
  const [error, setError] = React.useState('');
  const set = (k) => (v) => setF((p) => ({ ...p, [k]: v }));

  async function submit(e) {
    e.preventDefault();
    setError('');
    if (!f.name.trim() || !f.email.trim() || !f.company.trim() || !f.role) {
      setError('Please add your name, work email, company and role.');
      return;
    }
    setState('sending');
    try {
      const fd = new FormData();
      Object.entries(f).forEach(([k, v]) => fd.append(k, v));
      fd.append('formType', 'product-studio');
      fd.append('_subject', `Product Studio conversation - ${f.name} (${f.company})`);
      const r = await fetch(PS_FORM_ENDPOINT, { method: 'POST', headers: { Accept: 'application/json' }, body: fd });
      if (!r.ok) throw new Error('failed');
      (window.dataLayer = window.dataLayer || []).push({ event: 'product_studio_booking_submitted' });
      setState('done');
    } catch (err) {
      setError('Something went wrong. Please try again, or email james.hill@outrun.insure directly.');
      setState('idle');
    }
  }

  if (state === 'done') {
    return (
      <div style={{ border: `1.5px solid ${ED.ink}`, padding: isMobile ? '28px 22px' : '40px 44px', background: ED.bg }}>
        <h3 style={{ ...edText.display, fontSize: isMobile ? 28 : 40, color: ED.ink, margin: 0, letterSpacing: '-0.025em' }}>Thanks - we&rsquo;ll be in touch.</h3>
        <p style={{ ...edText.sans, fontSize: 17, lineHeight: 1.6, color: ED.ink, margin: '14px 0 0' }}>We&rsquo;ll come back to you within one working day to arrange a time.</p>
      </div>
    );
  }

  return (
    <form onSubmit={submit} noValidate style={{ border: `1.5px solid ${ED.ink}`, padding: isMobile ? '24px 20px' : '36px 40px', background: ED.bg, display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 20 }}>
        <PsInput id="name" label="Name" required value={f.name} onChange={set('name')} autoComplete="name" />
        <PsInput id="email" label="Work email" type="email" required value={f.email} onChange={set('email')} autoComplete="email" />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 20 }}>
        <PsInput id="company" label="Company" required value={f.company} onChange={set('company')} autoComplete="organization" />
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <label htmlFor="role" style={{ ...edText.tag, fontSize: 11, color: ED.ink2, marginBottom: 8 }}>Role<span style={{ color: ED.red, marginLeft: 4 }}>*</span></label>
          <select id="role" name="role" required value={f.role} onChange={(e) => set('role')(e.target.value)}
            style={{ ...edText.sans, fontSize: 17, color: f.role ? ED.ink : ED.ink2, padding: '14px 16px', borderRadius: 2, border: `1px solid ${ED.rule}`, background: ED.bg, width: '100%', boxSizing: 'border-box' }}>
            <option value="" disabled>Choose one</option>
            {['MGA leadership', 'Underwriting', 'Operations', 'Capacity provider', 'Other'].map((o) => <option key={o} value={o}>{o}</option>)}
          </select>
        </div>
      </div>
      <PsInput id="product" label="The product you want live next (optional)" value={f.product} onChange={set('product')} placeholder="e.g. a commercial combined scheme for a niche trade" />
      {error && <div style={{ ...edText.sans, fontSize: 15, color: ED.red, padding: '12px 16px', border: `1px solid ${ED.red}` }}>{error}</div>}
      <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', justifyContent: 'space-between', alignItems: isMobile ? 'stretch' : 'center', gap: 16 }}>
        <p style={{ ...edText.sans, fontSize: 13, lineHeight: 1.5, color: ED.ink2, margin: 0, maxWidth: 380 }}>
          We&rsquo;ll only use these details to arrange the conversation. See our <a href="/privacy" style={{ color: ED.ink2 }}>privacy policy</a>.
        </p>
        <button type="submit" disabled={state === 'sending'} style={{ ...edText.med, fontSize: 15, padding: '14px 22px', borderRadius: 4, border: `1px solid ${ED.ink}`, background: ED.ink, color: ED.inverse, cursor: 'pointer', whiteSpace: 'nowrap' }}>
          {state === 'sending' ? 'Sending…' : <>Book a conversation <span aria-hidden="true">→</span></>}
        </button>
      </div>
    </form>
  );
}

function PsCta() {
  const ED = React.useContext(PsCtx);
  const edText = ED.text;
  const isMobile = psUseIsMobile();
  // Event version: links from the stand QR code / follow-up emails add ?event=mga-outlook
  const isEvent = typeof window !== 'undefined' && new URLSearchParams(window.location.search).get('event') === 'mga-outlook';
  const mark = !isMobile && (
    <PsTarget size={560} place={{ right: -200, bottom: -160 }} state="resolved" crosshair rings={[0.94, 0.76, 0.58, 0.4]} redRing={0.26} dotR={12} baseOpacity={0.5} />
  );
  return (
    <PsMarked id="book" style={{ padding: isMobile ? '56px 24px 72px' : '120px 144px', background: ED.bgWarm, borderTop: `1px solid ${ED.rule}` }} mark={mark}>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'minmax(0, 0.9fr) minmax(0, 1.1fr)', gap: isMobile ? 32 : 80, alignItems: 'start' }}>
        <div>
          <h2 style={{ ...edText.display, fontSize: isMobile ? 'clamp(34px, 9.5vw, 38px)' : 72, lineHeight: isMobile ? 1.05 : 1.0, color: ED.ink, margin: 0, letterSpacing: '-0.035em' }}>
            {isEvent
              ? <>Good to meet you at <span style={{ ...edText.displayBold, color: ED.red, fontStyle: 'normal' }}>MGA Outlook Europe</span>.</>
              : <>Have a guide waiting to become a <span style={{ ...edText.displayBold, color: ED.red, fontStyle: 'normal' }}>product</span>?</>}
          </h2>
          <p style={{ ...edText.sans, fontSize: isMobile ? 18 : 19, lineHeight: 1.6, color: ED.ink, margin: isMobile ? '20px 0 0' : '32px 0 0', maxWidth: 520 }}>
            {isEvent
              ? <>Book your follow-up conversation here.</>
              : <>Book 30 minutes and see Product Studio work on a guide like yours.</>}
          </p>
        </div>
        <PsForm />
      </div>
    </PsMarked>
  );
}

// ─── root ──────────────────────────────────────────────────────

function ProductStudioSite({ accent, fontMode = 'serif' }) {
  return (
    <PsChrome accent={accent} fontMode={fontMode} current="/product-studio">
      <PsHero />
      <PsHow />
      <PsFaqs />
      <PsRoles />
      <PsCta />
    </PsChrome>
  );
}

Object.assign(window, { ProductStudioSite });
