// All 10 luxury levels — cascading multi-select where useful

const LEVEL_REWARDS = { 1:1, 2:1, 3:2, 4:2, 5:2, 6:3, 7:2, 8:4, 9:1, 10:3 };
window.LEVEL_REWARDS = LEVEL_REWARDS;

function GoldHeadline({ text }) {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return (
    <>
      {parts.map((p, i) => {
        if (p.startsWith('**')) {
          return <span key={i} style={{ color: LUX.gold }}>{p.slice(2, -2)}</span>;
        }
        return <React.Fragment key={i}>{p}</React.Fragment>;
      })}
    </>
  );
}

// Reusable cascading-pill section: multi-select parent → for each selected,
// show a child PillGrid keyed to that parent.
function CascadeSection({ label, parentSel, childOptions, childValues, setChildValues, dark, childLabel }) {
  if (!parentSel?.length) return null;
  return (
    <div style={{ marginTop: 14 }}>
      <SectionLabel dark>{label}</SectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {parentSel.map(pid => {
          const opts = childOptions[pid];
          if (!opts) return null;
          return (
            <div key={pid} style={{
              padding: '10px 12px',
              background: dark ? 'rgba(245,240,232,0.04)' : 'rgba(11,26,46,0.03)',
              border: `1px solid ${dark ? 'rgba(245,240,232,0.08)' : 'rgba(11,26,46,0.08)'}`,
              borderRadius: 12,
            }}>
              <div style={{
                fontFamily: "'JetBrains Mono', monospace", fontSize: 9.5, letterSpacing: 1.6,
                fontWeight: 700, color: LUX.gold, marginBottom: 8,
              }}>{childLabel ? childLabel(pid) : pid.toUpperCase()}</div>
              <PillGrid dark={dark} multi
                options={opts}
                value={childValues[pid] || []}
                setValue={v => setChildValues({ ...childValues, [pid]: v })}/>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─────── L1 Contact ───────
function Level1({ data, setData, onNext, onBack, ...p }) {
  const set = (k) => (v) => setData({ ...data, [k]: v });
  const [sms, setSms] = React.useState(data.sms ?? true);
  React.useEffect(() => setData({ ...data, sms }), [sms]);
  const canContinue = !!(data.first && data.last && data.email);
  return (
    <LuxShell {...p} onNext={onNext} onBack={onBack}
      levelNum={1} reward={1} dark={false} iconName="contact"
      title={<GoldHeadline text="FIRST — WHO'S CHECKING **IN**?"/>}
      subtitle="Basics. So we know where to send the prize."
      ctaLabel="Continue" canContinue={canContinue}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{ display: 'flex', gap: 8 }}>
          <div style={{ flex: 1 }}><TextField label="FIRST NAME" value={data.first} onChange={set('first')} placeholder="Jane"/></div>
          <div style={{ flex: 1 }}><TextField label="LAST NAME" value={data.last} onChange={set('last')} placeholder="Doe"/></div>
        </div>
        <TextField label="EMAIL" value={data.email} onChange={set('email')} type="email" placeholder="jane@example.com"/>
        <TextField label="PHONE" value={data.phone} onChange={set('phone')} type="tel" placeholder="(415) 555-0199" format={formatPhone}/>
        <TextField label="DATE OF BIRTH" value={data.dob} onChange={set('dob')} placeholder="MM / DD / YYYY"/>
        <div onClick={() => setSms(!sms)} style={{
          marginTop: 4, padding: '14px 16px',
          background: sms ? LUX.goldTint : '#FFFFFF',
          border: `1px solid ${sms ? LUX.gold : LUX.inputBorder}`,
          borderRadius: 12, cursor: 'pointer',
          display: 'flex', alignItems: 'center', gap: 12,
          transition: 'all 160ms ease',
        }}>
          <div style={{
            width: 22, height: 22, borderRadius: 6,
            background: sms ? LUX.gold : '#FFFFFF',
            border: sms ? 'none' : `1.5px solid rgba(11,26,46,0.25)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            {sms && <svg width="12" height="12" viewBox="0 0 14 14"><path d="M2 7 L6 11 L12 3" stroke={LUX.navy} strokeWidth="2.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
          </div>
          <div style={{ fontFamily: 'Inter', fontSize: 13.5, color: LUX.navy, lineHeight: 1.35 }}>
            <b>Text me if I win.</b> Obviously.
          </div>
        </div>
      </div>
    </LuxShell>
  );
}

// ─────── L2 Vitals ───────
function Level2({ data, setData, firstName, ...p }) {
  const set = (k) => (v) => setData({ ...data, [k]: v });
  const can = !!(data.zip || data.gender || (data.occ?.length) || data.income);
  return (
    <LuxShell {...p} levelNum={2} reward={1} dark={false} iconName="vitals"
      title={<GoldHeadline text={firstName ? `${firstName.toUpperCase()} — QUICK **VITALS.**` : `QUICK **VITALS.**`}/>}
      subtitle="Paint us a picture. Skip what you want."
      canContinue={can}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <TextField label="ZIP CODE" value={data.zip} onChange={set('zip')} placeholder="10024"/>
        <SectionLabel>GENDER</SectionLabel>
        <PillGrid options={['Woman','Man','Non-binary','Prefer not to say']}
          value={data.gender} setValue={set('gender')}/>
        <SectionLabel>OCCUPATION</SectionLabel>
        <PillGrid options={[
          {id:'tech',label:'Tech',hint:'💻'},{id:'creative',label:'Creative',hint:'🎨'},
          {id:'finance',label:'Finance',hint:'🏦'},{id:'health',label:'Healthcare',hint:'🏥'},
          {id:'edu',label:'Education',hint:'🎓'},{id:'trades',label:'Trades',hint:'🔧'},
          {id:'food',label:'Food & Bev',hint:'🍽️'},{id:'student',label:'Student',hint:'🎒'},
          {id:'retired',label:'Retired',hint:'🌴'},{id:'other',label:'Other',hint:'✨'},
        ]} value={data.occ} setValue={set('occ')} multi/>
        <SectionLabel>HOUSEHOLD INCOME · OPTIONAL</SectionLabel>
        <PillGrid options={['<$50k','$50–100k','$100–200k','$200k+','Skip']}
          value={data.income} setValue={set('income')}/>
      </div>
    </LuxShell>
  );
}

// ─────── L3 Hotel Loyalty (cascading: programs → primary + tier) ───────
const PROGRAM_LABELS = {
  bonvoy: 'MARRIOTT BONVOY · TIER',
  hilton: 'HILTON HONORS · TIER',
  ihg: 'IHG ONE REWARDS · TIER',
  hyatt: 'WORLD OF HYATT · TIER',
};
const TIER_OPTS = {
  bonvoy: [{id:'silver',label:'Silver'},{id:'gold',label:'Gold'},{id:'platinum',label:'Platinum'},{id:'titanium',label:'Titanium'},{id:'ambassador',label:'Ambassador'},{id:'member',label:'Just a member'}],
  hilton: [{id:'silver',label:'Silver'},{id:'gold',label:'Gold'},{id:'diamond',label:'Diamond'},{id:'member',label:'Just a member'}],
  ihg: [{id:'silver',label:'Silver'},{id:'gold',label:'Gold'},{id:'platinum',label:'Platinum'},{id:'diamond',label:'Diamond'},{id:'member',label:'Just a member'}],
  hyatt: [{id:'discoverist',label:'Discoverist'},{id:'explorist',label:'Explorist'},{id:'globalist',label:'Globalist'},{id:'member',label:'Just a member'}],
};
function Level3({ data, setData, firstName, ...p }) {
  const tiers = data.tiers || {};
  return (
    <LuxShell {...p} levelNum={3} reward={2} dark iconName="loyalty"
      title={<GoldHeadline text={firstName ? `${firstName.toUpperCase()}, WHICH **PROGRAMS** ARE YOU IN?` : `WHICH HOTEL **PROGRAMS** ARE YOU IN?`}/>}
      subtitle="Tap all that apply. Then tell us your status."
      canContinue={(data.programs?.length || 0) > 0}>
      <PillGrid dark multi value={data.programs} setValue={v=>setData({...data,programs:v})} options={[
        {id:'bonvoy',label:'Marriott Bonvoy',hint:'🏨'},
        {id:'hilton',label:'Hilton Honors',hint:'🏨'},
        {id:'ihg',label:'IHG One Rewards',hint:'🏨'},
        {id:'hyatt',label:'World of Hyatt',hint:'🏨'},
        {id:'airbnb',label:'Airbnb — no loyalty',hint:'🏡'},
        {id:'none',label:'None of the above',hint:'🤷'},
      ]}/>
      <CascadeSection dark label="YOUR STATUS"
        parentSel={(data.programs || []).filter(x => TIER_OPTS[x])}
        childOptions={TIER_OPTS}
        childValues={tiers}
        setChildValues={v => setData({ ...data, tiers: v })}
        childLabel={pid => PROGRAM_LABELS[pid]}/>
    </LuxShell>
  );
}

// ─────── L4 Travel Frequency + Property Type ───────
function Level4({ data, setData, ...p }) {
  return (
    <LuxShell {...p} levelNum={4} reward={2} dark iconName="travel"
      title={<GoldHeadline text="HOW DO YOU **TRAVEL**?"/>}
      subtitle="Frequency and where you stay. Multi-select."
      canContinue={!!data.travel && (data.props?.length || 0) > 0}>
      <SectionLabel dark>FREQUENCY</SectionLabel>
      <PillGrid dark value={data.travel} setValue={v=>setData({...data,travel:v})} options={[
        {id:'rare',label:'Rarely — couple times a year',hint:'🏠'},
        {id:'few',label:'Every few months',hint:'🧳'},
        {id:'monthly',label:'Monthly',hint:'✈️'},
        {id:'weekly',label:'Weekly — on the road',hint:'🌍'},
      ]}/>
      <SectionLabel dark>PROPERTY TYPE · MULTI</SectionLabel>
      <PillGrid dark multi value={data.props} setValue={v=>setData({...data,props:v})} options={[
        {id:'luxury',label:'Luxury hotels',hint:'✨'},
        {id:'boutique',label:'Boutique / design',hint:'🎨'},
        {id:'business',label:'Business hotels',hint:'💼'},
        {id:'resort',label:'All-inclusive resorts',hint:'🌴'},
        {id:'airbnb',label:'Airbnb / VRBO',hint:'🏡'},
        {id:'hostel',label:'Hostels / budget',hint:'🎒'},
        {id:'cruise',label:'Cruises',hint:'🚢'},
      ]}/>
    </LuxShell>
  );
}

// ─────── L5 Live Events (cascading by type) ───────
const EVENT_TYPES = {
  concerts: [{id:'edm',label:'EDM / festivals'},{id:'pop',label:'Pop / mainstream'},{id:'rock',label:'Rock / indie'},{id:'hiphop',label:'Hip-hop / R&B'},{id:'country',label:'Country'},{id:'classical',label:'Classical / opera'}],
  sports: [{id:'home',label:'Home-team games'},{id:'away',label:'Travel for games'},{id:'playoffs',label:'Playoffs only'},{id:'finals',label:'Big finals (Super Bowl etc.)'}],
  festivals: [{id:'music',label:'Music (Coachella, Bonnaroo)'},{id:'food',label:'Food & wine'},{id:'film',label:'Film festivals'},{id:'cultural',label:'Cultural / heritage'}],
  theater: [{id:'broadway',label:'Broadway / West End'},{id:'comedy',label:'Comedy / standup'},{id:'ballet',label:'Ballet / dance'}],
};
function Level5({ data, setData, ...p }) {
  return (
    <LuxShell {...p} levelNum={5} reward={2} dark iconName="events"
      title={<GoldHeadline text="WHAT KIND OF **LIVE** EVENTS?"/>}
      subtitle="Multi-select. Then tell us your flavor."
      canContinue={(data.types?.length || 0) > 0}>
      <SectionLabel dark>EVENT TYPES</SectionLabel>
      <PillGrid dark multi value={data.types} setValue={v=>setData({...data,types:v})} options={[
        {id:'concerts',label:'Concerts',hint:'🎤'},
        {id:'sports',label:'Sports',hint:'🏟️'},
        {id:'festivals',label:'Festivals',hint:'🎪'},
        {id:'theater',label:'Theater & comedy',hint:'🎭'},
        {id:'none',label:'Not really my thing',hint:'🛋️'},
      ]}/>
      <CascadeSection dark label="GO DEEPER"
        parentSel={(data.types || []).filter(x => EVENT_TYPES[x])}
        childOptions={EVENT_TYPES}
        childValues={data.subtypes || {}}
        setChildValues={v => setData({ ...data, subtypes: v })}
        childLabel={pid => `${pid.toUpperCase()} · TAP STYLES`}/>
      <SectionLabel dark>HOW MANY PER YEAR</SectionLabel>
      <PillGrid dark value={data.freq} setValue={v=>setData({...data,freq:v})} options={[
        '1–3','4–8','9–15','16+'
      ]}/>
    </LuxShell>
  );
}

// ─────── L6 Sports Leagues + Teams (cascading) ───────
const LEAGUE_TEAMS = {
  nfl: ['Chiefs','49ers','Cowboys','Eagles','Bills','Ravens','Packers','Patriots','Other'],
  nba: ['Lakers','Warriors','Celtics','Heat','Nuggets','Bucks','Knicks','Suns','Other'],
  mlb: ['Yankees','Dodgers','Red Sox','Cubs','Giants','Mets','Braves','Astros','Other'],
  mls: ['Inter Miami','LAFC','Atlanta United','NYC FC','Seattle','Other'],
  f1:  ['Red Bull','Ferrari','Mercedes','McLaren','Aston Martin','NASCAR fan','Other'],
};
function Level6({ data, setData, ...p }) {
  const teams = data.teams || {};
  return (
    <LuxShell {...p} levelNum={6} reward={3} dark iconName="leagues"
      title={<GoldHeadline text="WHICH **LEAGUES** DO YOU FOLLOW?"/>}
      subtitle="Tap leagues. Then tell us your team."
      canContinue={(data.leagues?.length || 0) > 0}>
      <PillGrid dark multi value={data.leagues} setValue={v=>setData({...data,leagues:v})} options={[
        {id:'nfl',label:'NFL',hint:'🏈'},
        {id:'nba',label:'NBA',hint:'🏀'},
        {id:'mlb',label:'MLB',hint:'⚾'},
        {id:'mls',label:'MLS / Soccer',hint:'⚽'},
        {id:'f1',label:'F1 / NASCAR',hint:'🏎️'},
        {id:'none',label:'Not a sports person',hint:'🎬'},
      ]}/>
      <CascadeSection dark label="YOUR TEAM · PICK ONE PER LEAGUE"
        parentSel={(data.leagues || []).filter(x => LEAGUE_TEAMS[x])}
        childOptions={Object.fromEntries(Object.entries(LEAGUE_TEAMS).map(([k,v])=>[k,v.map(t=>({id:t,label:t}))]))}
        childValues={teams}
        setChildValues={v => setData({ ...data, teams: v })}
        childLabel={pid => `${pid.toUpperCase()} · YOUR TEAM`}/>
    </LuxShell>
  );
}

// ─────── L7 Dining (multi-axis) ───────
function Level7({ data, setData, firstName, ...p }) {
  return (
    <LuxShell {...p} levelNum={7} reward={2} dark iconName="dining"
      title={<GoldHeadline text={firstName ? `NICE, ${firstName.toUpperCase()} — WHEN YOU **EAT OUT**?` : `WHEN YOU **EAT OUT**, WHAT'S THE MIX?`}/>}
      subtitle="Multi-select all axes. Most people are a blend."
      canContinue={(data.tiers?.length || 0) > 0}>
      <SectionLabel dark>PRICE TIER · MULTI</SectionLabel>
      <PillGrid dark multi value={data.tiers} setValue={v=>setData({...data,tiers:v})} options={[
        {id:'qsr',label:'Quick service — McDonald\'s, Chick-fil-A',hint:'🍔'},
        {id:'fastcasual',label:'Fast casual — Chipotle, Sweetgreen',hint:'🥗'},
        {id:'midrange',label:'Mid-range sit-down',hint:'🍝'},
        {id:'finedining',label:'Fine dining — tasting menus',hint:'🥂'},
        {id:'omakase',label:'Omakase / chef\'s counter',hint:'🍣'},
      ]}/>
      <SectionLabel dark>CUISINES YOU CHASE</SectionLabel>
      <PillGrid dark multi value={data.cuisines} setValue={v=>setData({...data,cuisines:v})} options={[
        {id:'italian',label:'Italian',hint:'🍕'},{id:'japanese',label:'Japanese',hint:'🍱'},
        {id:'french',label:'French',hint:'🥖'},{id:'mexican',label:'Mexican',hint:'🌮'},
        {id:'mediterranean',label:'Mediterranean',hint:'🫒'},{id:'chinese',label:'Chinese',hint:'🥟'},
        {id:'steakhouse',label:'Steakhouse',hint:'🥩'},{id:'thai',label:'Thai',hint:'🍜'},
        {id:'indian',label:'Indian',hint:'🍛'},{id:'plant',label:'Plant-based',hint:'🌱'},
      ]}/>
      <SectionLabel dark>WHEN YOU TRAVEL · DINING STYLE</SectionLabel>
      <PillGrid dark multi value={data.travelDining} setValue={v=>setData({...data,travelDining:v})} options={[
        {id:'roomservice',label:'Room service',hint:'🛎️'},
        {id:'hotelrest',label:'Hotel restaurant',hint:'🏨'},
        {id:'localspots',label:'Venture out — local spots',hint:'🗺️'},
        {id:'reservations',label:'Plan reservations weeks ahead',hint:'📅'},
        {id:'delivery',label:'Order delivery',hint:'📱'},
      ]}/>
    </LuxShell>
  );
}

// ─────── L8 Trip Planner — cascading destinations ───────
const REGION_COUNTRIES = {
  europe: ['Italy','France','Spain','Portugal','UK','Greece','Switzerland','Iceland','Croatia','Other'],
  caribbean: ['Bahamas','St. Lucia','Turks & Caicos','Aruba','Jamaica','Dominican Republic','St. Barts','Anguilla','Other'],
  asia: ['Japan','Thailand','Vietnam','Indonesia (Bali)','Singapore','South Korea','Maldives','India','Other'],
  domestic: ['Hawaii','New York','California','Florida','Las Vegas','Colorado','Utah / Nat\'l Parks','New England','Other'],
  mexico: ['Cabo','Tulum / Riviera Maya','Mexico City','Puerto Vallarta','Cancún','Other'],
  africa: ['Morocco','South Africa','Kenya / Tanzania','Egypt','Seychelles','Other'],
  samerica: ['Brazil','Argentina','Peru','Chile','Colombia','Other'],
  middleeast: ['UAE (Dubai)','Saudi Arabia','Israel','Jordan','Qatar','Other'],
  oceania: ['Australia','New Zealand','Fiji','French Polynesia','Other'],
};
const COUNTRY_CITIES = {
  // Europe
  'Italy': ['Rome','Milan','Florence','Venice','Amalfi Coast','Lake Como','Sicily','Other'],
  'France': ['Paris','French Riviera','Provence','Loire Valley','Other'],
  'Spain': ['Barcelona','Madrid','Ibiza','Mallorca','Seville','Other'],
  'Portugal': ['Lisbon','Porto','Algarve','Madeira','Other'],
  'UK': ['London','Edinburgh','Cotswolds','Other'],
  'Greece': ['Santorini','Mykonos','Athens','Crete','Other'],
  'Switzerland': ['Zurich','Geneva','Zermatt','St. Moritz','Other'],
  'Iceland': ['Reykjavik','Ring Road','Other'],
  'Croatia': ['Dubrovnik','Hvar','Split','Other'],
  // Caribbean
  'Bahamas': ['Nassau','Exuma','Other'],
  'St. Lucia': ['Soufrière','Rodney Bay','Other'],
  'Turks & Caicos': ['Providenciales','Grace Bay','Other'],
  'Aruba': ['Palm Beach','Eagle Beach','Other'],
  'Jamaica': ['Montego Bay','Negril','Ocho Rios','Other'],
  // Asia
  'Japan': ['Tokyo','Kyoto','Osaka','Hakone','Okinawa','Other'],
  'Thailand': ['Bangkok','Phuket','Koh Samui','Chiang Mai','Other'],
  'Vietnam': ['Hanoi','Ho Chi Minh','Hoi An','Halong Bay','Other'],
  'Indonesia (Bali)': ['Ubud','Seminyak','Nusa Dua','Other'],
  'Maldives': ['North Malé','South Malé','Baa Atoll','Other'],
  // Domestic
  'Hawaii': ['Maui','Oahu','Kauai','Big Island','Other'],
  'New York': ['NYC','Hudson Valley','Hamptons','Other'],
  'California': ['LA','SF / Bay Area','Napa / Sonoma','San Diego','Big Sur','Other'],
  'Florida': ['Miami','Orlando','Naples','Key West','Other'],
  'Colorado': ['Aspen','Vail','Denver','Telluride','Other'],
  // Mexico
  'Cabo': ['San José del Cabo','Cabo San Lucas','East Cape','Other'],
  'Tulum / Riviera Maya': ['Tulum','Playa del Carmen','Riviera Maya','Other'],
  // UAE
  'UAE (Dubai)': ['Dubai','Abu Dhabi','Other'],
};

// Region selector — was an absolute-positioned "world map" with overlapping
// pills on small viewports. Replaced with a clean flex-wrap pill grid grouped
// by hemisphere/continent so labels never collide. Background grid + emoji
// hint preserve the "TAP A REGION · DREAM BIG" visual interest.
function RegionMap({ regions, setRegions }) {
  const REGION_GROUPS = [
    { label: 'Americas',     items: [
      { id: 'domestic',  label: 'US',         emoji: '🇺🇸' },
      { id: 'mexico',    label: 'Mexico',     emoji: '🌮' },
      { id: 'caribbean', label: 'Caribbean',  emoji: '🏝️' },
      { id: 'samerica',  label: 'S. America', emoji: '🦋' },
    ]},
    { label: 'EMEA',         items: [
      { id: 'europe',     label: 'Europe',  emoji: '🏛️' },
      { id: 'middleeast', label: 'M. East', emoji: '🕌' },
      { id: 'africa',     label: 'Africa',  emoji: '🦁' },
    ]},
    { label: 'Asia-Pacific', items: [
      { id: 'asia',    label: 'Asia',    emoji: '🏯' },
      { id: 'oceania', label: 'Oceania', emoji: '🐨' },
    ]},
  ];
  const sel = (id) => regions?.includes(id);
  const toggle = (id) => {
    const cur = regions || [];
    setRegions(cur.includes(id) ? cur.filter(x => x !== id) : [...cur, id]);
  };
  return (
    <div style={{
      position: 'relative',
      width: '100%',
      background: 'linear-gradient(135deg, rgba(246,133,34,0.06), rgba(255,255,255,0.02))',
      border: '1px solid rgba(245,240,232,0.10)',
      borderRadius: 14,
      overflow: 'hidden',
      marginTop: 6,
      padding: '12px 12px 14px',
    }}>
      {/* Subtle grid background — purely decorative */}
      <svg viewBox="0 0 100 50" preserveAspectRatio="none" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%',
        opacity: 0.14, pointerEvents: 'none',
      }}>
        {[10,20,30,40].map(y => (
          <line key={'h'+y} x1="0" y1={y} x2="100" y2={y} stroke="#F68522" strokeWidth="0.1"/>
        ))}
        {[20,40,60,80].map(x => (
          <line key={'v'+x} x1={x} y1="0" x2={x} y2="50" stroke="#F68522" strokeWidth="0.1"/>
        ))}
      </svg>

      {REGION_GROUPS.map((group, gi) => (
        <div key={group.label} style={{
          position: 'relative', zIndex: 2,
          marginTop: gi === 0 ? 0 : 12,
        }}>
          <div style={{
            fontFamily: "'JetBrains Mono', monospace", fontSize: 8.5,
            letterSpacing: 1.6, color: 'rgba(245,240,232,0.42)',
            fontWeight: 700, marginBottom: 6, textTransform: 'uppercase',
          }}>{group.label}</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {group.items.map(r => {
              const isSel = sel(r.id);
              return (
                <button key={r.id} onClick={() => toggle(r.id)} style={{
                  padding: '7px 12px',
                  background: isSel ? LUX.gold : 'rgba(10,10,10,0.55)',
                  border: `1.5px solid ${isSel ? LUX.gold : 'rgba(246,133,34,0.45)'}`,
                  color: isSel ? '#FFFFFF' : LUX.cream,
                  fontFamily: "'JetBrains Mono', monospace",
                  fontSize: 10, letterSpacing: 1.2, fontWeight: 700,
                  borderRadius: 100,
                  cursor: 'pointer',
                  boxShadow: isSel ? `0 0 18px ${LUX.gold}, 0 0 0 4px rgba(246,133,34,0.18)` : 'none',
                  transition: 'all 220ms cubic-bezier(.34,1.56,.64,1)',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  whiteSpace: 'nowrap',
                }}>
                  <span style={{ fontSize: 13, lineHeight: 1 }}>{r.emoji}</span>
                  {r.label.toUpperCase()}
                </button>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}

function Level8({ data, setData, ...p }) {
  const status = data.status; // 'booked' | 'planning' | 'dreaming' | undefined
  const isLockedNo = status === 'no';
  const showDeep = status && status !== 'no';
  const can = !!status && (isLockedNo || (data.regions?.length || 0) > 0);

  return (
    <LuxShell {...p} levelNum={8} reward={3} dark iconName="trip"
      title={<GoldHeadline text="GOT A TRIP **PLANNED**?"/>}
      subtitle="Even a daydream counts. Tell us where."
      canContinue={can}>
      {/* Status gate */}
      <PillGrid dark value={data.status} setValue={v=>setData({...data,status:v})} options={[
        {id:'booked',label:'Already booked it',hint:'✅'},
        {id:'planning',label:'Actively planning',hint:'🗓️'},
        {id:'dreaming',label:'Dreaming / open to ideas',hint:'💭'},
        {id:'no',label:'Nothing on the radar',hint:'🛋️'},
      ]}/>

      {showDeep && (
        <>
          <SectionLabel dark>WHEN</SectionLabel>
          <PillGrid dark value={data.window} setValue={v=>setData({...data,window:v})} options={[
            '< 30 days','1–3 months','3–6 months','6–12 months','12+ months / someday'
          ]}/>

          <SectionLabel dark>REGION · TAP ALL THAT APPLY · DREAM BIG</SectionLabel>
          <RegionMap regions={data.regions} setRegions={v => setData({...data, regions: v})}/>

          {/* Cascade: regions → countries */}
          <CascadeSection dark label="COUNTRY · TAP ALL THAT APPLY"
            parentSel={(data.regions || []).filter(r => REGION_COUNTRIES[r])}
            childOptions={Object.fromEntries(
              Object.entries(REGION_COUNTRIES).map(([k,v]) => [k, v.map(c => ({id:c,label:c}))])
            )}
            childValues={data.countries || {}}
            setChildValues={v => setData({...data, countries: v})}
            childLabel={pid => `${pid.toUpperCase()} · COUNTRIES`}/>

          {/* Cascade: countries → cities (only for countries with sub-options) */}
          {(() => {
            const allCountries = Object.values(data.countries || {}).flat()
              .filter(c => COUNTRY_CITIES[c]);
            if (!allCountries.length) return null;
            return (
              <CascadeSection dark label="CITY / AREA · TAP ALL THAT APPLY"
                parentSel={allCountries}
                childOptions={Object.fromEntries(
                  allCountries.map(c => [c, COUNTRY_CITIES[c].map(x => ({id:x,label:x}))])
                )}
                childValues={data.cities || {}}
                setChildValues={v => setData({...data, cities: v})}
                childLabel={pid => `${pid.toUpperCase()}`}/>
            );
          })()}

          <SectionLabel dark>TRIP STYLE · MULTI</SectionLabel>
          <PillGrid dark multi value={data.styles} setValue={v=>setData({...data,styles:v})} options={[
            {id:'resort',label:'Resort relax',hint:'🌴'},
            {id:'city',label:'City exploration',hint:'🏙️'},
            {id:'wellness',label:'Wellness / spa',hint:'🧘'},
            {id:'adventure',label:'Adventure',hint:'🏔️'},
            {id:'beach',label:'Beach',hint:'🏖️'},
            {id:'cultural',label:'Cultural',hint:'🏛️'},
            {id:'romantic',label:'Romantic',hint:'💕'},
            {id:'family',label:'Family',hint:'👨‍👩‍👧'},
            {id:'ski',label:'Ski / winter',hint:'⛷️'},
            {id:'foodie',label:'Foodie tour',hint:'🍷'},
          ]}/>

          <SectionLabel dark>WHO'S COMING</SectionLabel>
          <PillGrid dark value={data.party} setValue={v=>setData({...data,party:v})} options={[
            {id:'solo',label:'Solo',hint:'🚶'},
            {id:'couple',label:'Couple',hint:'💑'},
            {id:'family',label:'Family w/ kids',hint:'👨‍👩‍👧'},
            {id:'multigen',label:'Multi-gen',hint:'👴👶'},
            {id:'friends',label:'Friends group',hint:'👯'},
          ]}/>

          <SectionLabel dark>NIGHTS</SectionLabel>
          <PillGrid dark value={data.nights} setValue={v=>setData({...data,nights:v})} options={[
            'Weekend (1–3)','4–7','8–14','15+'
          ]}/>

          <SectionLabel dark>BUDGET PER NIGHT · USD</SectionLabel>
          <PillGrid dark value={data.budget} setValue={v=>setData({...data,budget:v})} options={[
            '< $200','$200–400','$400–800','$800–1,500','$1,500+'
          ]}/>

          <SectionLabel dark>OCCASION · OPTIONAL</SectionLabel>
          <PillGrid dark value={data.occasion} setValue={v=>setData({...data,occasion:v})} options={[
            {id:'none',label:'Just because',hint:'🌟'},
            {id:'anniv',label:'Anniversary',hint:'💍'},
            {id:'honey',label:'Honeymoon',hint:'🥂'},
            {id:'bday',label:'Birthday',hint:'🎂'},
            {id:'baby',label:'Babymoon',hint:'🤰'},
            {id:'reunion',label:'Reunion',hint:'🥹'},
            {id:'graduation',label:'Graduation',hint:'🎓'},
          ]}/>

          <SectionLabel dark>WHAT WOULD MAKE THIS TRIP PERFECT? · MULTI</SectionLabel>
          <PillGrid dark multi value={data.perks} setValue={v=>setData({...data,perks:v})} options={[
            {id:'suite',label:'Suite upgrade',hint:'🛏️'},
            {id:'spa',label:'Spa credit',hint:'💆'},
            {id:'late',label:'Late checkout',hint:'⏰'},
            {id:'fnb',label:'F&B credit',hint:'🍷'},
            {id:'transfer',label:'Airport transfer',hint:'🚗'},
            {id:'kids',label:'Kids\' club',hint:'🎈'},
            {id:'club',label:'Club lounge access',hint:'🥂'},
            {id:'experience',label:'Curated experience',hint:'🗝️'},
            {id:'private',label:'Private guide',hint:'🧭'},
          ]}/>

          {/* Soft pre-offer card — Marriott 'package preview' */}
          {(data.regions?.length > 0) && (
            <div style={{
              marginTop: 18,
              padding: '14px 16px',
              background: 'linear-gradient(135deg, rgba(196,163,90,0.12), rgba(196,163,90,0.04))',
              border: `1px solid ${LUX.gold}`,
              borderRadius: 14,
            }}>
              <div style={{
                fontFamily: "'JetBrains Mono', monospace", fontSize: 8.5, letterSpacing: 1.8,
                color: LUX.gold, fontWeight: 700, marginBottom: 6,
              }}>BONVOY · PACKAGE PREVIEW</div>
              <div style={{
                fontFamily: 'Inter, sans-serif', fontWeight: 900,
                fontSize: 18, color: LUX.cream, lineHeight: 1.15, marginBottom: 6,
                letterSpacing: -0.3,
              }}>
                {(() => {
                  const cities = Object.values(data.cities || {}).flat();
                  const countries = Object.values(data.countries || {}).flat();
                  const dest = cities[0] || countries[0] || (data.regions[0] || 'somewhere');
                  return `Curating your ${dest} package…`;
                })()}
              </div>
              <div style={{
                fontFamily: 'Inter', fontSize: 12, color: 'rgba(245,240,232,0.65)', lineHeight: 1.5,
              }}>
                We'll pre-build options across Bonvoy properties and surface them after you finish.
                You can opt in for a Bonvoy concierge to reach out — or just keep your data.
              </div>
            </div>
          )}
        </>
      )}

      {isLockedNo && (
        <div style={{
          marginTop: 16, padding: '14px 16px',
          background: 'rgba(245,240,232,0.04)',
          border: `1px solid rgba(245,240,232,0.1)`,
          borderRadius: 14,
        }}>
          <div style={{
            fontFamily: 'Inter', fontSize: 13, color: 'rgba(245,240,232,0.7)', lineHeight: 1.45,
          }}>No worries. We'll skip the trip questions and keep moving.</div>
        </div>
      )}
    </LuxShell>
  );
}

// ─────── L9 Booking Behavior (luxury-relevant identity) ───────
function Level9({ data, setData, ...p }) {
  return (
    <LuxShell {...p} levelNum={9} reward={1} dark iconName="booking"
      title={<GoldHeadline text="WHEN YOU **BOOK**, WHO ARE YOU?"/>}
      subtitle="Multi-select. Be honest. Or don't."
      canContinue={(data.psy?.length || 0) > 0}>
      <PillGrid dark multi value={data.psy} setValue={v=>setData({...data,psy:v})} options={[
        {id:'status',label:'Status seeker — chase elite tier',hint:'👑'},
        {id:'collector',label:'Experience collector',hint:'🗺️'},
        {id:'loyalmax',label:'Loyalty maximizer — points first',hint:'💳'},
        {id:'deal',label:'Deal hunter',hint:'🔍'},
        {id:'brand',label:'Brand loyal',hint:'🏛️'},
        {id:'spontaneous',label:'Spontaneous booker',hint:'⚡'},
        {id:'planner',label:'Itinerary obsessive',hint:'📋'},
        {id:'bleisure',label:'Bleisure — mix work + play',hint:'💼'},
        {id:'wellness',label:'Wellness-focused',hint:'🌿'},
        {id:'sustainability',label:'Sustainability matters',hint:'♻️'},
      ]}/>
    </LuxShell>
  );
}

// ─────── L10 Sponsor — Marriott Bonvoy ───────
function Level10({ data, setData, ...p }) {
  const can = !!(data.brand && data.cards?.length >= 0 && data.intent && data.nps);
  const okToContinue = !!(data.brand && data.intent && data.nps);
  return (
    <LuxShell {...p} levelNum={10} reward={3} dark iconName="sponsor"
      title={<GoldHeadline text="A WORD FROM **MARRIOTT** BONVOY."/>}
      subtitle="Last stretch. Real questions, real answers."
      ctaLabel="Finish · Bank Entries" canContinue={okToContinue}>
      {/* Sponsor banner */}
      <div style={{
        padding: '14px 16px', marginBottom: 16,
        background: 'rgba(196,163,90,0.08)',
        border: `1px solid ${LUX.gold}`,
        borderRadius: 12,
        textAlign: 'center',
      }}>
        <div style={{
          fontFamily: "'JetBrains Mono', monospace", fontSize: 9, letterSpacing: 2,
          color: LUX.gold, fontWeight: 700, marginBottom: 4,
        }}>SPONSORED · RESERVED SLOT</div>
        <div style={{
          fontFamily: 'Inter, sans-serif', fontWeight: 900,
          fontSize: 22, color: LUX.cream, letterSpacing: -0.3,
        }}>Marriott Bonvoy</div>
      </div>

      <SectionLabel dark>Q1 · WHICH BRAND IS THE BEST FIT FOR YOUR NEXT TRIP?</SectionLabel>
      <PillGrid dark value={data.brand} setValue={v=>setData({...data,brand:v})} options={[
        {id:'ritz',label:'The Ritz-Carlton',hint:'✨'},
        {id:'stregis',label:'St. Regis',hint:'🥂'},
        {id:'edition',label:'EDITION',hint:'🎨'},
        {id:'westin',label:'Westin',hint:'🌿'},
        {id:'autograph',label:'Autograph Collection',hint:'🏛️'},
        {id:'courtyard',label:'Courtyard',hint:'💼'},
        {id:'residence',label:'Residence Inn',hint:'🏠'},
        {id:'unsure',label:'Not sure yet',hint:'🤔'},
      ]}/>

      <SectionLabel dark>Q2 · WHICH BONVOY CARDS ARE IN YOUR WALLET?</SectionLabel>
      <PillGrid dark multi value={data.cards} setValue={v=>setData({...data,cards:v})} options={[
        {id:'brilliant',label:'Bonvoy Brilliant (Amex)',hint:'💳'},
        {id:'boundless',label:'Bonvoy Boundless (Chase)',hint:'💳'},
        {id:'bevy',label:'Bonvoy Bevy (Amex)',hint:'💳'},
        {id:'bold',label:'Bonvoy Bold (Chase)',hint:'💳'},
        {id:'business',label:'Bonvoy Business (Amex)',hint:'💼'},
        {id:'none',label:'No Bonvoy card',hint:'🚫'},
        {id:'considering',label:'Considering one',hint:'👀'},
      ]}/>

      <SectionLabel dark>Q3 · BOOKING INTENT · NEXT 12 MONTHS</SectionLabel>
      <PillGrid dark value={data.intent} setValue={v=>setData({...data,intent:v})} options={[
        {id:'booked',label:'Already booked',hint:'✅'},
        {id:'planning',label:'Actively planning',hint:'🗓️'},
        {id:'considering',label:'Considering',hint:'💭'},
        {id:'unsure',label:'Nothing planned',hint:'🤷'},
      ]}/>

      <SectionLabel dark>Q4 · LIKELIHOOD TO RECOMMEND BONVOY · 1–5</SectionLabel>
      <div style={{
        fontFamily: 'Inter', fontSize: 11, color: 'rgba(245,240,232,0.5)',
        marginBottom: 10,
      }}>1 = not at all · 5 = absolutely</div>
      <RatingScale dark value={data.nps} setValue={v=>setData({...data,nps:v})}/>
    </LuxShell>
  );
}

Object.assign(window, {
  Level1, Level2, Level3, Level4, Level5,
  Level6, Level7, Level8, Level9, Level10,
});
