/* global React */
const TRIP_STATUS = {
  booked:'Booked', planning:'Planning', dreaming:'Dreaming', noplans:'No plans'
};
const FRICTION = {
  cost:'Cost', time:'Time off work', no_occasion:'No occasion', family:'Family logistics',
  anxiety:'Travel anxiety', happens:"Hasn't happened", other:'Other',
  prefer_not:'Prefer not to say', skipped:'Skipped'
};
const CARRIER_LABEL = {
  WN:'Southwest', UA:'United', DL:'Delta', AA:'American', B6:'JetBlue', AS:'Alaska', NK:'Spirit', F9:'Frontier', MIX:'Mix of carriers', NONE:"Hasn't flown this year"
};
const FREQ_LABEL = {
  once_or_less:'≤1 / yr', '2_3':'2–3 / yr', '4_10':'4–10 / yr', '10_25':'10–25 / yr', '25p':'25+ / yr (commuter)'
};
const COMPANION_LABEL = {
  solo:'Solo, mostly', partner:'Partner', family:'Family', friends:'Friends / group', mix:'Mix — depends'
};
const SWITCH_LABEL = {
  sometimes:'Already does sometimes', yes:'Would consider', maybe:'Maybe — depends',
  committed:'Committed elsewhere', no:'Not into Southwest'
};

function destLabel(id) {
  if (!id || id === '__skipped') return null;
  if (typeof id === 'string' && id.startsWith('free:')) return `${id.slice(5)} · freeform`;
  const F = window.SW_FLOWS || {};
  const all = [...(F.swDestinationsTagged || []), ...(F.offNetworkAspirational || [])];
  const hit = all.find(d => d.id === id);
  if (!hit) return id;
  const isOff = (F.offNetworkAspirational || []).some(d => d.id === id);
  return `${hit.label}${isOff ? ' · aspirational' : (hit.code ? ' · ' + hit.code : '')}`;
}

const STATE_ORDER = ['TRIP STATUS','FRICTION','DESTINATION','FREQUENCY','CARRIER','COMPANION','SWITCH','HOME AIRPORT','CONTACT','ENTERED','ADVISOR','ROUTED'];

function Row({ k, v }) {
  const empty = (v === undefined || v === null || v === '');
  return (
    <div className="sw-overlay-row">
      <span className="k">{k}</span>
      <span className={`v ${empty ? 'empty' : ''}`}>{empty ? '—' : v}</span>
    </div>
  );
}

// "Cans in the wild" detailed scan-feed widget — moved from consumer hero to overlay (Section 1)
function CansInWild() {
  const routes = [
    { from: 'AUS', to: 'LAS', surface: 'ACL FEST', t: '2m ago' },
    { from: 'DAL', to: 'MCO', surface: 'COWBOYS · ATT', t: '4m' },
    { from: 'DEN', to: 'PHX', surface: 'DU CAMPUS',  t: '7m' },
    { from: 'BWI', to: 'FLL', surface: 'BWI HOTEL',  t: '11m' },
    { from: 'PHX', to: 'CUN', surface: 'ASU CAMPUS', t: '14m' }
  ];
  return (
    <div className="sw-cans-wild">
      {routes.map((r,i) => (
        <div className="row" key={i}>
          <div className="route">{r.from}→{r.to}</div>
          <div className="surface">{r.surface}</div>
          <div className="t">{r.t}</div>
        </div>
      ))}
      <div className="foot">7 surfaces live · refreshing</div>
    </div>
  );
}

