/* ============================================================
   The three deep pages behind the landing:
     /evidence  — every case with its five-question verdict
     /verify    — the method, in the two registers at once
     /limits    — what we cannot do, with the numbers
   ============================================================ */

function PageHead({ eyebrow, title, lead }) {
  return (
    <section className="relative overflow-hidden">
      <div className="mx-auto max-w-[1280px] px-8 lg:px-16 pt-16 sm:pt-20 pb-12">
        <Eyebrow>{eyebrow}</Eyebrow>
        <h1 className="mt-4 display text-ink" style={{ fontSize: 'clamp(34px, 4.8vw, 58px)' }}>
          {title}
        </h1>
        <p className="mt-6 text-[16px] sm:text-[17px] text-mute leading-relaxed max-w-[720px]">{lead}</p>
      </div>
    </section>
  );
}

/* ---------------------------------------------------------------- */

/* ---------------------------------------------------------------
   THE CASE, ON ONE SCREEN (Mo, 16.09.). The film carries the story
   and the only headline on this page; this column carries the few
   numbers that matter, each with an icon instead of a sentence. It
   must fit without scrolling, so every line here earns its place.  */
const CaseIcon = {
  Voice: ({ className = '' }) => (
    <svg viewBox="0 0 24 24" className={className} fill="none" aria-hidden="true">
      <path d="M4 5h16v11H9l-5 4V5z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/>
    </svg>
  ),
  Link: ({ className = '' }) => (
    <svg viewBox="0 0 24 24" className={className} fill="none" aria-hidden="true">
      <path d="M10 13a4 4 0 0 0 6 .5l2-2a4 4 0 0 0-5.7-5.7l-1 1" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
      <path d="M14 11a4 4 0 0 0-6-.5l-2 2A4 4 0 0 0 11.7 18l1-1" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
    </svg>
  ),
};

function RoleTag({ children }) {
  return (
    <span className="mono text-[9.5px] rounded-full px-2.5 py-1 inline-block"
      style={{
        background: 'rgba(34,211,238,0.12)', color: '#0891B2',
        border: '1px solid rgba(34,211,238,0.35)', letterSpacing: '0.16em',
      }}>
      {children}
    </span>
  );
}

function CaseFigure({ icon, v, k }) {
  const I = icon;
  return (
    <div className="rounded-lg px-3 py-2" style={{ boxShadow: 'inset 0 0 0 1px rgb(var(--c-line))' }}>
      <div className="flex items-center gap-1.5">
        <I className="w-[14px] h-[14px] text-mute shrink-0"/>
        <span className="text-[19px] font-semibold tracking-[-0.02em] leading-none">{v}</span>
      </div>
      <div className="mt-1 text-[11px] text-mute leading-tight">{k}</div>
    </div>
  );
}

function CaseResult({ r }) {
  return (
    <div className="py-1.5 border-t border-line">
      <div className="flex items-baseline gap-2.5">
        <span className="text-[16px] font-semibold tracking-[-0.02em] shrink-0 w-[78px]"
          style={{ color: '#06B6D4' }}>{r.v}</span>
        <span className="text-[12.5px] font-medium leading-snug">{r.b}</span>
      </div>
      <div className="mt-0.5 pl-[88px] text-[11.5px] text-mute leading-snug">
        after {r.t} · {r.s}
      </div>
    </div>
  );
}

/* The five checks, in place — a dialog, not a second page. */
function CheckDialog({ onClose }) {
  const { FIVE } = window.GD;
  React.useEffect(() => {
    const esc = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', esc);
    return () => window.removeEventListener('keydown', esc);
  }, [onClose]);
  return (
    <div className="fixed inset-0 z-50 grid place-items-center p-6"
      style={{ background: 'rgba(10,10,11,0.55)' }} onClick={onClose}>
      <div role="dialog" aria-modal="true" onClick={e => e.stopPropagation()}
        className="w-full max-w-[600px] max-h-[82vh] overflow-y-auto rounded-2xl bg-paper p-7"
        style={{ boxShadow: '0 24px 60px rgba(0,0,0,0.28)' }}>
        <div className="flex items-start justify-between gap-4">
          <h3 className="text-[20px] font-semibold tracking-[-0.02em]">
            Before a finding may be shown, it has to survive five questions.
          </h3>
          <button type="button" onClick={onClose} aria-label="Close"
            className="mono text-[11px] text-mute hover:text-ink shrink-0">ESC</button>
        </div>
        <ul className="mt-5 space-y-3">
          {FIVE.map(f => (
            <li key={f.id} className="flex items-baseline gap-3">
              <span className="mono text-[9.5px] text-mute shrink-0 w-[76px]">{f.q}</span>
              <span className="text-[14px] leading-snug">{f.ask}</span>
            </li>
          ))}
        </ul>
        <p className="mt-6 pt-5 border-t border-line text-[13px] text-mute leading-relaxed">
          Ten dated events went through it. Four came through, three left an indication, two moved
          nothing at all, one was too small to judge — and all four kinds are published.
        </p>
      </div>
    </div>
  );
}

