/* Chapters 4-6. v2. */
/* global React, Icon */

const { useState: useS46, useEffect: useE46, useRef: useR46 } = React;

/* ---------- Chapter 4 — Demo with session tally ---------- */
const SCENARIO_ICONS = { plane: Icon.Plane, suitcase: Icon.Suitcase, alert: Icon.Alert, edit: Icon.Edit };

// Live iframe URLs — same engines wired in the v1 production (fcb-airlines.vercel.app).
// Dashboard uses an unlock token to bypass the email gate (cookie set via middleware).
const DASHBOARD_URL = 'https://report-demo.fcb.ai/report?unlock=fcb-demo-2026';
const PHONE_BASE = 'https://whatsapp-demos.fcb.ai';

function LiveDashboard({ lang }) {
  return (
    <iframe
      className="dash-iframe"
      src={DASHBOARD_URL}
      title={lang === 'fr' ? 'Tableau de bord en direct' : 'Live dashboard'}
      loading="lazy"
    />
  );
}

function FakeDashboard({ lang }) {
  // Build a smooth area chart
  const points = [12, 18, 15, 24, 28, 34, 32, 40, 48, 44, 52, 58, 64, 70, 68, 76, 82, 88, 84, 92];
  const w = 600, h = 100, pad = 4;
  const xs = points.map((_, i) => pad + (i * (w - pad*2)) / (points.length - 1));
  const ys = points.map((v) => h - pad - (v / 100) * (h - pad*2));
  const path = xs.map((x, i) => `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${ys[i].toFixed(1)}`).join(' ');
  const fill = `${path} L ${xs[xs.length-1]} ${h - pad} L ${xs[0]} ${h - pad} Z`;
  return (
    <div className="dash">
      <div className="dash-row">
        <div className="dash-tile">
          <div className="k">{lang === 'fr' ? 'CONV. 7J' : 'CONV. 7D'}</div>
          <div className="v">8 412</div>
          <div className="delta">▲ 12.4%</div>
        </div>
        <div className="dash-tile">
          <div className="k">CSAT</div>
          <div className="v">99.7%</div>
          <div className="delta">▲ 0.4 pt</div>
        </div>
        <div className="dash-tile alert">
          <div className="k">{lang === 'fr' ? 'EN ATTENTE' : 'WAITING'}</div>
          <div className="v">12</div>
          <div className="delta" style={{ color: 'var(--coral)' }}>▼ all handled</div>
        </div>
      </div>
      <div className="dash-chart">
        <div className="head">
          <span>{lang === 'fr' ? 'CONVERSATIONS · 24H' : 'CONVERSATIONS · 24H'}</span>
          <span style={{ color: 'var(--grass)' }}>● {lang === 'fr' ? 'En direct' : 'Live'}</span>
        </div>
        <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
          <defs>
            <linearGradient id="dashFill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="rgba(11,59,82,.30)" />
              <stop offset="100%" stopColor="rgba(11,59,82,0)" />
            </linearGradient>
          </defs>
          <path d={fill} fill="url(#dashFill)" />
          <path d={path} stroke="#0B3B52" strokeWidth="1.8" fill="none" />
          {xs.map((x, i) => i % 4 === 0 && <circle key={i} cx={x} cy={ys[i]} r="2" fill="#0B3B52" />)}
        </svg>
      </div>
      <div className="dash-list">
        <div className="head">{lang === 'fr' ? 'TOP SUJETS · AUJOURD\u2019HUI' : 'TOP TOPICS · TODAY'}</div>
        {[
          [lang === 'fr' ? 'Bagages' : 'Baggage', .82, 211],
          [lang === 'fr' ? 'Modification' : 'Modification', .64, 165],
          [lang === 'fr' ? 'Enregistrement' : 'Check-in', .51, 132],
          [lang === 'fr' ? 'Fidélité' : 'Loyalty', .38, 98],
        ].map(([label, w, n]) => (
          <div key={label} className="row">
            <span>{label}</span>
            <span className="bar" style={{ width: `${w * 100}%`, maxWidth: 180 }} />
            <span className="v tabular">{n}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function LivePhone({ scenario, lang }) {
  const src = `${PHONE_BASE}/?theme=airlines&scenario=${scenario}&lang=${lang}&embed=1`;
  return (
    <div className="phone live">
      <div className="screen">
        <iframe
          key={`${scenario}-${lang}`}
          className="phone-iframe"
          src={src}
          title={`WhatsApp · ${scenario}`}
          loading="lazy"
        />
      </div>
    </div>
  );
}

function FakePhone({ scenario, lang }) {
  // Different message scripts per scenario
  const scripts = {
    'airlines-upsell': lang === 'fr' ? [
      { ai: 'Bonjour Camille — vol AF1234 vers Pointe-à-Pitre, samedi.' },
      { ai: 'Sièges Business disponibles ✈️ Surclassement à 380 € (au lieu de 850 €). On valide ?' },
      { me: 'Oui, allons-y.' },
      { ai: 'Parfait. Souhaitez-vous ajouter un bagage 32 kg pour 29 € ?', cta: 'Ajouter' },
    ] : [
      { ai: 'Hi Camille — flight AF1234 to Pointe-à-Pitre on Saturday.' },
      { ai: 'Business seats free ✈️ Upgrade for €380 (vs €850). Shall we?' },
      { me: 'Yes, let\u2019s go.' },
      { ai: 'Done. Add a 32-kg bag for €29?', cta: 'Add' },
    ],
    'airlines-baggage': lang === 'fr' ? [
      { me: 'Combien de bagages puis-je prendre ?' },
      { ai: 'En Economy Soft : 1 cabine 12 kg + 1 sac perso. Pas de bagage en soute inclus.' },
      { ai: 'Vous voyagez avec un enfant — un bagage 23 kg offert lui est associé.' },
      { me: 'Je veux ajouter une valise 23 kg.' },
      { ai: 'Bagage ajouté à votre PNR · 39 €.', cta: 'Payer' },
    ] : [
      { me: 'How many bags can I bring?' },
      { ai: 'Economy Soft: 1 cabin 12 kg + 1 personal. No checked bag included.' },
      { ai: 'Travelling with a child — one 23-kg bag is included for them.' },
      { me: 'Add a 23-kg bag for me.' },
      { ai: 'Bag added to your PNR · €39.', cta: 'Pay' },
    ],
    'airlines-disruption': lang === 'fr' ? [
      { ai: '⚠️ Votre vol AF1234 a été retardé de 3h30.' },
      { ai: 'Indemnisation CE 261/2004 applicable. Bon repas 12 € prêt à utiliser.' },
      { me: 'Je peux changer pour un vol plus tôt ?' },
      { ai: 'Oui — vol AF1230, +0 €, départ 16h25.', cta: 'Sélectionner' },
    ] : [
      { ai: '⚠️ Your flight AF1234 has been delayed by 3h 30.' },
      { ai: 'EU 261/2004 compensation applies. Meal voucher €12 ready.' },
      { me: 'Can I change to an earlier flight?' },
      { ai: 'Yes — AF1230, +€0, departs 16:25.', cta: 'Select' },
    ],
    'airlines-modification': lang === 'fr' ? [
      { me: 'Je voudrais changer la date de mon retour.' },
      { ai: 'OTP envoyé au +33 6 80 ** ** 79. Confirmez ?' },
      { me: '624-103' },
      { ai: 'Identifié ✓. Frais : 65 € + différence tarifaire 24 €. Total 89 €.', cta: 'Confirmer' },
    ] : [
      { me: 'I\u2019d like to change my return date.' },
      { ai: 'OTP sent to +33 6 80 ** ** 79. Confirm?' },
      { me: '624-103' },
      { ai: 'Verified ✓. Fees: €65 + fare diff €24. Total €89.', cta: 'Confirm' },
    ],
  };
  const msgs = scripts[scenario] || scripts['airlines-baggage'];
  return (
    <div className="phone">
      <div className="screen">
        <div className="wa-bar">
          <div className="avatar">C</div>
          <div className="name">
            <span>Camille · Air Caraïbes</span>
            <span className="status">{lang === 'fr' ? 'en ligne' : 'online'}</span>
          </div>
        </div>
        <div className="wa-messages">
          {msgs.map((m, i) => (
            <div key={i} className={`bubble ${m.me ? 'me' : 'ai'}`}>
              {m.me || m.ai}
              {m.cta && <div className="ai-link">{m.cta}</div>}
              <span className="t">12:0{i}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Tally({ lang }) {
  // Animated counters — local state, deterministic curve
  const [conv, setConv] = useS46(1247);
  const [hrs, setHrs] = useS46(38.2);
  const [sat, setSat] = useS46(99.7);
  useE46(() => {
    const id = setInterval(() => {
      setConv((c) => c + Math.floor(Math.random() * 3));
      setHrs((h) => Math.round((h + 0.1) * 10) / 10);
      setSat((s) => 99.5 + Math.random() * 0.4);
    }, 2400);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="tally">
      <div className="tally-bar">
        <div className="tally-cell">
          <div className="k"><span className="dot" />{lang === 'fr' ? 'CONV. AUJOURD\u2019HUI' : 'CONV. TODAY'}</div>
          <div className="v teal tabular">{conv.toLocaleString('en').replace(/,/g, ' ')}</div>
          <div className="delta">Air Caraïbes · live</div>
        </div>
        <div className="tally-cell">
          <div className="k">{lang === 'fr' ? 'HEURES AGENTS' : 'AGENT HOURS'}</div>
          <div className="v amber tabular">{hrs.toFixed(1)}h</div>
          <div className="delta">{lang === 'fr' ? 'libérées 7J' : 'freed · 7D'}</div>
        </div>
        <div className="tally-cell">
          <div className="k">CSAT</div>
          <div className="v grass tabular">{sat.toFixed(1)}%</div>
          <div className="delta">{lang === 'fr' ? 'rolling 24h' : 'rolling 24h'}</div>
        </div>
        <div className="tally-cell">
          <div className="k">{lang === 'fr' ? 'CANAUX' : 'CHANNELS'}</div>
          <div className="v">3</div>
          <div className="delta">web · wa · app</div>
        </div>
      </div>
      <div className="tally-foot">
        <div className="src"><span style={{ width: 5, height: 5, borderRadius: 99, background: 'var(--grass)', display:'inline-block' }} /> {lang === 'fr' ? 'Données live' : 'Live data'}</div>
        <a className="open" href="#" onClick={(e) => e.preventDefault()}>{lang === 'fr' ? 'Voir en plein écran' : 'Open full screen'} <Icon.External size={11} /></a>
      </div>
    </div>
  );
}

function Chapter4({ t, onNext, lang }) {
  const [tab, setTab] = useS46('whatsapp');
  // Default to the upsell scenario — strongest pitch hook (proactive outreach
   // → in-chat conversion → chained cross-sell). Was [1] (baggage).
  const [scen, setScen] = useS46(t.chapter4.scenarios[0].id);
  const activeScen = t.chapter4.scenarios.find((s) => s.id === scen) || t.chapter4.scenarios[0];
  return (
    <section className="chapter" data-screen-label="04 Démo">
      <div className="chapter-num">04 / 06 · {t.chapter4.eyebrow}</div>

      <h2 className="ch4-h2">
        {t.chapter4.h2.split('. ').map((part, i, arr) => (
          <React.Fragment key={i}>
            {i === arr.length - 1 ? <span className="it">{part}</span> : <>{part}.{' '}</>}
          </React.Fragment>
        ))}
      </h2>

      <Tally lang={lang} />

      <div className="demo-frame">
        <div className="demo-screen">
          <div className="demo-chrome">
            <div className="demo-tabs">
              <button className={tab === 'dashboard' ? 'on' : ''} onClick={() => setTab('dashboard')}>
                <Icon.Dashboard size={14} /> {t.chapter4.tabDashboard}
              </button>
              <button className={tab === 'whatsapp' ? 'on' : ''} onClick={() => setTab('whatsapp')}>
                <Icon.Chat size={14} /> {t.chapter4.tabWhatsApp}
              </button>
            </div>
            <span className="demo-url">{tab === 'dashboard' ? t.chapter4.urlTagDashboard : t.chapter4.urlTagWhatsApp}</span>
            <div className="demo-status">
              <span className="chip live"><span className="dot" />{t.chapter4.statusLive}</span>
            </div>
          </div>
          <div className={`demo-body ${tab === 'dashboard' ? 'flush' : ''}`}>
            {tab === 'dashboard'
              ? <LiveDashboard lang={lang} />
              : <div className="phone-wrap"><LivePhone scenario={scen} lang={lang} /></div>}
          </div>
        </div>

        {tab === 'dashboard' ? (
          /* DASHBOARD-TAB right block — business impact of the report,
             with a highlight quote about clients updating their roadmap. */
          <div className="scenarios dashboard-info">
            <div className="head">
              <span className="eyebrow amber">{t.chapter4.dashboardEyebrow}</span>
            </div>
            <h3 className="dashboard-info-title">{t.chapter4.dashboardTitle}</h3>
            <ul className="dashboard-info-list">
              {t.chapter4.dashboardBullets.map((b) => (
                <li key={b}><Icon.Check size={12} /> <span>{b}</span></li>
              ))}
            </ul>
            <div className="dashboard-highlight">
              <span className="hl-label">{t.chapter4.dashboardHighlightLabel}</span>
              <p className="hl-body">{t.chapter4.dashboardHighlight}</p>
            </div>
          </div>
        ) : (
          /* WHATSAPP-TAB right block — scenario picker + active scenario bullets */
          <div className="scenarios">
            <div className="head">
              <span className="ti">{t.chapter4.switchTitle}</span>
              <span className="eyebrow amber">{t.chapter4.switchEyebrow}</span>
            </div>
            <div className="scenarios-grid">
              {t.chapter4.scenarios.map((s) => {
                const SI = SCENARIO_ICONS[s.icon] || Icon.Plane;
                return (
                  <button key={s.id} className={`scenario ${scen === s.id ? 'on' : ''}`} onClick={() => { setScen(s.id); setTab('whatsapp'); }}>
                    <div className="ic"><SI size={16} /></div>
                    <div className="label">{s.label}</div>
                    <div className="sub">{s.sub}</div>
                  </button>
                );
              })}
            </div>
            <div className="scenario-detail">
              <div className="eyebrow">{t.chapter4.whatsappTitle}</div>
              <ul>
                {activeScen.bullets.map((b) => (
                  <li key={b}><Icon.Check size={12} /> <span>{b}</span></li>
                ))}
              </ul>
            </div>
            <div style={{ marginTop: 12, fontSize: 12, color: 'var(--ink-55)', lineHeight: 1.5, fontFamily: "'Newsreader', serif", fontStyle: 'italic' }}>
              {t.chapter4.switchFootnote}
            </div>
          </div>
        )}
      </div>

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

/* ---------- Chapter 5 — Dark FCB ---------- */
const REASON_ICONS = [Icon.Plane, Icon.Plug, Icon.Trend, Icon.Handshake, Icon.Chart, Icon.Star];
const REASON_ACCENTS = ['#8A5CFF', '#4F7BFF', '#E664C8', '#FFB98A', '#B48BFF', '#4F7BFF'];

function Chapter5({ t, onNext, lang }) {
  return (
    <section className="chapter dark ch5" data-screen-label="05 Pourquoi FCB">
      <div className="blob1" /><div className="blob2" /><div className="blob3" />
      <div style={{ position: 'relative' }}>
        <div className="chapter-num">05 / 06 · {t.chapter5.eyebrow}</div>

        <div className="ch5-hero">
          <div>
            <span className="eyebrow" style={{ color: 'var(--fcb-violet)' }}>{t.chapter5.eyebrow}</span>
            <h1 className="ch5-h1">
              {t.chapter5.h1Part1}<span className="grad">{t.chapter5.h1Highlight}</span>
            </h1>
            <p className="ch5-sub">{t.chapter5.subtitle}</p>
          </div>
          <div className="ch5-fact">
            <div className="k">{lang === 'fr' ? 'En production' : 'In production'}</div>
            <div className="v grad">8 yrs</div>
            <div className="pair">
              <div><div className="lbl">{lang === 'fr' ? 'Clients voyage' : 'Travel clients'}</div><div className="num">20+</div></div>
              <div><div className="lbl">{lang === 'fr' ? 'Compagnies' : 'Airlines'}</div><div className="num">7</div></div>
              <div><div className="lbl">{lang === 'fr' ? 'Conv. / mois' : 'Conv. / month'}</div><div className="num">1.4M</div></div>
              <div><div className="lbl">{lang === 'fr' ? 'Implantations' : 'Locations'}</div><div className="num">4</div></div>
            </div>
          </div>
        </div>

        <div style={{ marginTop: 56 }}>
          <span className="eyebrow" style={{ color: 'var(--fcb-blue)' }}>{t.chapter5.benefitsLabel}</span>
          <h2 style={{ fontFamily: 'Inter, sans-serif', fontWeight: 600, letterSpacing: '-0.025em', fontSize: 'clamp(24px, 3vw, 32px)', lineHeight: 1.15, margin: '14px 0 0', color: 'var(--fcb-text)' }}>
            {t.chapter5.benefitsTitle}
          </h2>
        </div>

        <div className="benefits">
          <div className="benefit-col passenger">
            <span className="lbl">{t.chapter5.passengerLabel}</span>
            <ul>
              {t.chapter5.passengerBenefits.map((b) => (
                <li key={b}><Icon.Check size={14} /><span>{b}</span></li>
              ))}
            </ul>
          </div>
          <div className="benefit-col airline">
            <span className="lbl">{t.chapter5.airlineLabel}</span>
            <ul>
              {t.chapter5.airlineBenefits.map((b) => (
                <li key={b}><Icon.Check size={14} /><span>{b}</span></li>
              ))}
            </ul>
          </div>
        </div>

        <div className="reasons">
          <div className="reasons-head">
            <div>
              <span className="eyebrow" style={{ color: 'var(--fcb-pink)' }}>{t.chapter5.whyLabel}</span>
              <h2 className="reasons-title">{t.chapter5.whyTitle}</h2>
            </div>
            <p className="reasons-sub">{t.chapter5.whySub}</p>
          </div>
          <div className="reasons-grid">
            {t.chapter5.reasons.map((r, i) => {
              const RI = REASON_ICONS[i % REASON_ICONS.length];
              const accent = REASON_ACCENTS[i % REASON_ACCENTS.length];
              return (
                <div key={r.num} className="reason" style={{ '--accent': accent }}>
                  <div className="top">
                    <span className="icon"><RI size={16} /></span>
                    <span className="num">{r.num}</span>
                    <span className="line" />
                  </div>
                  <div className="title">{r.title}</div>
                  <div className="body">{r.body}</div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="refs">
          <span className="eyebrow" style={{ color: 'var(--fcb-violet)' }}>{t.chapter5.refsLabel}</span>
          <h2 className="reasons-title">{t.chapter5.refsTitle}</h2>

          <div className="refs-table" style={{ marginTop: 28 }}>
            <div className="refs-head">
              <div>{lang === 'fr' ? 'CLIENT' : 'CLIENT'}</div>
              <div>{lang === 'fr' ? 'SECTEUR' : 'SECTOR'}</div>
              <div>KPI</div>
              <div>{lang === 'fr' ? 'TÉMOIGNAGE' : 'TESTIMONIAL'}</div>
            </div>
            {t.chapter5.references.map((r, i) => (
              <div key={r.client} className="ref-row">
                <div className="client">
                  <div className="nm">{r.client}</div>
                  <div className="role">{r.role}</div>
                </div>
                <div className="sector">{r.sector}</div>
                <div className="kpi">
                  <div className="v tabular">{r.kpi}</div>
                  <div className="s">{r.kpiSub}</div>
                </div>
                <div className="quote">
                  “{r.quote}”
                  <span className="who">{r.person}</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="locations">
          <span className="eyebrow" style={{ color: 'var(--fcb-blue)' }}>{t.chapter5.locationsLabel}</span>
          <div className="list">
            {t.chapter5.locations.map((loc) => (
              <span key={loc} className="location"><span className="dot" />{loc}</span>
            ))}
          </div>
        </div>

        <div className="chapter-foot">
          <div className="foot-meta">{t.chapter5.continueLabel}</div>
          <button className="next-btn fcb" onClick={onNext}>
            {t.chapter5.nextEngagementLabel} <span className="arrow"><Icon.Arrow size={14} /></span>
          </button>
        </div>
      </div>
    </section>
  );
}
window.Chapter5 = Chapter5;

/* ---------- Chapter 6 — Closer ---------- */
function Chapter6({ t, lang }) {
  return (
    <section className="chapter dark ch6" data-screen-label="06 Close">
      <div className="blob1" /><div className="blob2" />
      <div style={{ position: 'relative' }}>
        <div className="chapter-num">06 / 06 · {t.chapter6.eyebrow}</div>

        <div className="ch6-vision">
          <span className="eyebrow" style={{ color: 'var(--fcb-violet)' }}>{t.chapter6.eyebrow}</span>
          <h2 className="ch6-h2">
            {t.chapter6.h2Part1}<span className="grad">{t.chapter6.h2Highlight}</span>
          </h2>
          <p className="ch6-lead">{t.chapter6.visionLead}</p>
          <p className="ch6-body">{t.chapter6.visionBody}</p>
        </div>

        <div className="ch6-contact">
          <span className="eyebrow" style={{ color: 'var(--fcb-gold)' }}>{t.chapter6.contactLabel}</span>
          <h3>{t.chapter6.contactTitle}</h3>
          <p className="body">{t.chapter6.contactBody}</p>

          <div className="contact-grid">
            <a className="contact-card" href={`mailto:${t.chapter6.contactEmail}`}>
              <span className="k">{t.chapter6.contactEmailLabel}</span>
              <span className="v">{t.chapter6.contactEmail}</span>
            </a>
            <a className="contact-card" href={lang === 'fr' ? 'tel:+33680962279' : 'tel:+33781543166'}>
              <span className="k">{t.chapter6.contactPhoneLabel}</span>
              <span className="v tabular">{t.chapter6.contactPhone}</span>
            </a>
            <a className="contact-card" href={`https://${t.chapter6.contactWeb}`} target="_blank" rel="noopener noreferrer">
              <span className="k">{t.chapter6.contactWebLabel}</span>
              <span className="v">{t.chapter6.contactWeb}</span>
            </a>
          </div>

          <div className="ch6-cta-row">
            {(() => {
              // Final CTA → WhatsApp message to the lang-appropriate contact.
              // FR: Olivier (06 80 96 22 79) · EN: Antoine, CEO (+33 7 81 54 31 66)
              const waMsg = lang === 'fr'
                ? "Bonjour Olivier, j'aimerais discuter de FCB.ai pour mon entreprise."
                : "Hi Antoine, I'd like to discuss FCB.ai for my airline.";
              const waNumber = lang === 'fr' ? '33680962279' : '33781543166';
              const waUrl = `https://wa.me/${waNumber}?text=${encodeURIComponent(waMsg)}`;
              return (
                <a className="ch6-cta" href={waUrl} target="_blank" rel="noopener noreferrer">
                  {t.chapter6.finalCtaLabel} <Icon.Arrow size={16} />
                </a>
              );
            })()}
            <div className="ch6-byline">
              <b>{t.chapter6.contactPerson}</b> · {t.chapter6.contactRole}
            </div>
          </div>
        </div>

        <div className="chapter-foot">
          <div className="foot-meta">{t.chapter6.endOfPitch}</div>
          <div className="foot-meta" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ color: 'var(--fcb-blue)' }}>●</span>
            Paris · Luxembourg · Casablanca · Johannesburg · {t.chapter6.preparedFor}
          </div>
        </div>
      </div>
    </section>
  );
}
window.Chapter6 = Chapter6;
