/* global React */
const { useState: useS_screens, useEffect: useE_screens, useMemo: useM_screens, useRef: useR_screens } = React;

// Resolve a destination ID to a friendly label using SW_FLOWS data
function destLabelScreen(id) {
  if (!id || id === '__skipped') return null;
  if (typeof id === 'string' && id.startsWith('free:')) return id.slice(5);
  const F = window.SW_FLOWS || {};
  const all = [...(F.swDestinationsTagged || []), ...(F.offNetworkAspirational || [])];
  const hit = all.find(d => d.id === id);
  return hit ? hit.label : id;
}

// ====================================================================
// HERO — Logic Patch v3.1 — Lead with the prize
// ====================================================================
function HeroScreen({ onStart }) {
  // animated entry count for "live" social proof line
  const [count, setCount] = useS_screens(3247);
  useE_screens(() => {
    const id = setInterval(() => setCount(c => c + Math.floor(Math.random() * 3)), 4200);
    return () => clearInterval(id);
  }, []);
  return (
    <section className="sw-hero">
      <div className="sw-hero-inner">
        <div className="sw-hero-meta">
          <span className="heart"><Heart size={11}/> Heart of Southwest</span>
          <span>Enter to win</span>
        </div>
        <h1>Win a year of <em>free flights</em> — for two.</h1>
        <p className="lede">Plus 110 other prizes. About a minute to enter. Tell us a few things about your travel — Southwest gets to know who you are, you get a personalized Southwest match.</p>
        <div className="sw-hero-cta">
          <button className="sw-btn" onClick={onStart}>Enter to win <ArrowRight /></button>
        </div>
        <div className="sw-hero-fineprint">
          No purchase necessary. Concept demo · illustrative only · not a Southwest offer.
        </div>
        <div className="sw-hero-social">
          <span className="live-dot"></span>
          <b>{count.toLocaleString()}</b> entered today · drawing closes <b>September 30, 2026</b>
        </div>
      </div>
    </section>
  );
}

// ====================================================================
// CARDS — big intent cards (Q01) and small destination cards (Q02, Q07)
// ====================================================================
function BigCardSelect({ options, value, onChange }) {
  return (
    <div className="sw-bigcards">
      {options.map(o => (
        <button
          key={o.id}
          className={`sw-bigcard ${value === o.id ? 'active' : ''}`}
          onClick={() => onChange(o.id)}>
          <span className="ico"><GateIcon kind={o.icon || 'spark'} size={22}/></span>
          <span className="lab">{o.label}</span>
          {o.hint && <span className="hint">{o.hint}</span>}
        </button>
      ))}
    </div>
  );
}

function CardsOrSearch({ cards, value, onChange, suggestions, placeholder, onSkip, skippable }) {
  const [searching, setSearching] = useS_screens(false);
  const isCardValue = cards.some(c => c.id === value);
  return (
    <div className="sw-cardsearch">
      {!searching && (
        <>
          <div className="sw-destcards">
            {cards.map(c => (
              <button
                key={c.id}
                className={`sw-destcard ${value === c.id ? 'active' : ''}`}
                onClick={() => onChange(c.id)}>
                <span className="lab">{c.label}</span>
                <span className="sub">{c.sub}</span>
              </button>
            ))}
          </div>
          <button className="sw-text-link" onClick={() => setSearching(true)}>
            Somewhere else <ArrowRight size={14} />
          </button>
        </>
      )}
      {searching && (
        <div>
          <Autocomplete
            value={isCardValue ? '' : value}
            onChange={onChange}
            suggestions={suggestions}
            placeholder={placeholder}
          />
          <button className="sw-text-link" onClick={() => setSearching(false)} style={{marginTop:14}}>
            ← Show top picks
          </button>
        </div>
      )}
      {skippable && (
        <button className="sw-skip-link" onClick={onSkip}>Skip this one →</button>
      )}
    </div>
  );
}