function BuyerOverlay({ answers, capture, screen, recs, qIndex, journeyState, advisorClicked, sharedForBonus, conversionPath }) {
  const a = answers || {};
  const tags = window.SW_RECS.audienceTags(null, a);

  let phase = 'IDLE';
  if (screen === 'hero')          phase = 'AWAITING SCAN';
  else if (screen === 'flow')     phase = 'FLOW ACTIVE';
  else if (screen === 'capture')  phase = 'CONTACT CAPTURE';
  else if (screen === 'celebrate')phase = 'ENTERED · CELEBRATING';
  else if (screen === 'advisor')  phase = 'ADVISOR HAND-OFF';
  else if (screen === 'capstone') phase = 'RECORD ROUTED';

  const tone = window.SW_RECS.flowTone(a);

  const session = React.useMemo(() => Math.floor(Math.random()*9e6+1e6).toString(36).toUpperCase(), []);

  return (
    <aside className="sw-overlay" aria-label="Buyer overlay">
      <div className="sw-overlay-scroll"><div className="sw-overlay-inner">
        <div>
          <h5><span className="live"></span> Buyer Overlay · Salesforce-ready</h5>
          <div style={{fontFamily:'var(--ff-mono)', fontSize:10, letterSpacing:'0.06em', color:'rgba(255,255,255,0.4)', marginTop:4}}>
            tenant.southwest · sess.{session}
          </div>
        </div>

        <div className="sw-overlay-section">
          <h5 style={{marginBottom:10}}>Session</h5>
          <Row k="Phase" v={phase} />
          <Row k="Journey state" v={journeyState || '—'} />
          <Row k="Implied tone" v={tone ? tone.toUpperCase() : '—'} />
        </div>

        <div className="sw-overlay-section">
          <h5 style={{marginBottom:10}}>Journey progression</h5>
          <div className="sw-tag-list">
            {STATE_ORDER.map(s => {
              const idx = STATE_ORDER.indexOf(s);
              const cur = STATE_ORDER.indexOf(journeyState || 'TRIP STATUS');
              const active = s === journeyState;
              const done = idx < cur;
              const cls = active ? 'gold' : (done ? '' : 'empty');
              return <span key={s} className={`sw-tag ${cls}`} style={done ? {opacity:0.55} : {}}>{s}</span>;
            })}
          </div>
        </div>

        <div className="sw-overlay-section">
          <h5 style={{marginBottom:10}}>Audience tags</h5>
          {tags.length === 0
            ? <div className="sw-overlay-row"><span className="v empty">none yet</span></div>
            : (
              <div className="sw-tag-list">
                {tags.map(t => {
                  const cls = /Defection|High Switch|Defector/.test(t) ? 'hot'
                    : /Companion|Loyalist|Aspirational|Friction/.test(t) ? 'gold' : '';
                  return <span className={`sw-tag ${cls}`} key={t}>{t}</span>;
                })}
              </div>
            )
          }
        </div>

        <div className="sw-overlay-section">
          <h5 style={{marginBottom:10}}>Trip context</h5>
          <Row k="Trip status"  v={TRIP_STATUS[a.tripStatus]} />
          <Row k="Destination"  v={a.destination === '__skipped' ? 'Skipped' : destLabel(a.destination)} />
          <Row k="Friction"     v={FRICTION[a.declaredFriction]} />
        </div>

        <div className="sw-overlay-section">
          <h5 style={{marginBottom:10}}>Travel pattern</h5>
          <Row k="Frequency"    v={FREQ_LABEL[a.annualFlights]} />
          <Row k="Carrier"      v={CARRIER_LABEL[a.carrierPrimary]} />
          <Row k="Companion"    v={COMPANION_LABEL[a.travelCompanion]} />
          <Row k="Switch posture" v={SWITCH_LABEL[a.switchPosture]} />
          <Row k="Home airport" v={a.homeAirport === '__skipped' ? 'Skipped' : a.homeAirport} />
        </div>

        <div className="sw-overlay-section">
          <h5 style={{marginBottom:10}}>Companion Pass path</h5>
          <Row k="Eligibility" v={
            a.annualFlights === '25p' || a.annualFlights === '10_25' ? 'Highly eligible'
            : a.annualFlights === '4_10' ? 'Reachable in <12mo'
            : a.annualFlights === '2_3'  ? 'Reachable with card'
            : 'Education path' } />
          <Row k="Advisor CTA clicked" v={advisorClicked ? 'TRUE' : 'false'} />
          <Row k="Conversion path" v={conversionPath || ''} />
          <Row k="Shared for bonus" v={sharedForBonus ? 'TRUE' : 'false'} />
        </div>

        <div className="sw-overlay-section">
          <h5 style={{marginBottom:10}}>Match</h5>
          {(!recs || recs.length === 0)
            ? <div className="sw-overlay-row"><span className="v empty">awaiting flow completion</span></div>
            : recs.map(r => <Row key={r.name} k={r.tag} v={r.name} />)}
        </div>

        <div className="sw-overlay-section">
          <h5 style={{marginBottom:10}}>Contact</h5>
          <Row k="Email"   v={capture?.email} />
          <Row k="Mobile"  v={capture?.phone} />
          <Row k="SMS opt" v={capture?.smsOptIn ? 'opted in' : (capture?.phone ? 'declined' : '')} />
          <Row k="Consent" v={capture?.consent ? 'agreed' : ''} />
        </div>

        <div className="sw-overlay-section">
          <h5 style={{marginBottom:10}}>Cans in the wild · last 24h</h5>
          <CansInWild />
        </div>

        <div className="sw-overlay-section sw-overlay-config">
          <h5 style={{marginBottom:10, color:'var(--sw-yellow)'}}>Program configuration</h5>
          <Row k="Drawing date" v="Sep 30, 2026" />
          <Row k="Prize pool" v="1 · 10 · 100 · ∞" />
          <Row k="Tenant" v="southwest" />
          <div style={{fontFamily:'var(--ff-mono)', fontSize:10, color:'rgba(255,255,255,0.45)', marginTop:8, lineHeight:1.5}}>
            Scale-adaptive · pilot defaults to 60–90d window · same engine drives Chase, Marriott, BTC tenants.
          </div>
        </div>

        <div className="sw-overlay-pulse">
          {phase === 'RECORD ROUTED'
            ? '↳ POSTED · CRM/leads/southwest_journey · audience tags applied'
            : 'POST /v1/declarations · sf.lead.upsert (pending)'}
        </div>
      </div></div>
    </aside>
  );
}

window.BuyerOverlay = BuyerOverlay;