function CaseAutomotivePage() {
  const { CASE_AUTO, CONTACT } = window.GD;
  const [checks, setChecks] = React.useState(false);
  const figures = [
    { icon: CaseIcon.Voice, v: CASE_AUTO.kpis[0].v, k: 'customer reviews' },
    { icon: Icon.Car, v: CASE_AUTO.kpis[1].v, k: 'dealerships' },
    { icon: Icon.Settings, v: CASE_AUTO.kpis[2].v, k: 'causes you can steer' },
    { icon: CaseIcon.Link, v: CASE_AUTO.kpis[3].v, k: 'of relationships hold' },
  ];

  return (
    <Page fill>
      <div className="mx-auto w-full max-w-[1600px] h-full px-6 lg:px-10 py-4 flex flex-col gap-3">
        <header className="shrink-0">
          <Eyebrow>CASE STUDY · AUTOMOTIVE AFTER-SALES</Eyebrow>
          <h1 className="mt-1 font-semibold tracking-[-0.022em] leading-[1.06]"
            style={{ fontSize: 'clamp(24px, 2.3vw, 33px)' }}>
            We read what customers write —{' '}
            <span className="grad-word">and find the causes you can steer.</span>
          </h1>
          <p className="mt-1.5 text-[14.5px] sm:text-[15px] text-mute leading-snug max-w-[110ch]">
            Public reviews from car dealerships, put through our causal AI pipeline — and one measure
            followed from the workshop floor all the way to the money.
          </p>
        </header>

        <div className="flex-1 min-h-0 grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_400px] gap-6">
          <div className="min-h-[520px] xl:min-h-0">
            <CaseFilm/>
          </div>

          <aside className="flex flex-col gap-4 min-h-0 overflow-y-auto no-scrollbar">
            <div>
              <div className="flex items-center gap-2.5">
                <RoleTag>WHAT</RoleTag>
                <span className="text-[13.5px] font-medium leading-snug">
                  The data set we analysed
                </span>
              </div>
              <div className="mt-2 grid grid-cols-2 gap-2">
                {figures.map(f => <CaseFigure key={f.k} {...f}/>)}
              </div>
              <p className="mt-2 text-[11.5px] text-mute leading-snug">
                Public reviews · 7 brands, 14 markets · names removed first.
              </p>
            </div>

            <div>
              <div className="flex items-center gap-2.5">
                <RoleTag>WHY</RoleTag>
                <span className="text-[13.5px] font-medium leading-snug">
                  These are the results
                </span>
              </div>
              <div className="mt-1.5">
                {CASE_AUTO.results.map(r => <CaseResult key={r.t} r={r}/>)}
              </div>
            </div>

            <div className="flex flex-wrap items-center gap-3">
              <a href={CONTACT}
                className="rounded-full bg-ink text-paper hover:bg-ink/90 px-5 py-2.5 text-[13.5px] font-medium inline-flex items-center gap-2 transition-colors">
                Get in touch <Icon.Arrow className="w-4 h-4"/>
              </a>
              <button type="button" onClick={() => setChecks(true)}
                className="mono text-[9.5px] text-mute hover:text-ink transition-colors">
                HOW WE CHECKED THIS
              </button>
            </div>
          </aside>
        </div>
      </div>
      {checks && <CheckDialog onClose={() => setChecks(false)}/>}
    </Page>
  );
}