// Destination picker — category filters + search, no popularity pre-ranking
function DestinationPicker({ categories, destinations, offNetwork, value, onChange, placeholder, offNetworkNote }) {
  const [cat, setCat] = useS_screens('all');
  const [query, setQuery] = useS_screens('');
  const [showAll, setShowAll] = useS_screens(false);

  const isOffNetwork = !!(offNetwork || []).find(d => d.id === value);
  const list = useM_screens(() => {
    if (cat === 'intl') return offNetwork || [];
    const filtered = (destinations || []).filter(d =>
      cat === 'all' ? true : (d.tags || []).includes(cat)
    );
    // Alphabetical — no popularity ranking
    return filtered.slice().sort((a,b) => a.label.localeCompare(b.label));
  }, [cat, destinations, offNetwork]);

  const q = query.trim().toLowerCase();
  const searchResults = useM_screens(() => {
    if (!q) return [];
    const all = [...(destinations||[]), ...(offNetwork||[])];
    return all.filter(d =>
      d.label.toLowerCase().includes(q) ||
      (d.code || '').toLowerCase().includes(q)
    ).slice(0, 12);
  }, [q, destinations, offNetwork]);

  const visible = q ? searchResults : (showAll ? list : list.slice(0, 9));

  return (
    <div className="sw-destpicker">
      <div className="sw-destsearch">
        <input
          type="text"
          className="sw-destsearch-input"
          placeholder={placeholder || 'Search a city or airport code'}
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
      </div>
      {!q && (
        <div className="sw-destcats">
          {(categories || []).map(c => (
            <button
              key={c.id}
              className={`sw-destcat ${cat === c.id ? 'active' : ''}`}
              onClick={() => { setCat(c.id); setShowAll(false); }}>
              {c.label}
            </button>
          ))}
        </div>
      )}
      <div className="sw-destgrid">
        {visible.length === 0 && !q && (
          <div className="sw-destempty">No matches in this filter.</div>
        )}
        {visible.length === 0 && q && (
          <button
            className="sw-destfree"
            onClick={() => onChange(`free:${query.trim()}`)}>
            <span className="lab">Use "{query.trim()}"</span>
            <span className="sub">We'll log it as your destination — Southwest may not fly there yet.</span>
          </button>
        )}
        {visible.map(d => (
          <button
            key={d.id}
            className={`sw-destchip ${value === d.id ? 'active' : ''}`}
            onClick={() => onChange(d.id)}>
            <span className="lab">{d.label}</span>
            {d.code && <span className="sub">{d.code}</span>}
          </button>
        ))}
      </div>
      {!q && !showAll && list.length > 9 && (
        <button className="sw-text-link" onClick={() => setShowAll(true)}>
          Show all {list.length} <ArrowRight size={14} />
        </button>
      )}
      {!q && showAll && list.length > 9 && (
        <button className="sw-text-link" onClick={() => setShowAll(false)}>
          Show less
        </button>
      )}
      {(cat === 'intl' || isOffNetwork) && offNetworkNote && (
        <div className="sw-destnote">{offNetworkNote}</div>
      )}
    </div>
  );
}

// ====================================================================
// QUESTION RUNNER
// ====================================================================
function QuestionRunner({ q, value, onChange, onNext, onBack, onSkip, stepLabel, hideBack }) {
  let body = null;
  let canNext = false;
  if (q.kind === 'big-cards') {
    body = <BigCardSelect options={q.options} value={value} onChange={(id) => { onChange(id); }} />;
    canNext = !!value;
  } else if (q.kind === 'cards-or-search') {
    body = (
      <CardsOrSearch
        cards={q.cards}
        value={value}
        onChange={onChange}
        suggestions={q.suggestions}
        placeholder={q.placeholder}
        onSkip={() => { onChange('__skipped'); onSkip && onSkip(); }}
        skippable={q.skippable}
      />
    );
    canNext = !!value && value !== '__skipped';
  } else if (q.kind === 'destination-picker') {
    body = (
      <DestinationPicker
        categories={q.categories}
        destinations={q.destinations}
        offNetwork={q.offNetwork}
        value={value}
        onChange={onChange}
        placeholder={q.placeholder}
        offNetworkNote={q.offNetworkNote}
        skippable={q.skippable}
        onSkip={() => { onChange('__skipped'); onSkip && onSkip(); }}
      />
    );
    canNext = !!value && value !== '__skipped';
  } else if (q.kind === 'pills') {
    body = <PillSelect options={q.options} value={value} onChange={(id) => { onChange(id); }} />;
    canNext = !!value;
  } else if (q.kind === 'multiselect') {
    body = <MultiPills options={q.options} value={value || []} onChange={onChange} />;
    canNext = (value || []).length > 0;
  } else if (q.kind === 'autocomplete') {
    body = <Autocomplete value={value} onChange={onChange} suggestions={q.suggestions} placeholder={q.placeholder} />;
    canNext = !!value;
  } else if (q.kind === 'openText') {
    body = <OpenText value={value} onChange={onChange} placeholder={q.placeholder} />;
    canNext = (value || '').trim().length > 1;
  }
  return (
    <QuestionChrome
      kicker={q.kicker}
      title={q.title}
      sub={q.sub}
      onBack={onBack}
      onNext={onNext}
      nextDisabled={!canNext}
      hideBack={hideBack}
      onSkip={q.skippable ? (() => { onChange(q.skipValue || '__skipped'); onSkip && onSkip(); }) : null}
    >
      {body}
    </QuestionChrome>
  );
}

