/* Atlas detail — Premium Automotive Aftersales (replaces old Findings) */
const { useState: adUseState, useEffect: adUseEffect, useRef: adUseRef } = React;

const ATLAS_DETAIL_DEFAULTS = /*EDITMODE-BEGIN*/{
  "totalDuration": 45,
  "stage1End": 4,
  "stage2End": 11,
  "stage3End": 17,
  "stage4End": 26,
  "stage5End": 34,
  "stage6End": 45,
  "animOpacity": 100,
  "paused": false
}/*EDITMODE-END*/;

/* Stage meter — minimalist Apple-style step indicator that lives inside the
   animation panel header. Numbers across the top, hairline progress fills
   cyan as the animation advances, active step's title + plain-language
   explainer sit below. Self-syncs to HeroAnimation via its own time loop
   keyed to the same totalDuration. */
function StageMeter({ stages, totalDuration, paused }) {
  const [stage, setStage] = adUseState(0);
  const startRef = adUseRef(typeof performance !== 'undefined' ? performance.now() : 0);

  adUseEffect(() => {
    if (paused) return;
    let raf = 0;
    let mounted = true;
    startRef.current = performance.now();
    const tick = (now) => {
      if (!mounted) return;
      let elapsed = (now - startRef.current) / 1000;
      if (elapsed >= totalDuration) {
        startRef.current = now;
        elapsed = 0;
      }
      let s = 5;
      for (let i = 0; i < 6; i++) {
        if (elapsed < stages[i]) { s = i; break; }
      }
      setStage(s);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => { mounted = false; cancelAnimationFrame(raf); };
  }, [stages, totalDuration, paused]);

  // BIG single-line message per stage. The graphic below carries the "how";
  // this text carries the "what we're saying right now". Apple-style: one
  // message at a time, large, centered.
  const titles = [
    'One review.',
    'Two causes, one effect.',
    'Now do it a million times.',
    'Place each one in time.',
    'Test cause → effect across time.',
    'Now we know what truly drives churn.',
  ];

  return (
    <div className="px-6 sm:px-8 pt-7 sm:pt-9 pb-4 sm:pb-5 text-center">
      <div className="flex items-center justify-center gap-2">
        {[0,1,2,3,4,5].map(i => {
          const active = i === stage;
          const past = i < stage;
          return (
            <div key={i}
              className={`h-[3px] rounded-full transition-all duration-500 ease-out ${
                active ? 'w-7 bg-cyan' : past ? 'w-3 bg-mute/70' : 'w-3 bg-line'
              }`}/>
          );
        })}
      </div>
      <h2 key={stage}
        className="sm-stage-fade mt-7 sm:mt-9 mx-auto max-w-3xl text-[26px] sm:text-[34px] md:text-[40px] font-medium tracking-[-0.022em] text-ink leading-[1.1]">
        {titles[stage]}
      </h2>
      <style>{`
        .sm-stage-fade {
          animation: smStageFade 480ms cubic-bezier(0.4, 0, 0.2, 1);
        }
        @keyframes smStageFade {
          from { opacity: 0; transform: translateY(6px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @media (prefers-reduced-motion: reduce) {
          .sm-stage-fade { animation: none !important; opacity: 1; transform: none; }
        }
      `}</style>
    </div>
  );
}

function AtlasDetailPage() {
  const [tweaks, setTweaks] = (window.useTweaks || ((d) => [d, () => {}]))(ATLAS_DETAIL_DEFAULTS);
  const stages = [tweaks.stage1End, tweaks.stage2End, tweaks.stage3End, tweaks.stage4End, tweaks.stage5End, tweaks.stage6End, tweaks.totalDuration];

  const kpis = [
    ['REVIEWS', '>4M'],
    ['BRANDS',  '>7'],
    ['MARKETS', '>10'],
  ];

  // Sample interpretation walks ONE causal pathway from the live taxonomy.
  // Math chain (auditable):
  //   1) BASE         = Non-Responsiveness topic-mentions extracted from
  //                     reviews this year in this market (NLP signal)
  //   2) DAMAGE       = base × ATE × cost_per_case    (sub-cause-attributable churn)
  //   3) LEVER from data: ATE_with_initiative vs ATE_baseline → recovery rate
  //   4) IMPACT       = base × (ATE - ATE_with_initiative) × cost_per_case
  const sampleAnalysis = {
    effect:    { name: 'Service Churn', count: 13 },
    cause:     { name: 'Communication & Responsiveness', count: 33 },
    subCause:  { name: 'Non-Responsiveness', ate: 0.21, count: 78 },
    market: {
      // Base = volume of Non-Responsiveness topic-mentions our NLP pipeline
      // extracts from this OEM × this market over a year. NOT distinct customers
      // (one customer can mention multiple times; one review can carry several
      // NR-themed topics).
      topicMentions: 15,    // K Non-Responsiveness topic-mentions / year
      costPerCase:   10,    // K EUR — avg revenue lost per churned customer
    },
    lever: {
      // From cross-OEM benchmarking inside the SAME dataset:
      // OEMs running AI-driven first-response + SLA workflows show a markedly
      // lower ATE for Non-Responsiveness → Service Churn. The diff is what
      // the lever could recover for this OEM.
      ateWithInitiative: 0.07,
    },
  };

  const [methodOpen, setMethodOpen] = adUseState(false);
  const [licenseOpen, setLicenseOpen] = adUseState(false);

  // ── Math chain — every number derived, no magic constants in the UI ──
  const ate              = sampleAnalysis.subCause.ate;
  const ateWithLever     = sampleAnalysis.lever.ateWithInitiative;
  const ateDelta         = +(ate - ateWithLever).toFixed(2);              // 0.14
  const recoveryShare    = Math.round((ateDelta / ate) * 100);            // 67
  const topicMentionsK   = sampleAnalysis.market.topicMentions;       // 15
  const costPerCase      = sampleAnalysis.market.costPerCase;
  // Damage = topic-mentions × ATE × cost (sub-cause-attributable churn cases × cost)
  const damageCases      = Math.round(topicMentionsK * 1000 * ate);          // 3,150
  const damageM          = +(damageCases * costPerCase / 1000).toFixed(1);   // 31.5
  // Impact = topic-mentions × ATE-delta × cost
  const preventedCases   = Math.round(topicMentionsK * 1000 * ateDelta);     // 2,100
  const impactPotentialM = +(preventedCases * costPerCase / 1000).toFixed(1); // 21.0

  return (
    <div className="min-h-screen flex flex-col bg-paper">
      <AppNav/>
      <main className="flex-1">
        <div className="mx-auto max-w-[1320px] px-8 lg:px-16 pt-12 pb-16">
          <div className="flex items-center gap-2 mono text-[10px] text-mute">
            <a href="#/lab" className="hover:text-ink">LAB</a><span className="text-line">/</span>
            <span className="text-ink/80">AUTOMOTIVE WALKTHROUGH</span>
          </div>

          <div className="mt-5 flex items-end justify-between flex-wrap gap-6">
            <div className="max-w-3xl">
              <h1 className="text-[40px] sm:text-[48px] leading-[1.04] font-semibold tracking-[-0.025em]">
                Lab — Premium <span className="grad-word">Automotive Aftersales</span>
              </h1>
              <p className="mt-4 text-[15px] text-mute max-w-2xl leading-relaxed">
                A walked-through causal pathway: from one review, to the population-level pattern, to a quantified intervention you can act on.
              </p>
            </div>
            <span className="mono text-[10px] text-cyan inline-flex items-center gap-2 border border-line bg-off rounded-full px-3 py-1.5">
              <span className="h-1.5 w-1.5 rounded-full bg-cyan pulse"></span>RUN COMPLETE · #128
            </span>
          </div>

          <div className="mt-10 rounded-2xl border border-line bg-off grid grid-cols-1 sm:grid-cols-3 divide-y sm:divide-y-0 sm:divide-x divide-line overflow-hidden">
            {kpis.map(([k,v]) => (
              <div key={k} className="px-8 py-6">
                <div className="mono text-[10px] text-mute">{k}</div>
                <div className="mt-2 text-[26px] font-semibold tracking-tight tabular-nums">{v}</div>
              </div>
            ))}
          </div>

          <div className="mt-10 grid grid-cols-1 xl:grid-cols-12 gap-6">
            <div className="xl:col-span-8">
              <div className="rounded-2xl border border-line bg-off overflow-hidden">
                <StageMeter
                  stages={stages}
                  totalDuration={tweaks.totalDuration}
                  paused={!!tweaks.paused}
                />
                <div className="relative aspect-[16/10] overflow-hidden">
                  {window.HeroAnimation && (
                    <window.HeroAnimation
                      totalDuration={tweaks.totalDuration}
                      stages={stages}
                      paused={!!tweaks.paused}
                    />
                  )}
                </div>
              </div>
            </div>

            <div className="xl:col-span-4">
              <div className="rounded-2xl border border-line bg-paper p-6 h-full flex flex-col">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="mono text-[10px] text-mute">SAMPLE INTERPRETATION</div>
                    <h3 className="mt-2 text-[18px] font-semibold tracking-tight">One brand <span className="text-mute">·</span> one market</h3>
                    <button
                      type="button"
                      onClick={() => setLicenseOpen(!licenseOpen)}
                      className="mt-1 mono text-[10px] text-cyan hover:text-cyan/80 transition-colors inline-flex items-center gap-1.5">
                      <span>filter brand × market</span>
                      <Icon.Lock className="w-3 h-3"/>
                    </button>
                  </div>
                  <button
                    type="button"
                    onClick={() => setMethodOpen(!methodOpen)}
                    aria-label="Methodology"
                    className="grid place-items-center h-7 w-7 rounded-full border border-line text-mute hover:text-ink hover:border-ink/40 transition-colors shrink-0"
                  >
                    <span className="text-[12px]" style={{ fontFamily: 'Geist, sans-serif', fontStyle: 'italic', fontWeight: 500 }}>i</span>
                  </button>
                </div>

                {licenseOpen && (
                  <div className="mt-3 rounded-xl border border-cyan/30 bg-cyan/5 p-4">
                    <div className="mono text-[9.5px] text-cyan">LICENSED ACCESS</div>
                    <p className="mt-1.5 text-[12px] text-ink leading-relaxed">
                      Brand and market filters require a licensed Lab seat. The teaser shows one anonymized pathway.
                    </p>
                    <a href="#/demo" className="mt-2 inline-flex items-center gap-1 text-[12px] text-cyan font-medium hover:opacity-80">
                      Request demo access <Icon.Arrow className="w-3 h-3"/>
                    </a>
                  </div>
                )}

                {methodOpen && (
                  <div className="mt-3 rounded-xl border border-line bg-off p-4">
                    <div className="mono text-[9.5px] text-mute">METHODOLOGY</div>
                    <p className="mt-2 text-[12.5px] text-ink leading-relaxed">
                      <span className="font-semibold">ATE</span> — the percentage-point change in an outcome per 1 pp change in cause incidents, after isolating confounders.
                    </p>
                    <p className="mt-2 text-[12px] text-mute leading-relaxed">
                      Tests: bootstrap resampling for confidence intervals, time-lag verified across quarters, validated on held-out periods. Causal AI built on DoWhy with domain priors.
                    </p>
                  </div>
                )}

                {/* EFFECT */}
                <div className="mt-6">
                  <div className="mono text-[10px] text-mute">EFFECT</div>
                  <div className="mt-2 flex items-center justify-between gap-2">
                    <div className="inline-flex items-center gap-2 rounded-full bg-cyan/10 border border-cyan/40 px-3 py-1.5">
                      <span className="h-1.5 w-1.5 rounded-full bg-cyan"/>
                      <span className="text-[14px] font-semibold tracking-tight text-ink">{sampleAnalysis.effect.name}</span>
                    </div>
                    <span className="mono text-[10px] text-subtle">+{sampleAnalysis.effect.count - 1} more</span>
                  </div>
                </div>

                {/* CAUSE */}
                <div className="mt-4">
                  <div className="mono text-[10px] text-mute">CAUSE</div>
                  <div className="mt-2 flex items-center justify-between gap-2">
                    <div className="inline-flex items-center gap-2 rounded-full bg-paper border border-navy/40 px-3 py-1.5">
                      <span className="h-1.5 w-1.5 rounded-full bg-navy"/>
                      <span className="text-[13.5px] font-medium tracking-tight text-ink">{sampleAnalysis.cause.name}</span>
                    </div>
                    <span className="mono text-[10px] text-subtle">+{sampleAnalysis.cause.count - 1} more</span>
                  </div>
                </div>

                {/* SUB-CAUSE */}
                <div className="mt-4">
                  <div className="mono text-[10px] text-mute">SUB-CAUSE</div>
                  <div className="mt-2 flex items-center justify-between gap-2">
                    <div className="inline-flex items-center gap-2 rounded-full bg-paper border border-navy/30 px-3 py-1.5">
                      <span className="text-[13.5px] font-medium tracking-tight text-ink">{sampleAnalysis.subCause.name}</span>
                      <span className="mono text-[11px] text-navy tabular-nums">ATE +{ate.toFixed(2)}</span>
                    </div>
                    <span className="mono text-[10px] text-subtle">+{sampleAnalysis.subCause.count - 1} more</span>
                  </div>
                </div>

                {/* INTERPRETATION → DAMAGE → LEVER → IMPACT POTENTIAL.
                     Each block: 1-line statement, ⓘ for the full audit trail.
                     The lever's recovery rate is derived from the dataset
                     itself (cross-OEM benchmark) — not assumed.            */}
                <div className="mt-4 rounded-2xl bg-off border border-line p-4 space-y-4">
                  <div>
                    <div className="mono text-[9.5px] text-mute flex items-center gap-1.5">
                      INTERPRETATION
                      <span title={`ATE +${ate.toFixed(2)} = each 1 pp rise in the Non-Responsiveness topic-mention rate raises the Service Churn rate by ${ate.toFixed(2)} pp, after isolating confounders (brand, dealer, market, time-period, seasonal effects). The base signal is ${topicMentionsK}K Non-Responsiveness topic-mentions our NLP pipeline extracted from reviews in this market this year — note: not distinct customers; one customer can voice multiple mentions, and one review can carry several NR-themed topics.`}
                        className="cursor-help text-cyan/70 text-[11px]">ⓘ</span>
                    </div>
                    <p className="mt-1.5 text-[12.5px] text-ink leading-relaxed">
                      Each 1 pp rise in this sub-cause's mention rate raises Service Churn by <span className="font-medium">{ate.toFixed(2)} pp</span>. ~{topicMentionsK}K Non-Responsiveness mentions extracted this year — that's the addressable signal.
                    </p>
                  </div>

                  <div>
                    <div className="mono text-[9.5px] text-mute flex items-center gap-1.5">
                      DAMAGE TODAY
                      <span title={`Sub-cause-attributable churn: ${topicMentionsK}K Non-Responsiveness topic-mentions × ATE ${ate.toFixed(2)} = ${damageCases.toLocaleString()} service-churn cases / year that the causal model traces back to this sub-cause. × €${costPerCase}K avg. cost per service-churn case (premium aftersales LTV benchmark) = €${damageM}M / year addressable damage from this single sub-cause.`}
                        className="cursor-help text-cyan/70 text-[11px]">ⓘ</span>
                    </div>
                    <p className="mt-1.5 text-[12.5px] text-ink leading-relaxed">
                      ~{damageCases.toLocaleString()} service-churn cases / year attributable to this sub-cause — <span className="font-medium">€{damageM} M annual damage</span>.
                    </p>
                  </div>

                  <div>
                    <div className="mono text-[9.5px] text-mute flex items-center gap-1.5">
                      LEVER <span className="text-subtle">· from data</span>
                      <span title={`Cross-OEM benchmarking inside the same dataset: peers running AI-driven first-response + SLA-bound workflows (Mercedes Telediagnose, BMW Service Status Tracking, Salesforce Einstein Service Cloud) show ATE ${ateWithLever.toFixed(2)} for Non-Responsiveness → Service Churn — vs ${ate.toFixed(2)} for this OEM. Difference: ${ateDelta.toFixed(2)} (≈ ${recoveryShare}% of the damage).`}
                        className="cursor-help text-cyan/70 text-[11px]">ⓘ</span>
                    </div>
                    <p className="mt-1.5 text-[12.5px] text-ink leading-relaxed">
                      Peers running AI-driven first-response + SLA workflows show ATE <span className="font-medium">{ateWithLever.toFixed(2)}</span> vs this OEM's <span className="font-medium">{ate.toFixed(2)}</span> — a <span className="font-medium">~{recoveryShare}%</span> recovery margin.
                    </p>
                  </div>

                  <div>
                    <div className="mono text-[9.5px] text-mute flex items-center gap-1.5">
                      IMPACT POTENTIAL
                      <span title={`${topicMentionsK}K Non-Responsiveness topic-mentions × ATE-delta ${ateDelta.toFixed(2)} = ${preventedCases.toLocaleString()} service-churn cases preventable / year. × €${costPerCase}K = €${impactPotentialM}M / year recoverable. From ONE sub-cause × ONE lever in ONE market.`}
                        className="cursor-help text-cyan/70 text-[11px]">ⓘ</span>
                    </div>
                    <p className="mt-1.5 text-[12.5px] text-ink leading-relaxed">
                      ~{preventedCases.toLocaleString()} cases preventable / year — <span className="font-semibold text-cyan">€{impactPotentialM} M recoverable / year</span>.
                    </p>
                  </div>
                </div>

                <div className="flex-1"/>
              </div>
            </div>
          </div>

          {window.TweaksPanel && (
            <window.TweaksPanel title="Tweaks">
              <window.TweakSection title="Live demo timing">
                <window.TweakToggle label="Pause" value={tweaks.paused} onChange={v => setTweaks({ paused: v })}/>
                <window.TweakSlider label="Total duration" min={16} max={36} step={1} suffix="s"
                  value={tweaks.totalDuration} onChange={v => setTweaks({ totalDuration: v })}/>
                <window.TweakSlider label="S1 end (bg establishes)" min={1.5} max={tweaks.stage2End - 1} step={0.5} suffix="s"
                  value={tweaks.stage1End} onChange={v => setTweaks({ stage1End: v })}/>
                <window.TweakSlider label="S2 end (typewriter)" min={tweaks.stage1End + 1} max={tweaks.stage3End - 1} step={0.5} suffix="s"
                  value={tweaks.stage2End} onChange={v => setTweaks({ stage2End: v })}/>
                <window.TweakSlider label="S3 end (parallel extract)" min={tweaks.stage2End + 1} max={tweaks.stage4End - 1} step={0.5} suffix="s"
                  value={tweaks.stage3End} onChange={v => setTweaks({ stage3End: v })}/>
                <window.TweakSlider label="S4 end (tree complete)" min={tweaks.stage3End + 1} max={tweaks.stage5End - 1} step={0.5} suffix="s"
                  value={tweaks.stage4End} onChange={v => setTweaks({ stage4End: v })}/>
                <window.TweakSlider label="S5 end (callout)" min={tweaks.stage4End + 1} max={tweaks.stage6End - 1} step={0.5} suffix="s"
                  value={tweaks.stage5End} onChange={v => setTweaks({ stage5End: v })}/>
                <window.TweakSlider label="S6 end (finale)" min={tweaks.stage5End + 1} max={tweaks.totalDuration} step={0.5} suffix="s"
                  value={tweaks.stage6End} onChange={v => setTweaks({ stage6End: v })}/>
              </window.TweakSection>
            </window.TweaksPanel>
          )}

          <div className="mt-6 rounded-2xl border border-line bg-off p-6 sm:p-7 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-5">
            <div>
              <div className="mono text-[10px] text-mute">NEXT</div>
              <h3 className="mt-2 text-[18px] font-semibold tracking-tight">Get inside the live platform.</h3>
              <p className="mt-1.5 text-[13px] text-mute max-w-xl">
                This is a public preview of one vertical. The full Lab gives you the causal engine itself — custom interventions, exportable findings, and additional verticals as they roll out.
              </p>
            </div>
            <div className="flex items-center gap-3">
              <a href="#/demo" className="inline-flex items-center gap-2 rounded-full bg-ink text-paper hover:bg-ink/90 px-6 py-2.5 text-[13.5px] font-medium transition-colors">
                Request Demo Access <Icon.Arrow className="w-4 h-4"/>
              </a>
            </div>
          </div>
        </div>
      </main>
      <Footer/>
    </div>
  );
}

window.AtlasDetailPage = AtlasDetailPage;