function VerifyPage() {
  const { FIVE } = window.GD;
  return (
    <Page>
      <PageHead
        eyebrow="HOW WE VERIFY"
        title={<>We try to <em className="grad-word">disprove</em> our own findings. Five times.</>}
        lead="A child should understand every visible sentence; a data scientist should find nothing to take apart. The two registers say the same thing here — the simple version may simplify, never overstate."
      />

      <Section id="frame">
        <div className="rounded-2xl border border-line bg-off p-7 sm:p-10 max-w-[900px]">
          <Eyebrow>THE FRAME, IN ONE PARAGRAPH</Eyebrow>
          <p className="mt-4 text-[17px] sm:text-[19px] leading-relaxed">
            We measure the way a natural experiment works: sites where something happened,
            against comparable sites where nothing happened — same brand, same market, same
            quarter. Then we try to disprove the result five times over. Does the difference
            count? Could it have been luck? Are we measuring something else, or ourselves?
            Does it show up more than once? Do we understand why?{' '}
            <span className="font-medium">What survives that, we call a demonstrated effect.</span>
          </p>
        </div>
      </Section>

      <Section id="five" tone="off">
        <div className="max-w-3xl">
          <Eyebrow>THE FIVE QUESTIONS</Eyebrow>
          <h2 className="mt-3 text-[30px] sm:text-[38px] font-semibold tracking-[-0.022em] leading-[1.08]">
            Each one can fail a finding on its own.
          </h2>
        </div>
        <div className="mt-10 space-y-4">
          {FIVE.map((f, i) => (
            <div key={f.id} className="rounded-2xl border border-line bg-paper p-6 sm:p-7 grid grid-cols-1 lg:grid-cols-12 gap-6">
              <div className="lg:col-span-4">
                <div className="mono text-[9.5px] text-cyan">{String(i + 1).padStart(2, '0')} · {f.q}</div>
                <div className="mt-3 text-[19px] font-semibold tracking-tight leading-snug">{f.ask}</div>
              </div>
              <div className="lg:col-span-8">
                <p className="text-[14px] text-mute leading-relaxed">{f.detail}</p>
                <p className="mt-4 text-[13.5px] leading-relaxed rounded-lg px-4 py-3"
                  style={{ background: 'rgba(34,211,238,0.07)', color: 'rgb(var(--c-ink))' }}>
                  <span className="mono text-[9px] text-mute mr-2">EXAMPLE</span>{f.example}
                </p>
              </div>
            </div>
          ))}
        </div>
      </Section>

      <Section id="ladder">
        <div className="max-w-3xl">
          <Eyebrow>THE LADDER</Eyebrow>
          <h2 className="mt-3 text-[30px] sm:text-[38px] font-semibold tracking-[-0.022em] leading-[1.08]">
            Four rungs. Never one higher than earned.
          </h2>
          <p className="mt-5 text-[15px] text-mute leading-relaxed">
            Every result is placed on exactly one of these, in the demo, in a report and in
            a sales conversation. The wording is fixed, so nobody has to guess how strong a
            statement is meant to be.
          </p>
        </div>
        <div className="mt-9"><LadderViz/></div>
      </Section>

      <Section id="lab" tone="off">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
          <div className="lg:col-span-4">
            <Eyebrow>THE OBVIOUS OBJECTION</Eyebrow>
            <h2 className="mt-3 text-[26px] font-semibold tracking-[-0.02em] leading-snug">
              “Is this proven the way a laboratory proves things?”
            </h2>
          </div>
          <div className="lg:col-span-8">
            <p className="text-[15px] leading-relaxed">
              No — and we do not claim it is. In a laboratory you randomise the treatment;
              nobody can randomise which dealerships rebuild their premises. So we randomise
              the test instead: the same finding is recomputed in hundreds of random cohorts
              without the event, one year before the event, without the reviews that mention
              the event itself, and in other countries. A false finding fails one of those
              — and ours did: two measures came back with nothing, and one case failed to
              replicate abroad. Where the outside world keeps a register, we check ourselves
              against it: an official recall wave shows up in our data at the predicted
              dose. This is not a laboratory. It is what a court would call a chain of
              evidence, with the thresholds written down.
            </p>
          </div>
        </div>
      </Section>
    </Page>
  );
}

/* ---------------------------------------------------------------- */

