/* Chapters 1-3. v2. */
/* global React, Icon, useCountUp */

const { useState, useEffect } = React;

const IRRITANT_ICONS = {
  suitcase: Icon.Suitcase,
  document: Icon.Document,
  alert: Icon.Alert,
  edit: Icon.Edit,
  search: Icon.Search,
  question: Icon.Question,
};

/* ---------- Chapter 1 — Editorial hero ---------- */
function Chapter1({ t, onNext, lang }) {
  return (
    <section className="chapter" data-screen-label="01 Intro" style={{ position: 'relative' }}>
      {/* Decorative flight path — rebuilt: precise, single arc, no airplane glyph */}
      <svg
        className="flight-line"
        viewBox="0 0 800 480"
        preserveAspectRatio="xMidYMid meet"
        aria-hidden="true"
      >
        <defs>
          <linearGradient id="ch1arc" x1="0" y1="1" x2="1" y2="0">
            <stop offset="0%" stopColor="rgba(214,154,31,.55)" />
            <stop offset="55%" stopColor="rgba(11,59,82,.25)" />
            <stop offset="100%" stopColor="rgba(11,145,214,.55)" />
          </linearGradient>
          <radialGradient id="ch1Orig" cx="0.5" cy="0.5" r="0.5">
            <stop offset="0%" stopColor="rgba(214,154,31,.45)" />
            <stop offset="100%" stopColor="rgba(214,154,31,0)" />
          </radialGradient>
          <radialGradient id="ch1Dest" cx="0.5" cy="0.5" r="0.5">
            <stop offset="0%" stopColor="rgba(11,145,214,.55)" />
            <stop offset="100%" stopColor="rgba(11,145,214,0)" />
          </radialGradient>
        </defs>
        <path d="M 60 430 Q 320 60 760 100" stroke="url(#ch1arc)" strokeWidth="1.6" fill="none" strokeDasharray="3 9" strokeLinecap="round" />
        <circle cx="60" cy="430" r="56" fill="url(#ch1Orig)" />
        <circle cx="60" cy="430" r="7" fill="#D69A1F" />
        <circle cx="60" cy="430" r="14" fill="none" stroke="rgba(214,154,31,.4)" strokeWidth="1.2" />
        <circle cx="760" cy="100" r="56" fill="url(#ch1Dest)" />
        <circle cx="760" cy="100" r="7" fill="#0B91D6" />
        <circle cx="760" cy="100" r="14" fill="none" stroke="rgba(11,145,214,.4)" strokeWidth="1.2" />
        {/* Tiny coordinate markers along the path */}
        <g fontFamily="JetBrains Mono, monospace" fontSize="10" fill="rgba(15,20,25,.35)">
          <text x="74" y="455">ORIG</text>
          <text x="710" y="92">DEST</text>
        </g>
      </svg>

      <div className="chapter-num">01 / 06 · {t.chapter1.eyebrow}</div>

      <div className="ch1-grid">
        <div>
          <h1 className="ch1-h1">
            {t.chapter1.h1Line1}
            <br />
            <span className="it">{t.chapter1.h1Line2Highlight}</span>
          </h1>
          <p className="ch1-sub">{t.chapter1.subtitle}</p>
        </div>

        <aside className="ch1-toc" aria-label="Pitch contents">
          <div className="head">
            <span>{lang === 'fr' ? 'Au sommaire' : 'In this pitch'}</span>
            <span>{t.chapter1.meta2}</span>
          </div>
          <div className="row"><span className="n">01</span><b>{t.rail.chapter1}</b><span className="sub">{lang === 'fr' ? 'le sujet' : 'the topic'}</span></div>
          <div className="row"><span className="n">02</span><b>{t.rail.chapter2}</b><span className="sub">{lang === 'fr' ? '4 tensions' : '4 tensions'}</span></div>
          <div className="row"><span className="n">03</span><b>{t.rail.chapter3}</b><span className="sub">Air Caraïbes</span></div>
          <div className="row"><span className="n">04</span><b>{t.rail.chapter4}</b><span className="sub">{t.chapter1.meta3}</span></div>
          <div className="row"><span className="n">05</span><b>{t.rail.chapter5}</b><span className="sub">{lang === 'fr' ? '6 raisons' : '6 reasons'}</span></div>
          <div className="row"><span className="n">06</span><b>{t.rail.chapter6}</b><span className="sub">{lang === 'fr' ? 'la suite' : "what's next"}</span></div>
        </aside>
      </div>

      <div className="ch1-strip">
        <div className="pair">
          <span className="k">{lang === 'fr' ? 'Format' : 'Format'}</span>
          <span className="v">{t.chapter1.meta1}</span>
        </div>
        <div className="pair">
          <span className="k">{lang === 'fr' ? 'Durée' : 'Length'}</span>
          <span className="v">{t.chapter1.meta2}</span>
        </div>
        <div className="pair">
          <span className="k">{lang === 'fr' ? 'Intégré' : 'Inside'}</span>
          <span className="v serif">{t.chapter1.meta3}</span>
        </div>
        <div className="pair">
          <span className="k">{lang === 'fr' ? 'Public' : 'Audience'}</span>
          <span className="v">{lang === 'fr' ? 'Direction passager' : 'Passenger leadership'}</span>
        </div>
      </div>

      <div className="chapter-foot">
        <div className="foot-meta">01 / 06</div>
        <button className="next-btn teal" onClick={onNext}>
          {t.chapter1.nextLabel} <span className="arrow"><Icon.Arrow size={14} /></span>
        </button>
      </div>
    </section>
  );
}
window.Chapter1 = Chapter1;