// ====================================================================
// CAPTURE — prize-led
// ====================================================================
function CaptureScreen({ value = {}, onChange, onNext, onBack }) {
  const v = value || {};
  const valid = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v.email || '');
  return (
    <QuestionChrome
      kicker="Entry · One step left"
      title="You're one click from being <em>entered.</em>"
      sub="Email's how we tell you if you won. SMS optional — Reply STOP to opt out anytime."
      onBack={onBack}
      onNext={onNext}
      nextDisabled={!valid || !v.consent}
      nextLabel="Lock in my entry"
    >
      <div className="sw-prize-summary">
        <div className="kicker">♥ The Prize</div>
        <div className="line"><b>1 year of free Southwest flights for two.</b> 110 other winners. Drawing closes September 30, 2026.</div>
      </div>
      <div className="sw-capture">
        <div className="field">
          <label htmlFor="sw-email">Email</label>
          <input id="sw-email" type="email" placeholder="you@somewhere.com" value={v.email||''} onChange={e => onChange({...v, email: e.target.value})}/>
        </div>
        <div className="field">
          <label htmlFor="sw-phone">Mobile (optional)</label>
          <input id="sw-phone" type="tel" placeholder="(555) 123-4567" value={v.phone||''} onChange={e => onChange({...v, phone: e.target.value})}/>
        </div>
        <label className="check-row">
          <input type="checkbox" checked={!!v.consent} onChange={e => onChange({...v, consent: e.target.checked})} />
          <span>I agree to receive a one-time email with my entry confirmation. <b>SMS optional</b> — message and data rates may apply, reply STOP to opt out (TCPA-compliant). <span className="sw-link">Privacy notice</span>.</span>
        </label>
        <label className="check-row">
          <input type="checkbox" checked={!!v.smsOptIn} onChange={e => onChange({...v, smsOptIn: e.target.checked})} disabled={!v.phone} />
          <span>Yes, text me Companion Pass tips and trip drops from Southwest × Ape (concept demo).</span>
        </label>
      </div>
    </QuestionChrome>
  );
}

// ====================================================================
// CELEBRATION — 4 beats, scrollable, paced
// ====================================================================
function ConfettiBurst() {
  // simple css-driven heart/dot burst
  const pieces = useM_screens(() => Array.from({length: 14}, (_, i) => ({
    i,
    angle: (Math.random() * 360),
    dist: 80 + Math.random() * 140,
    delay: Math.random() * 200,
    char: i % 3 === 0 ? '♥' : (i % 3 === 1 ? '✦' : '●'),
    color: i % 3 === 0 ? '#E51937' : (i % 3 === 1 ? '#F9B612' : '#7DA9E5')
  })), []);
  return (
    <div className="sw-confetti" aria-hidden="true">
      {pieces.map(p => (
        <span
          key={p.i}
          className="piece"
          style={{
            color: p.color,
            transform: `rotate(${p.angle}deg) translateY(-${p.dist}px)`,
            animationDelay: `${p.delay}ms`
          }}>
          {p.char}
        </span>
      ))}
    </div>
  );
}

function PrizeTier({ rank, badge, title, desc, odds, oddsBold }) {
  return (
    <div className={`sw-prize-tier rank-${rank}`}>
      <div className="badge">{badge}</div>
      <div className="title" dangerouslySetInnerHTML={{__html: title}} />
      <div className="desc">{desc}</div>
      <div className={`odds ${oddsBold ? 'bold' : ''}`}>{odds}</div>
    </div>
  );
}