function LimitsPage() {
  const { LIMITS, EXPLAIN } = window.GD;
  return (
    <Page>
      <PageHead
        eyebrow="WHAT WE CANNOT DO"
        title={<>State the edge, <em className="grad-word">earn the middle.</em></>}
        lead="This page exists because almost nobody can name these numbers, and most people do not know they exist. Whoever states the limit of their model has also told you where to trust it."
      />

      <Section id="limits-list">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {LIMITS.map((l, i) => (
            <div key={l.t} className="rounded-2xl border border-line bg-paper p-6 sm:p-7">
              <div className="mono text-[9.5px] text-mute">LIMIT {String(i + 1).padStart(2, '0')}</div>
              <h2 className="mt-3 text-[18px] font-semibold tracking-tight leading-snug">{l.t}</h2>
              <p className="mt-3 text-[13.5px] text-mute leading-relaxed">{l.b}</p>
            </div>
          ))}
        </div>
      </Section>

      <Section id="explain" tone="off">
        <div className="max-w-3xl">
          <Eyebrow>THE NUMBER ALMOST NOBODY PUBLISHES</Eyebrow>
          <h2 className="mt-3 text-[30px] sm:text-[38px] font-semibold tracking-[-0.022em] leading-[1.08]">
            How much of what happens is explainable at all?
          </h2>
          <p className="mt-5 text-[15px] text-mute leading-relaxed">{EXPLAIN.intro}</p>
        </div>

        <div className="mt-10 rounded-2xl border border-line bg-paper overflow-hidden">
          <div className="px-6 py-4 border-b border-line grid grid-cols-12 gap-4">
            <span className="col-span-6 sm:col-span-4 mono text-[9.5px] text-mute">OUTCOME</span>
            <span className="col-span-6 sm:col-span-2 mono text-[9.5px] text-mute">CEILING</span>
            <span className="hidden sm:block sm:col-span-6 mono text-[9.5px] text-mute">WHY IT IS NOT 100%</span>
          </div>
          {EXPLAIN.rows.map(([t, ceil, why]) => (
            <div key={t} className="px-6 py-4 border-b border-line last:border-b-0 grid grid-cols-12 gap-4 items-center">
              <span className="col-span-6 sm:col-span-4 text-[13.5px]">{t}</span>
              <span className="col-span-6 sm:col-span-2 text-[19px] font-semibold tracking-tight">{ceil}</span>
              <span className="col-span-12 sm:col-span-6 text-[12.5px] text-mute leading-relaxed">{why}</span>
            </div>
          ))}
        </div>
        <p className="mt-4 text-[12.5px] text-mute max-w-3xl leading-relaxed">
          Read every explainability figure against that ceiling, never against 100%. Half to
          three quarters of quarter-to-quarter movement is sampling noise — no model should
          explain it, and none can.
        </p>

        <div className="mt-10 grid grid-cols-1 md:grid-cols-2 gap-4">
          {EXPLAIN.claims.map(([n, b], i) => (
            <div key={i} className="rounded-2xl border border-line bg-paper p-6">
              <div className="text-[30px] font-semibold tracking-[-0.03em]">{n}</div>
              <p className="mt-3 text-[13.5px] text-mute leading-relaxed">{b}</p>
            </div>
          ))}
        </div>
      </Section>

      <Section id="why-this-helps">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
          <div className="lg:col-span-4">
            <Eyebrow>WHY THIS IS AN ARGUMENT</Eyebrow>
            <h2 className="mt-3 text-[26px] font-semibold tracking-[-0.02em] leading-snug">
              A product that closes its own data gap.
            </h2>
          </div>
          <div className="lg:col-span-8">
            <p className="text-[15px] leading-relaxed">
              Under 1% of the movement traces back to measures we can name today. That is not
              a verdict on the measures — the demonstrated ones work — it is a statement about
              visibility: we only see what leaves a trace in what customers write. Every
              measure a customer records in the loop moves from invisible medication into the
              tested catalogue. The number on this page is the one we expect to change, and
              we would rather you watch it move than never have seen it.
            </p>
            <div className="mt-8 flex flex-wrap gap-3">
              <a href="#/evidence" className="rounded-full border border-line hover:border-ink/40 px-6 py-3 text-[14px] text-ink transition-colors">
                See what does hold
              </a>
              <a href={window.GD.CONTACT} className="rounded-full bg-ink text-paper hover:bg-ink/90 px-6 py-3 text-[14px] font-medium inline-flex items-center gap-2 transition-colors">
                Get in touch <Icon.Arrow className="w-4 h-4"/>
              </a>
            </div>
          </div>
        </div>
      </Section>
    </Page>
  );
}

/* ---------------------------------------------------------------- */

window.CaseAutomotivePage = CaseAutomotivePage;
window.VerifyPage = VerifyPage;
window.LimitsPage = LimitsPage;