/* ---------- Chapter 2 — Editorial numbered list ---------- */
function ProblemRow({ p, idx }) {
  // Pick the visual based on row index
  const Vis = idx === 0 ? Ch2VisClock
            : idx === 1 ? Ch2VisPeak
            : idx === 2 ? Ch2VisPie
            : Ch2VisCursor;
  return (
    <div className={`ch2-row r${idx + 1}`}>
      <div className="num">{p.num}</div>
      <div className="ch2-row-title">{p.title}</div>
      <div className="ch2-row-body">{p.body}</div>
      <div className="ch2-row-icon">
        <Vis />
      </div>
    </div>
  );
}

function Ch2VisClock() {
  return (
    <div className="vis">
      <div className="vis-eyebrow">NOW</div>
      <div className="ch2-vis-clock">
        <div className="face" aria-hidden="true" />
        <div className="label">
          <div className="a">&lt; 1s</div>
          <div className="b">latency</div>
        </div>
      </div>
    </div>
  );
}
function Ch2VisPeak() {
  return (
    <div className="vis">
      <div className="vis-eyebrow">CONTACTS · WEEK</div>
      <div className="ch2-vis-peak">
        <div className="bar"/><div className="bar"/><div className="bar"/><div className="bar"/>
        <div className="bar"/><div className="bar"/><div className="bar"/><div className="bar"/>
      </div>
    </div>
  );
}
function Ch2VisPie() {
  return (
    <div className="vis">
      <div className="vis-eyebrow">TIER-1 SHARE</div>
      <div className="ch2-vis-pie">
        <div className="pie" aria-hidden="true" />
        <div className="label">
          <div className="a">70 %</div>
          <div className="b">basic queries</div>
        </div>
      </div>
    </div>
  );
}
function Ch2VisCursor() {
  return (
    <div className="vis">
      <div className="vis-eyebrow">SESSION · SCROLL</div>
      <div className="ch2-vis-cursor">
        <div className="scroll" aria-hidden="true" />
        <div className="row"><span>FAQ</span><span>EXIT</span></div>
      </div>
    </div>
  );
}

function Chapter2({ t, onNext, lang }) {
  return (
    <section className="chapter" data-screen-label="02 Le constat">
      <div className="chapter-num">02 / 06 · {t.chapter2.eyebrow}</div>

      <div className="ch2-head">
        <h2 className="ch2-h2">
          {/* break the long line in three with mixed colors, no copy change */}
          {(() => {
            const parts = t.chapter2.h2.split('. ').filter(Boolean);
            return (
              <>
                <span className="a">{parts[0]}.</span>{' '}
                <span className="b">{parts[1]}.</span>{' '}
                <span className="c">{parts[2]}</span>
              </>
            );
          })()}
        </h2>
        <p className="ch2-intro">{t.chapter2.intro}</p>
      </div>

      <div className="ch2-list">
        {t.chapter2.problems.map((p, i) => (
          <ProblemRow key={p.num} p={p} idx={i} />
        ))}
      </div>

      <div className="gold-mine">
        <div className="big">∞</div>
        <div className="body">
          <div className="label">{t.chapter2.goldMineLabel}</div>
          <div className="text">{t.chapter2.goldMineBody}</div>
        </div>
      </div>

      <div className="chapter-foot">
        <div className="foot-meta">02 / 06</div>
        <button className="next-btn teal" onClick={onNext}>
          {t.chapter2.nextLabel} <span className="arrow"><Icon.Arrow size={14} /></span>
        </button>
      </div>
    </section>
  );
}
window.Chapter2 = Chapter2;

/* ---------- Chapter 3 — Camille + phased irritants ---------- */
function HeroStat({ number, suffix, label, sub }) {
  const sep = number.includes(',') ? ',' : '.';
  const normalized = number.replace(',', '.');
  const dotIdx = normalized.indexOf('.');
  const decimals = dotIdx === -1 ? 0 : normalized.length - dotIdx - 1;
  const target = parseFloat(normalized);
  const [ref, val] = useCountUp(target, decimals, 1600, sep);
  return (
    <div ref={ref} className="camille-stat-hero">
      <div className="num tabular">
        {val}<span className="suff">{suffix}</span>
      </div>
      <div className="label">{label}</div>
      <div className="sub">14 mois · Air Caraïbes</div>
    </div>
  );
}
function MiniStat({ number, suffix, label, color }) {
  const sep = number.includes(',') ? ',' : '.';
  const normalized = number.replace(',', '.');
  const dotIdx = normalized.indexOf('.');
  const decimals = dotIdx === -1 ? 0 : normalized.length - dotIdx - 1;
  const target = parseFloat(normalized);
  const [ref, val] = useCountUp(target, decimals, 1400, sep);
  return (
    <div ref={ref} className="camille-stat-mini">
      <div className={`num ${color} tabular`}>{val}<span className="suff">{suffix}</span></div>
      <div className="label">{label}</div>
    </div>
  );
}