function companionMath(answers) {
  const a = answers || {};
  const f = a.annualFlights;
  const c = a.travelCompanion;
  const carrier = a.carrierPrimary;
  const friction = a.declaredFriction;

  if (friction && friction !== 'skipped' && friction !== 'prefer_not') {
    if (friction === 'cost') return "You said cost is the main thing — Southwest's lowest fare bucket runs cheaper than most carriers' base economy. Companion Pass on top means one trip pays for two.";
    if (friction === 'time') return "You said time off is the issue. Southwest's strongest move for you: short weekend escapes — Vegas, Nashville, Miami, Phoenix — fly out Friday, back Sunday.";
    if (friction === 'family') return "Family logistics make travel hard. The Companion Pass is the loyalty perk most family travelers don't realize is reachable in a year.";
  }

  if (f === '25p' || f === '10_25') {
    if (c === 'partner' || c === 'family') return "You fly a lot, with someone. That's exactly the profile Companion Pass was built for — two of those trips on Southwest plus a card and your partner flies free for the rest of 2026 and all of 2027.";
    return "Heavy flyer territory. With your travel pattern, 2 Southwest trips plus a Rapid Rewards card hits Companion Pass eligibility — bring whoever, anywhere we fly, free.";
  }
  if (f === '4_10') {
    return "Two of those flights on Southwest + a Southwest credit card and you'd qualify for a full year of free Companion travel starting January 2027. We can show you the path.";
  }
  if (f === '2_3') {
    return "Companion Pass is reachable in one year — a Southwest card + a couple of trips and you're there. Want us to show you the math?";
  }
  return "Companion Pass is closer than most people think. Here's how the simplest path works.";
}

function CelebrationScreen({ answers, capture, onAdvisor, onCapstone, onShare, onRestart }) {
  const math = companionMath(answers);
  const homeAirport = (answers.homeAirport && answers.homeAirport !== '__skipped') ? answers.homeAirport : null;
  const destination = answers.destination && answers.destination !== '__skipped' ? destLabelScreen(answers.destination) : null;
  return (
    <section className="sw-celebrate">
      <div className="inner">

        {/* BEAT 1 — DOPAMINE */}
        <div className="sw-beat sw-beat-1">
          <ConfettiBurst />
          <div className="kicker">Entry locked</div>
          <h1 className="dopamine">YOU'RE <em>IN!</em></h1>
          <p className="lede">Your entry's locked. Drawing closes <b>September 30, 2026</b>. Winners notified within 7 days.</p>
          <div className="hint">Plus, here's what you could win ↓</div>
        </div>

        {/* BEAT 2 — PRIZE STACK */}
        <div className="sw-beat sw-beat-2">
          <div className="beat-num">Beat 02 · The Prize Stack</div>
          <h2 className="beat-h">Four ways to win.</h2>
          <p className="beat-sub">Grand Prize down to a guaranteed instant win. Every entry walks away with something.</p>

          <PrizeTier
            rank="grand"
            badge="🏆 GRAND PRIZE · 1 winner"
            title="A full year of <em>free Southwest flights</em> — for you and a companion."
            desc="Anywhere Southwest flies, every flight free, all year. Worth $5,000–$15,000."
            odds="1 in ~30,000 chance"
          />
          <PrizeTier
            rank="second"
            badge="2nd Place · 10 winners"
            title="$1,000 to fly Southwest, anywhere they go."
            desc="Your choice of destination, your dates."
            odds="1 in ~3,000"
          />
          <PrizeTier
            rank="third"
            badge="3rd Place · 100 winners"
            title="One free Southwest flight, anywhere they fly."
            desc="Round-trip economy, your pick of route."
            odds="1 in ~300"
          />
          <PrizeTier
            rank="instant"
            badge="Everyone wins"
            title="25 Southwest reward points, banked instantly."
            desc="Toward your next flight."
            odds="Guaranteed — every entry."
            oddsBold
          />
        </div>

        {/* BEAT 3 — COMPANION PASS MATH */}
        <div className="sw-beat sw-beat-3">
          <div className="beat-num">Beat 03 · Whether you win or not</div>
          <h2 className="beat-h">Here's how <em>close</em> you are.</h2>
          <p className="beat-sub">Southwest's Companion Pass lets one person fly with you for free, all year. Most people don't realize how reachable it is.</p>
          <div className="sw-companion-card">
            <div className="ck"><Heart size={14}/> Your Companion Pass math</div>
            <p className="cm">{math}</p>
            <button className="sw-btn red" onClick={onAdvisor}>Talk to a Companion Pass advisor <ArrowRight /></button>
          </div>
        </div>

        {/* BEAT 4 — VIRAL SHARE */}
        <div className="sw-beat sw-beat-4">
          <div className="beat-num">Beat 04 · One more thing</div>
          <h2 className="beat-h">Want a <em>bonus entry?</em></h2>
          <p className="beat-sub">Share with someone who'd love a year of free flights — they enter, you get a bonus shot.</p>
          <div className="sw-share-row">
            <button className="sw-share-btn" onClick={onShare}><span className="i">💬</span><span>Messages</span></button>
            <button className="sw-share-btn" onClick={onShare}><span className="i">✉</span><span>Email</span></button>
            <button className="sw-share-btn" onClick={onShare}><span className="i">𝕏</span><span>X</span></button>
            <button className="sw-share-btn" onClick={onShare}><span className="i">⬚</span><span>Copy link</span></button>
          </div>
          <div style={{display:'flex', gap:12, flexWrap:'wrap', marginTop:24}}>
            <button className="sw-btn ghost" onClick={onCapstone}>See how this routes <ArrowRight /></button>
            <button className="sw-btn ghost" onClick={onRestart}>Start over</button>
          </div>
        </div>
      </div>
    </section>
  );
}

// ====================================================================
// ADVISOR SCREEN — 3 elements (script · data hand-off · 3 next steps)
// ====================================================================
function AdvisorScreen({ answers, capture, onBack, onCapstone }) {
  const a = answers || {};
  const FLOWS = window.SW_FLOWS;

  // Resolve declared answers into copy snippets for the mock script
  const freqMap = { once_or_less:'roughly once a year', '2_3':'2–3 times a year', '4_10':'4–10 times a year', '10_25':'10–25 times a year', '25p':'25+ trips a year' };
  const compMap = { solo:'solo', partner:'with your partner', family:'with family', friends:'with friends', mix:'with a mix of people' };
  const carrierName = FLOWS.carrierLabel(a.carrierPrimary);
  const freqDesc = freqMap[a.annualFlights] || 'occasionally';
  const compDesc = compMap[a.travelCompanion] || '';
  const home = (a.homeAirport && a.homeAirport !== '__skipped') ? a.homeAirport : null;
  const dest = (a.destination && a.destination !== '__skipped') ? destLabelScreen(a.destination) : null;

  const script1 = `Based on flying ${freqDesc} ${compDesc}, you're closer than most to qualifying for a Companion Pass — likely 2 Southwest trips away.`;
  const script2 = a.carrierPrimary && a.carrierPrimary !== 'WN' && a.carrierPrimary !== 'NONE'
    ? `Today you fly mostly ${carrierName}. A Southwest Plus card on top of your existing wallet gets you to qualifying within ~90 days at typical $1K/month spend.`
    : `A Southwest Rapid Rewards card adds 30,000+ points right out of the gate — accelerating your Companion Pass qualifying timeline.`;
  const script3 = home && dest
    ? `From ${home} to ${dest}, fares typically run $79–149 round-trip — the simplest first qualifying trip.`
    : home
    ? `From ${home}, the simplest first qualifying trip is usually under $129 round-trip on a flexible weekend.`
    : `Your simplest first qualifying trip is usually a short hop from your home market, under $129 round-trip.`;

  return (
    <section className="sw-advisor">
      <div className="inner">
        <button className="sw-q-back" onClick={onBack} style={{marginBottom:18}}><ArrowLeft /> Back to celebration</button>
        <div className="kicker">Companion Pass advisor · concept demo</div>
        <h2>Here's what your conversation would <em>cover.</em></h2>
        <p className="lede">Your declared answers route to a Southwest Companion Pass advisor in real time. They open the conversation already knowing your travel pattern.</p>

        {/* ELEMENT 1 — Mock script */}
        <div className="sw-advisor-section">
          <div className="adv-eyebrow">Element 01 · The conversation</div>
          <div className="adv-script">
            {[
              { title: 'Your travel pattern qualifies you fast.', body: script1 },
              { title: 'A Southwest card accelerates the math.',   body: script2 },
              { title: 'Your simplest first-trip path.',           body: script3 }
            ].map((s, i) => (
              <div className="adv-bullet" key={i}>
                <div className="avatar"><Heart size={12} color="#fff" /></div>
                <div className="copy">
                  <div className="t">{s.title}</div>
                  <div className="b">{s.body}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* ELEMENT 2 — Data hand-off visualization */}
        <div className="sw-advisor-section">
          <div className="adv-eyebrow">Element 02 · How your info reaches your advisor</div>
          <div className="adv-handoff">
            <div className="node"><div className="cap">Your answers</div><div className="dot d1"></div></div>
            <div className="line"></div>
            <div className="node"><div className="cap">Encrypted hand-off</div><div className="dot d2"></div></div>
            <div className="line"></div>
            <div className="node"><div className="cap">Southwest CRM record</div><div className="dot d3"></div></div>
            <div className="line"></div>
            <div className="node"><div className="cap">Your advisor</div><div className="dot d4"></div></div>
          </div>
          <div className="adv-record">
            <div className="rec-head">Salesforce · lead.upsert</div>
            <div className="rec-row"><span>email</span><span>{capture?.email || 'you@somewhere.com'}</span></div>
            <div className="rec-row"><span>annual_flights</span><span>{a.annualFlights || '—'}</span></div>
            <div className="rec-row"><span>carrier_primary</span><span>{a.carrierPrimary || '—'}</span></div>
            <div className="rec-row"><span>travel_companion</span><span>{a.travelCompanion || '—'}</span></div>
            <div className="rec-row"><span>destination</span><span>{dest || '—'}</span></div>
            <div className="rec-row"><span>home_airport</span><span>{home || '—'}</span></div>
            <div className="rec-row"><span>switch_posture</span><span>{a.switchPosture || '—'}</span></div>
          </div>
          <p className="adv-cap">Your declared answers route to a Southwest Companion Pass advisor in real time. They open the conversation already knowing your travel pattern, current carrier, and what would actually move you to Southwest. No re-explaining.</p>
        </div>

        {/* ELEMENT 3 — Three next-step paths */}
        <div className="sw-advisor-section">
          <div className="adv-eyebrow">Element 03 · What you can do right now</div>
          <div className="adv-paths">
            <button className="adv-path">
              <div className="p-ico" style={{background:'rgba(48,76,178,0.1)', color:'var(--sw-blue)'}}>🃏</div>
              <div className="p-body">
                <div className="p-t">Apply for a Southwest card</div>
                <div className="p-d">Take 2 minutes — Rapid Rewards Plus</div>
              </div>
              <ArrowRight />
            </button>
            <button className="adv-path">
              <div className="p-ico" style={{background:'rgba(229,25,55,0.1)', color:'var(--sw-red)'}}>✈</div>
              <div className="p-body">
                <div className="p-t">Book a Southwest flight</div>
                <div className="p-d">{home && dest ? `From ${home} to ${dest}, starting $79` : (dest ? `To ${dest}, starting $79` : 'From your home airport, starting $79')}</div>
              </div>
              <ArrowRight />
            </button>
            <button className="adv-path">
              <div className="p-ico" style={{background:'rgba(249,182,18,0.18)', color:'var(--sw-navy)'}}>💬</div>
              <div className="p-body">
                <div className="p-t">Talk to an advisor live</div>
                <div className="p-d">Schedule a 15-min call</div>
              </div>
              <ArrowRight />
            </button>
          </div>
          <p className="adv-cap">Concept demo — these paths are illustrative. In production, each routes to live Southwest infrastructure.</p>
        </div>

        <div style={{display:'flex', gap:12, flexWrap:'wrap', marginTop:24}}>
          <button className="sw-btn dark" onClick={onCapstone}>See how this routes <ArrowRight /></button>
          <button className="sw-btn outline-dark" onClick={onBack}>Back to celebration</button>
        </div>
      </div>
    </section>
  );
}

// ====================================================================
// CAPSTONE
// ====================================================================
function CapstoneScreen({ answers, capture, onRestart }) {
  const tags = window.SW_RECS.audienceTags(null, answers);
  const tone = window.SW_RECS.flowTone(answers);
  return (
    <section className="sw-capstone">
      <div className="inner">
        <div className="sw-kicker">Behind the scenes / Where this declared record goes</div>
        <h2>One can. <em>One declared record.</em> Three buyers.</h2>
        <p className="lede">Every answer you gave routes from the Journey Engine into Southwest's Salesforce-ready record schema, with audience tags pre-attached.</p>

        <div className="sw-flow-grid">
          <div className="sw-flow-step">
            <div className="num">01 · CAPTURE</div>
            <div className="name">QR scan → Journey</div>
            <div className="body">Co-branded can in hand at a Southwest-target surface (campus, festival, stadium, hotel). One QR, one tap, one declared session.</div>
            <span className="tag">First-party · TCPA-compliant</span>
          </div>
          <div className="sw-flow-step">
            <div className="num">02 · DECLARE</div>
            <div className="name">Branched flow</div>
            <div className="body">Single linear flow with adaptive branching. Trip status, destination, frequency, carrier, companion, switch posture — all surfaced in 60–75 seconds.</div>
            <span className="tag">{tone === 'frequent' ? 'High-value defection path' : 'Adaptive flow'}</span>
          </div>
          <div className="sw-flow-step">
            <div className="num">03 · ENRICH</div>
            <div className="name">Audience tagging</div>
            <div className="body">{tags.length} tags pre-attached for routing across marketing, network planning, loyalty, and competitive intelligence teams.</div>
            <div className="sw-tag-list" style={{marginTop:6}}>
              {tags.slice(0,5).map(t => <span key={t} className="sw-tag">{t}</span>)}
            </div>
          </div>
          <div className="sw-flow-step">
            <div className="num">04 · ROUTE</div>
            <div className="name">Salesforce-ready</div>
            <div className="body">Record lands as a structured object in Southwest's CRM. Companion Pass eligibility flags fire automatically; defection candidates flag for outreach.</div>
            <span className="tag">CRM · Salesforce schema</span>
          </div>
        </div>

        <div style={{marginTop:36, padding:24, border:'1px solid var(--sw-gray-2)', borderRadius:18, background:'white'}}>
          <div className="sw-kicker" style={{margin:0, marginBottom:12}}>Three buyers / one record</div>
          <div className="sw-flow-grid">
            <div>
              <div style={{fontWeight:600, fontSize:16, marginBottom:6}}>Marketing</div>
              <div style={{fontSize:13, color:'var(--sw-ink-2)'}}>Brand-perception ground truth — what the market thinks of Southwest, plus declared friction from non-flyers.</div>
            </div>
            <div>
              <div style={{fontWeight:600, fontSize:16, marginBottom:6}}>Network Planning</div>
              <div style={{fontSize:13, color:'var(--sw-ink-2)'}}>Stated home airport + destination demand, declared route preferences, competitive frequency by city pair.</div>
            </div>
            <div>
              <div style={{fontWeight:600, fontSize:16, marginBottom:6}}>Loyalty</div>
              <div style={{fontSize:13, color:'var(--sw-ink-2)'}}>Companion Pass eligibility flags, status-match candidates, first-time-flyer onboarding triggers.</div>
            </div>
            <div>
              <div style={{fontWeight:600, fontSize:16, marginBottom:6}}>Competitive Intel</div>
              <div style={{fontSize:13, color:'var(--sw-ink-2)'}}>Defection scoring, switch-trigger declared, current carrier — first-party, not third-party broker data.</div>
            </div>
          </div>
        </div>

        <div style={{marginTop:36, display:'flex', gap:12, flexWrap:'wrap'}}>
          <button className="sw-btn dark" onClick={onRestart}>Run it again <ArrowRight /></button>
          <button className="sw-btn outline-dark" onClick={() => window.scrollTo({top:0, behavior:'smooth'})}>Back to top</button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { HeroScreen, QuestionRunner, CaptureScreen, CelebrationScreen, AdvisorScreen, CapstoneScreen });