/* Map the 6 irritants from dict order to journey phases.
   Pre-trip: suitcase, document, edit
   Disruption: alert, question  (covering both stress + edge cases)
   Onboard / hidden: search  */
function phaseFor(irritant) {
  switch (irritant.icon) {
    case 'suitcase': case 'document': case 'edit': return 'pre';
    case 'alert': case 'question': return 'disrupt';
    case 'search': return 'onboard';
    default: return 'pre';
  }
}

function IrritantCard({ ir }) {
  const I = IRRITANT_ICONS[ir.icon] || Icon.Question;
  return (
    <div className="irritant">
      <div className="icon"><I size={18} /></div>
      <div className="title">{ir.title}</div>
      <div className="body">{ir.body}</div>
    </div>
  );
}

function Chapter3({ t, onNext, lang }) {
  // Bucket irritants
  const buckets = { pre: [], disrupt: [], onboard: [] };
  t.chapter3.irritants.forEach((ir) => { buckets[phaseFor(ir)].push(ir); });

  const phaseMeta = lang === 'fr'
    ? {
        pre:    { kicker: 'AVANT LE VOL', title: 'Au moment de la réservation', sub: 'Frictions sur les règles et la modification.' },
        disrupt:{ kicker: 'PERTURBATION', title: 'Quand le plan déraille', sub: 'Stress maximum, faible disponibilité agents.' },
        onboard:{ kicker: 'À BORD & APRÈS', title: 'Services peu visibles', sub: 'Demande latente, mal servie par les parcours.' },
      }
    : {
        pre:    { kicker: 'BEFORE THE FLIGHT', title: 'At booking time', sub: 'Friction on rules and modifications.' },
        disrupt:{ kicker: 'DISRUPTION', title: 'When the plan breaks', sub: 'Peak stress, low agent availability.' },
        onboard:{ kicker: 'ON BOARD & AFTER', title: 'Hidden services', sub: 'Latent demand, poorly served by your journeys.' },
      };

  return (
    <section className="chapter" data-screen-label="03 Camille">
      <div className="chapter-num">03 / 06 · {t.chapter3.eyebrow}</div>

      <h2 className="ch3-h2">
        {t.chapter3.h2Part1}<span className="it">{t.chapter3.h2Highlight}</span>
      </h2>
      <p className="ch3-intro">{t.chapter3.intro}</p>

      <div className="camille">
        <div className="camille-head">
          <div className="meta">
            <span className="eyebrow">{t.chapter3.camilleLabel}</span>
            <h3>{t.chapter3.camilleTitle}</h3>
            <div className="sub">{t.chapter3.camilleSub}</div>
          </div>
          <span className="chip live"><span className="dot" />{lang === 'fr' ? 'En production' : 'In production'}</span>
        </div>

        <div className="camille-stats">
          <HeroStat
            number={t.chapter3.stat3Number}
            suffix={t.chapter3.stat3Suffix}
            label={t.chapter3.stat3Label}
          />
          <div className="camille-stat-side">
            <MiniStat
              number={t.chapter3.stat1Number}
              suffix={t.chapter3.stat1Suffix}
              label={t.chapter3.stat1Label}
              color="sky"
            />
            <MiniStat
              number={t.chapter3.stat2Number}
              suffix={t.chapter3.stat2Suffix}
              label={t.chapter3.stat2Label}
              color="amber"
            />
          </div>
        </div>

        <ul className="camille-points">
          {t.chapter3.camillePoints.map((p) => (
            <li key={p}><Icon.Check size={14} /><span>{p}</span></li>
          ))}
        </ul>
      </div>

      <div className="insights-head">
        <span className="eyebrow">{t.chapter3.insightsLabel}</span>
        <h3 className="insights-title">{t.chapter3.insightsTitle}</h3>
        <p className="insights-sub">{t.chapter3.insightsSub}</p>
      </div>

      <div className="phases">
        {['pre', 'disrupt', 'onboard'].map((key) => {
          const items = buckets[key];
          if (!items.length) return null;
          const meta = phaseMeta[key];
          return (
            <div key={key} className={`phase ${key}`}>
              <div className="head">
                <span className="badge">{meta.kicker}</span>
                <div className="meta"><b>{meta.title}</b><br />{meta.sub}</div>
              </div>
              <div className="grid">
                {items.map((ir) => <IrritantCard key={ir.title} ir={ir} />)}
              </div>
            </div>
          );
        })}
      </div>

      <p className="insights-foot">{t.chapter3.insightsFootnote}</p>

      <div className="chapter-foot">
        <div className="foot-meta">03 / 06</div>
        <button className="next-btn teal" onClick={onNext}>
          {t.chapter3.nextLabel} <span className="arrow"><Icon.Arrow size={14} /></span>
        </button>
      </div>
    </section>
  );
}
window.Chapter3 = Chapter3;
