// All page components. Globally registered.

/* ─────────────────── HOME ─────────────────── */
function HomePage({ tweaks, brand }) {
  return (
    <div>
      <h1 className="page-title">Hi Marco — here's your command center.</h1>
      <p className="page-sub">{brand.name} · {brand.tagline} · {PROJECT.events} events · {PROJECT.stations} touchpoints</p>

      <AtlediCard
        msg={<>Coachella Day 1 is <strong>live</strong>. <strong>47 people</strong> have played in the last hour, and <strong>Holo Sunnies are 85% gone</strong> at Main Stage. At this rate, you'll run out in ~2 hours.</>}
        actions={['Re-route sunnies →', 'See station live', 'What worked best?']}
      />

      <div className="grid-4" style={{ marginTop: 20 }}>
        {KPIS.map((k, i) => <KpiCard key={i} {...k} />)}
      </div>

      <div className="row" style={{ marginTop: 24, alignItems: 'flex-start' }}>
        <div style={{ flex: 1.6 }}>
          <div className="section-title" style={{ margin: '0 0 12px' }}>My next events</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {UPCOMING.map((e, i) => <EventRow key={i} {...e} />)}
          </div>
        </div>
        <div style={{ flex: 1 }}>
          <div className="section-title" style={{ margin: '0 0 12px' }}>Live pulse</div>
          <div className="card">
            <div className="card-header">
              <h3>Engagement funnel</h3>
              <span className="pill live">Live</span>
            </div>
            <FunnelBars />
          </div>
          <div className="card" style={{ marginTop: 14 }}>
            <div className="card-header"><h3>Recent activity</h3></div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {ACTIVITY.map((a, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, fontSize: 13 }}>
                  <div style={{ width: 6, height: 6, borderRadius: '50%', background: i === 0 ? 'var(--lime)' : 'var(--line-2)', marginTop: 6, flexShrink: 0 }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ color: 'var(--text)' }}>{a.text}</div>
                    <div style={{ color: 'var(--text-muted)', fontSize: 11, marginTop: 2 }}>{a.when}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function AtlediCard({ msg, actions }) {
  return (
    <div className="atledi">
      <div className="atledi-orb" />
      <div className="atledi-body">
        <div className="atledi-label">
          <IconSparkles size={12} /> Atledi · narrative insight
        </div>
        <p className="atledi-msg">{msg}</p>
        <div className="atledi-actions">
          {actions.map((a, i) => (
            <button key={i} className={"atledi-action" + (i === 0 ? ' primary' : '')}>{a}</button>
          ))}
        </div>
      </div>
      <button className="icon-btn" title="dismiss">✕</button>
    </div>
  );
}

function KpiCard({ lbl, val, delta, dir, spark, note }) {
  return (
    <div className="kpi">
      <div className="lbl">{lbl}</div>
      <div className="val mono">{val}</div>
      <div className={"delta " + (dir === 'up' ? 'up' : 'down')}>
        {dir === 'up' ? <IconArrowUp size={12} /> : <IconArrowDown size={12} />}
        {delta} {note && <span style={{ color: 'var(--text-muted)', marginLeft: 4 }}>· {note}</span>}
      </div>
      <div className="spark"><Sparkline data={spark} color={dir === 'up' ? '#C8E530' : '#f4b740'} /></div>
    </div>
  );
}

function EventRow({ name, location, when, status, stations, cover, initial }) {
  return (
    <div className="event-card">
      <div className="event-cover" style={{ background: cover }}>
        <span style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 22, color: 'rgba(0,0,0,0.5)' }}>{initial}</span>
      </div>
      <div>
        <div className="event-name">{name}</div>
        <div className="event-meta">
          <span>{location}</span>
          <span className="dot">·</span>
          <span>{stations > 0 ? `${stations} touchpoints` : 'No touchpoints yet'}</span>
        </div>
      </div>
      <div className="event-side">
        {status === 'live' && <span className="pill live">Live now</span>}
        {status === 'ready' && <span className="pill green">Ready</span>}
        {status === 'draft' && <span className="pill">Draft</span>}
        <div className="event-side"><div className="when">{when}</div></div>
      </div>
    </div>
  );
}

function FunnelBars() {
  const steps = [
    { lbl: 'QR scanned', val: 1240, pct: 100, color: '#C8E530' },
    { lbl: 'Survey started', val: 1118, pct: 90, color: '#a9d028' },
    { lbl: 'Survey completed', val: 982, pct: 79, color: '#8fb524' },
    { lbl: 'Played game', val: 947, pct: 76, color: '#6e9020' },
    { lbl: 'Prize won', val: 947, pct: 76, color: '#506a17' },
  ];
  return (
    <div>
      {steps.map((s, i) => (
        <div key={i} className="bar-row">
          <div className="lbl">{s.lbl}</div>
          <div className="bar" style={{ background: 'var(--ink-4)' }}>
            <span style={{ width: s.pct + '%', background: s.color }} />
          </div>
          <div className="num">{s.val.toLocaleString()}</div>
        </div>
      ))}
    </div>
  );
}

/* ─────────────────── BRAND STUDIO ─────────────────── */
function BrandStudio({ tweaks, brand, setTweak }) {
  const [tab, setTab] = React.useState('Identity');
  const [previewScreen, setPreviewScreen] = React.useState('survey');
  const tabs = ['Identity', 'Experience', 'Look & feel', 'Game', 'Prizes', 'Output'];

  return (
    <div>
      <h1 className="page-title">Brand Studio</h1>
      <p className="page-sub">Design the moment. Every change is live in the preview.</p>

      <div className="studio">
        <div>
          <div className="tabs">
            {tabs.map(t => (
              <button key={t} className={"tab" + (t === tab ? ' active' : '')} onClick={() => setTab(t)}>{t}</button>
            ))}
          </div>

          {tab === 'Identity' && <IdentityTab tweaks={tweaks} setTweak={setTweak} brand={brand} />}
          {tab === 'Experience' && <ExperienceTab tweaks={tweaks} setTweak={setTweak} />}
          {tab === 'Look & feel' && <LookFeelTab tweaks={tweaks} setTweak={setTweak} />}
          {tab === 'Game' && <GameTab tweaks={tweaks} setTweak={setTweak} />}
          {tab === 'Prizes' && <PrizesTab />}
          {tab === 'Output' && <OutputTab />}
        </div>

        <div className="phone-wrap">
          <div className="phone-controls">
            <button className={previewScreen === 'survey' ? 'active' : ''} onClick={() => setPreviewScreen('survey')}>Survey</button>
            <button className={previewScreen === 'wheel' ? 'active' : ''} onClick={() => setPreviewScreen('wheel')}>Game</button>
            <button className={previewScreen === 'prize' ? 'active' : ''} onClick={() => setPreviewScreen('prize')}>Prize</button>
          </div>
          <div className="phone">
            <div className="phone-screen" style={{
              '--screen-bg': tweaks.previewBg,
              '--screen-fg': tweaks.previewFg,
              '--screen-accent': tweaks.brandColor,
            }}>
              {previewScreen === 'survey' && <SurveyPreview brand={brand} />}
              {previewScreen === 'wheel' && <WheelPreview brand={brand} accent={tweaks.brandColor} />}
              {previewScreen === 'prize' && <PrizePreview brand={brand} accent={tweaks.brandColor} />}
            </div>
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>Live consumer preview · iPhone 14 Pro</div>
        </div>
      </div>
    </div>
  );
}

function IdentityTab({ tweaks, setTweak, brand }) {
  const palettes = [
    ['#C8E530', '#0a0a0a'],
    ['#ff6b9d', '#1a0a14'],
    ['#9b6bff', '#0e0a1a'],
    ['#6bd9ff', '#0a141a'],
    ['#ffd66b', '#1a140a'],
    ['#4dd28b', '#0a1a12'],
  ];
  return (
    <div>
      <div className="grid-2">
        <div>
          <div className="field">
            <label>Brand name</label>
            <input type="text" defaultValue={brand.name} />
          </div>
          <div className="field">
            <label>Tagline</label>
            <input type="text" defaultValue="Pop the bottle. Pop the brand." />
          </div>
          <div className="field">
            <label>Primary color</label>
            <div className="swatches">
              {palettes.map(([c], i) => (
                <button key={i} className={"sw" + (tweaks.brandColor === c ? ' active' : '')} style={{ background: c }} onClick={() => setTweak('brandColor', c)} />
              ))}
            </div>
          </div>
          <div className="field">
            <label>Typography</label>
            <select className="input" defaultValue="Space Grotesk" style={{ background: 'var(--ink-3)', color: 'var(--text)', border: '1px solid var(--line)', borderRadius: 10, padding: '11px 14px' }}>
              <option>Space Grotesk</option>
              <option>DM Sans</option>
              <option>Inter</option>
              <option>Manrope</option>
              <option>Plus Jakarta Sans</option>
            </select>
          </div>
        </div>
        <div>
          <div className="field">
            <label>Logo · primary</label>
            <div className="upload-box">
              <div style={{ width: 56, height: 56, margin: '0 auto 10px', borderRadius: 14, background: brand.logoGradient, display: 'grid', placeItems: 'center', color: '#4a1414', fontWeight: 700, fontSize: 22, fontFamily: 'Space Grotesk' }}>{brand.initials}</div>
              <div>Logo.svg uploaded — replace</div>
            </div>
          </div>
          <div className="field">
            <label>Logo · secondary (white)</label>
            <div className="upload-box">Drop white version here</div>
          </div>
        </div>
      </div>

      <div style={{ background: 'var(--ink-3)', border: '1px solid var(--line)', borderRadius: 12, padding: 14, display: 'flex', gap: 12, alignItems: 'center', fontSize: 13 }}>
        <IconSparkles size={18} stroke="var(--lime)" />
        <div style={{ flex: 1 }}>
          <div style={{ color: 'var(--lime)', fontSize: 11, textTransform: 'uppercase', letterSpacing: 0.6, marginBottom: 2 }}>Atledi suggestion</div>
          <div>Your logo skews pink + warm yellow. Try the pink palette below — your hub looks 2x more on-brand when the wheel mirrors your gradient.</div>
        </div>
        <button className="btn sm primary">Apply</button>
      </div>
    </div>
  );
}

function ExperienceTab({ tweaks, setTweak }) {
  const features = [
    { id: 'consent', label: 'Consent', desc: 'Bilingual T&C agreement' },
    { id: 'ageGate', label: 'Age gate (21+)', desc: 'Required for alcohol activations' },
    { id: 'demographics', label: 'Demographics', desc: 'Age, gender, ethnicity, nationality' },
    { id: 'leadCapture', label: 'Lead capture', desc: 'Name, email, phone — pushes to CRM' },
    { id: 'bilingual', label: 'Bilingual (EN + ES)', desc: 'Toggleable per consumer' },
  ];
  return (
    <div>
      <p style={{ fontSize: 13, color: 'var(--text-dim)', margin: '0 0 14px' }}>Toggle features on or off. Reorder by dragging. The system handles the flow.</p>
      {features.map(f => (
        <div className="feature-row" key={f.id}>
          <div className="grip">⋮⋮</div>
          <div>
            <div className="label">{f.label}</div>
            <div className="desc">{f.desc}</div>
          </div>
          <div className="right">
            <div className={"toggle" + (tweaks[f.id] !== false ? ' on' : '')} onClick={() => setTweak(f.id, !(tweaks[f.id] !== false))} />
          </div>
        </div>
      ))}
      <button className="btn ghost" style={{ marginTop: 10 }}><IconPlus size={14} /> Add custom question</button>
    </div>
  );
}

function LookFeelTab({ tweaks, setTweak }) {
  return (
    <div>
      <div className="field">
        <label>Button style</label>
        <div style={{ display: 'flex', gap: 8 }}>
          {['Pill', 'Rounded', 'Square'].map(s => (
            <button key={s} className={"chip" + (tweaks.btnStyle === s ? ' active' : '')} onClick={() => setTweak('btnStyle', s)}>{s}</button>
          ))}
        </div>
      </div>
      <div className="field">
        <label>Celebration theme</label>
        <div style={{ display: 'flex', gap: 8 }}>
          {['Confetti', 'Soccer', 'Sparkles', 'Custom'].map(s => (
            <button key={s} className={"chip" + (tweaks.celebration === s ? ' active' : '')} onClick={() => setTweak('celebration', s)}>{s}</button>
          ))}
        </div>
      </div>
      <div className="field">
        <label>Headline copy</label>
        <input type="text" defaultValue="Spin to win Joyly merch!" />
      </div>
      <div className="field">
        <label>Consumer tone</label>
        <textarea rows={3} defaultValue="Playful. Confident. A little sparkly. Talk like a friend who hands out free stuff." style={{ resize: 'vertical' }} />
      </div>
    </div>
  );
}

function GameTab({ tweaks, setTweak }) {
  const games = [
    { id: 'wheel', name: 'Spin Wheel', tier: 'Tier 1', desc: 'Logo in hub · segments brand colors · prize photos on land' },
    { id: 'scratch', name: 'Scratch Card', tier: 'Tier 1', desc: 'Coating in secondary color — consumer rubs your brand off' },
    { id: 'pirinola', name: 'Pirinola', tier: 'Tier 1', desc: '6 outcomes · center face wears your logo' },
    { id: 'plinko', name: 'Plinko', tier: 'Tier 2', locked: true, desc: 'Ball is your logo · pegs accent color · prize photo buckets' },
    { id: 'slot', name: 'Slot Machine', tier: 'Tier 2', locked: true, desc: 'Reel symbols = xotskies · classic dopamine loop' },
    { id: 'loteria', name: 'Lotería Jackpot', tier: 'Tier 2', locked: true, desc: 'Cultural fit · call-outs in your brand voice' },
  ];
  return (
    <div>
      <div className="grid-3">
        {games.map(g => (
          <div key={g.id} className={"card"} style={{
            cursor: g.locked ? 'default' : 'pointer',
            borderColor: tweaks.game === g.id ? 'var(--lime)' : 'var(--line)',
            opacity: g.locked ? 0.7 : 1,
            position: 'relative',
          }} onClick={() => !g.locked && setTweak('game', g.id)}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              <span className={"pill " + (g.tier === 'Tier 1' ? 'lime' : '')}>{g.tier}</span>
              {g.locked && <span style={{ fontSize: 11, color: 'var(--warn)' }}>🔒 upgrade</span>}
              {tweaks.game === g.id && <span className="pill green" style={{ marginLeft: 'auto' }}>Selected</span>}
            </div>
            <div style={{ fontSize: 15, fontWeight: 600, fontFamily: 'Space Grotesk', marginBottom: 6 }}>{g.name}</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.5 }}>{g.desc}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PrizesTab() {
  return (
    <div>
      <p style={{ fontSize: 13, color: 'var(--text-dim)', margin: '0 0 14px' }}>Pick xotskies from your merch · set rarity (1 = ultra-rare, 5 = common).</p>
      <div className="grid-3">
        {MERCH.slice(0, 6).map((m, i) => (
          <div key={i} className="card" style={{ padding: 14 }}>
            <div style={{ display: 'flex', gap: 12 }}>
              <div style={{ width: 56, height: 56, borderRadius: 10, background: m.color, flexShrink: 0 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{m.name}</div>
                <div style={{ fontSize: 11, color: 'var(--text-muted)', fontFamily: 'Space Mono', marginTop: 2 }}>{m.available}/{m.initial}</div>
                <div style={{ display: 'flex', gap: 2, marginTop: 6, color: '#f4b740' }}>
                  {[1,2,3,4,5].map(n => <IconStar key={n} size={12} stroke="none" fill={n <= m.rarity ? '#f4b740' : '#262626'} />)}
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function OutputTab() {
  return (
    <div>
      <div className="grid-2">
        <div className="card">
          <div className="card-header"><h3>Branded QR code</h3><span className="pill lime">Tier 1</span></div>
          <div style={{ aspectRatio: 1, background: '#fff', borderRadius: 14, display: 'grid', placeItems: 'center', padding: 22 }}>
            <FakeQR brand="J" />
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
            <button className="btn"><IconDownload size={14} /> PNG</button>
            <button className="btn"><IconDownload size={14} /> SVG</button>
            <button className="btn"><IconDownload size={14} /> Print sheet</button>
          </div>
        </div>
        <div className="card">
          <div className="card-header"><h3>Shareable link</h3></div>
          <div style={{ background: 'var(--ink-3)', padding: 12, borderRadius: 10, fontFamily: 'Space Mono', fontSize: 13, color: 'var(--lime)' }}>xotski.com/s/joyly-coachella-w1</div>
          <div style={{ marginTop: 14 }}>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 6 }}>Deploy to touchpoint</div>
            <select style={{ width: '100%', background: 'var(--ink-3)', border: '1px solid var(--line)', borderRadius: 10, padding: '11px 14px', color: 'var(--text)' }}>
              <option>Coachella W1 D1 · Main Stage</option>
              <option>Coachella W1 D1 · Polo Field</option>
              <option>Coachella W1 D1 · Sahara Tent</option>
            </select>
          </div>
          <div style={{ marginTop: 14, fontSize: 12, color: 'var(--text-dim)' }}>
            <strong style={{ color: 'var(--lime)' }}>23 scans</strong> in the last hour at Main Stage.
          </div>
        </div>
      </div>
    </div>
  );
}

const FakeQR = ({ brand }) => {
  // 21x21 procedurally-fake QR
  const dots = [];
  for (let r = 0; r < 21; r++) {
    for (let c = 0; c < 21; c++) {
      const isFinder = ((r < 7 && c < 7) || (r < 7 && c > 13) || (r > 13 && c < 7));
      const inner = ((r >= 1 && r <= 5 && c >= 1 && c <= 5 && !(r >= 2 && r <= 4 && c >= 2 && c <= 4)) || (r >= 2 && r <= 4 && c >= 2 && c <= 4));
      const hash = (r * 31 + c * 17 + r * c) % 7;
      const on = isFinder ? (((r === 0 || r === 6 || c === 0 || c === 6) && r < 7 && c < 7) || ((r === 0 || r === 6 || c === 14 || c === 20) && r < 7 && c > 13) || ((r === 14 || r === 20 || c === 0 || c === 6) && r > 13 && c < 7) || (r >= 2 && r <= 4 && c >= 2 && c <= 4) || (r >= 2 && r <= 4 && c >= 16 && c <= 18) || (r >= 16 && r <= 18 && c >= 2 && c <= 4)) : (hash < 3);
      if (on) dots.push({ r, c });
    }
  }
  return (
    <svg viewBox="0 0 21 21" width="100%" height="100%">
      {dots.map(({r, c}, i) => <rect key={i} x={c} y={r} width="1" height="1" fill="#0a0a0a" />)}
      <rect x="8" y="8" width="5" height="5" fill="#fff" />
      <rect x="8.5" y="8.5" width="4" height="4" rx="0.5" fill="#ff6b9d" />
      <text x="10.5" y="11.7" fontSize="3" fill="#fff" fontWeight="700" textAnchor="middle" fontFamily="Space Grotesk">{brand}</text>
    </svg>
  );
};

function SurveyPreview({ brand }) {
  return (
    <>
      <div className="s-header">
        <div className="s-logo" style={{ background: brand.logoGradient }}>{brand.initials}</div>
        <div className="s-title">Welcome to {brand.name}</div>
        <div className="s-sub">Answer a few quick questions and spin to win merch.</div>
      </div>
      <div className="s-progress"><span /></div>
      <div className="s-question">
        <h4>How old are you?</h4>
        <div className="s-options">
          <div className="s-opt">Under 18</div>
          <div className="s-opt">18 to 25</div>
          <div className="s-opt sel">26 to 35</div>
          <div className="s-opt">36 or older</div>
        </div>
      </div>
      <div className="s-cta">Continue</div>
    </>
  );
}

function WheelPreview({ brand, accent }) {
  // 8 segments
  const segs = ['Hat', 'Tote', 'Tee', 'Stickers', 'Try again', 'Sunnies', 'Keychain', 'Fanny'];
  const colors = [brand.brandHex, '#ffd66b', '#ff6b9d', '#9b6bff', '#1a1a1a', '#6bd9ff', '#4dd28b', '#ffaa6b'];
  const segAngle = 360 / segs.length;
  return (
    <div className="wheel-wrap">
      <div className="wheel-headline">Spin to win {brand.name} merch!</div>
      <div className="wheel-sub">Tap the wheel</div>
      <div className="wheel" style={{ position: 'relative' }}>
        <div className="wheel-pin" />
        <svg viewBox="-1 -1 2 2" width="240" height="240" style={{ borderRadius: '50%' }}>
          {segs.map((s, i) => {
            const a1 = (i * segAngle - 90) * Math.PI / 180;
            const a2 = ((i + 1) * segAngle - 90) * Math.PI / 180;
            const x1 = Math.cos(a1), y1 = Math.sin(a1);
            const x2 = Math.cos(a2), y2 = Math.sin(a2);
            const mid = ((i + 0.5) * segAngle - 90) * Math.PI / 180;
            const tx = Math.cos(mid) * 0.65;
            const ty = Math.sin(mid) * 0.65;
            return (
              <g key={i}>
                <path d={`M 0 0 L ${x1} ${y1} A 1 1 0 0 1 ${x2} ${y2} Z`} fill={colors[i]} stroke="#fff" strokeWidth="0.01" />
                <text x={tx} y={ty} fontSize="0.09" fill={i === 4 ? '#fff' : '#0a0a0a'} textAnchor="middle" fontWeight="700" fontFamily="Space Grotesk" transform={`rotate(${(i + 0.5) * segAngle - 90} ${tx} ${ty})`}>{s}</text>
              </g>
            );
          })}
        </svg>
        <div className="wheel-hub" style={{ background: brand.logoGradient }}>
          <span style={{ color: '#4a1414' }}>{brand.initials}</span>
        </div>
      </div>
      <div style={{ marginTop: 'auto', padding: '14px 20px 22px', width: '100%' }}>
        <div className="s-cta" style={{ margin: 0 }}>SPIN</div>
      </div>
    </div>
  );
}

function PrizePreview({ brand, accent }) {
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '50px 20px 22px', textAlign: 'center' }}>
      <div style={{ fontSize: 11, color: 'var(--screen-fg)', opacity: 0.5, marginBottom: 8 }}>YOU WON</div>
      <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 22, marginBottom: 16 }}>Holo Sunnies ✨</div>
      <div style={{ width: 200, height: 200, borderRadius: 24, background: 'linear-gradient(135deg, #6bd9ff, #b262f5)', display: 'grid', placeItems: 'center', boxShadow: '0 20px 40px -10px rgba(107,217,255,0.4)' }}>
        <div style={{ fontSize: 60 }}>🕶️</div>
      </div>
      <div style={{ marginTop: 18, fontSize: 13, opacity: 0.7, padding: '0 12px' }}>
        Show this screen at the {brand.name} booth to claim. Valid for 30 minutes.
      </div>
      <div className="s-cta" style={{ margin: 'auto 0 0', width: '100%' }}>Save to wallet</div>
    </div>
  );
}

/* ─────────────────── PROJECTS ─────────────────── */
function ProjectsPage({ brand }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
        <h1 className="page-title">Projects</h1>
        <button className="btn primary"><IconPlus size={14} /> New project</button>
      </div>
      <p className="page-sub">Your campaigns and the events inside them.</p>

      <div className="filter-row">
        <button className="chip active">All · 4</button>
        <button className="chip">Active · 2</button>
        <button className="chip">Upcoming · 1</button>
        <button className="chip">Past · 1</button>
        <button className="chip">Draft · 0</button>
        <div style={{ flex: 1 }} />
        <div className="search"><IconSearch size={14} /><input placeholder="Search projects, events…" /></div>
      </div>

      <div className="grid-3" style={{ marginBottom: 28 }}>
        <ProjectCard name="Joyly Summer 2026" status="live" stations={28} events={12} cover={brand.logoGradient} progress={62} />
        <ProjectCard name="Joyly NYC Launch" status="ready" stations={6} events={3} cover="linear-gradient(135deg, #9b6bff, #6bd9ff)" progress={20} />
        <ProjectCard name="Joyly Holiday 2025" status="complete" stations={18} events={9} cover="linear-gradient(135deg, #ffd66b, #ff6b9d)" progress={100} />
      </div>

      <div className="section-title">Joyly Summer 2026 · structure</div>
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <TreeRows />
      </div>
    </div>
  );
}

function ProjectCard({ name, status, stations, events, cover, progress }) {
  return (
    <div className="card" style={{ cursor: 'pointer', padding: 0, overflow: 'hidden' }}>
      <div style={{ height: 100, background: cover, position: 'relative' }}>
        <div style={{ position: 'absolute', top: 12, right: 12 }}>
          {status === 'live' && <span className="pill live">Live</span>}
          {status === 'ready' && <span className="pill green">Ready</span>}
          {status === 'complete' && <span className="pill">Complete</span>}
        </div>
      </div>
      <div style={{ padding: 16 }}>
        <div style={{ fontFamily: 'Space Grotesk', fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em' }}>{name}</div>
        <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>{events} events · {stations} touchpoints</div>
        <div className="bar" style={{ marginTop: 12 }}><span style={{ width: progress + '%' }} /></div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 6, fontFamily: 'Space Mono' }}>{progress}% deployed</div>
      </div>
    </div>
  );
}

function TreeRows() {
  const [open, setOpen] = React.useState({ wc: true });
  const groups = [
    { id: 'wc', name: 'West Coast Tour', events: [
      { name: 'Coachella W1 — Day 1', status: 'live', stations: ['Main Stage', 'Polo Field', 'Sahara Tent', 'Yuma'] },
      { name: 'Coachella W1 — Day 2', status: 'ready', stations: ['Main Stage', 'Polo Field'] },
      { name: 'BottleRock Napa Valley', status: 'ready', stations: ['Lawn Stage', 'Wine Garden', 'Main Gate'] },
    ]},
    { id: 'mw', name: 'Midwest Loop', events: [
      { name: 'Lollapalooza Chicago', status: 'draft', stations: [] },
    ]},
  ];
  return (
    <div>
      {groups.map(g => (
        <React.Fragment key={g.id}>
          <div className="tree-row" onClick={() => setOpen(o => ({ ...o, [g.id]: !o[g.id] }))}>
            <div className="tree-name">
              <span style={{ transform: open[g.id] ? 'rotate(90deg)' : 'none', transition: '0.15s', display: 'inline-flex' }}><IconChevR size={14} /></span>
              <IconFolder size={16} className="icn" />
              <strong>{g.name}</strong>
              <span style={{ color: 'var(--text-muted)', fontSize: 12 }}>{g.events.length} events</span>
            </div>
            <div />
            <IconChevR size={14} className="icn" />
          </div>
          {open[g.id] && g.events.map((e, i) => (
            <React.Fragment key={i}>
              <div className="tree-row l2">
                <div className="tree-name">
                  <IconCalendar size={14} className="icn" />
                  <span>{e.name}</span>
                  {e.status === 'live' && <span className="pill live">Live</span>}
                  {e.status === 'ready' && <span className="pill green">Ready</span>}
                  {e.status === 'draft' && <span className="pill">Draft</span>}
                </div>
                <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{e.stations.length} touchpoints</span>
                <IconChevR size={14} className="icn" />
              </div>
              {e.stations.map((s, j) => (
                <div key={j} className="tree-row l3">
                  <div className="tree-name">
                    <IconMap size={13} className="icn" />
                    <span style={{ color: 'var(--text-dim)' }}>{s}</span>
                  </div>
                  <span className="pill" style={{ fontSize: 10 }}><IconQr size={10} /> QR ready</span>
                  <IconChevR size={14} className="icn" />
                </div>
              ))}
            </React.Fragment>
          ))}
        </React.Fragment>
      ))}
    </div>
  );
}

/* ─────────────────── MY MERCH ─────────────────── */
function MyMerchPage({ brand }) {
  const [tab, setTab] = React.useState('Manage');
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
        <h1 className="page-title">My Merch</h1>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn"><IconDownload size={14} /> Export</button>
          <button className="btn primary"><IconPlus size={14} /> Add merch</button>
        </div>
      </div>
      <p className="page-sub">Pieces of {brand.name} people take home — planned, in the field, and learning.</p>

      <div className="tabs">
        {['Plan', 'Manage', 'Learn'].map(t => (
          <button key={t} className={"tab" + (t === tab ? ' active' : '')} onClick={() => setTab(t)}>{t}</button>
        ))}
      </div>

      {tab === 'Manage' && <MerchManageTab />}
      {tab === 'Plan' && <MerchPlanTab />}
      {tab === 'Learn' && <MerchLearnTab />}
    </div>
  );
}

function MerchManageTab() {
  return (
    <div>
      <AtlediCard
        msg={<><strong>Holo Sunnies</strong> are at <strong>85% depletion</strong> after just 2 hours. At this pace they'll run out before sundown — shift 40 units from BottleRock allocation?</>}
        actions={['Shift 40 units', 'See depletion curve', 'Dismiss']}
      />
      <div style={{ height: 20 }} />
      <div className="merch-grid">
        {MERCH.map((m, i) => {
          const pct = Math.round((m.available / m.initial) * 100);
          const lvl = pct < 15 ? 'red' : pct < 35 ? 'warn' : 'green';
          return (
            <div key={i} className="merch-card">
              <div className="merch-photo" style={{ background: `linear-gradient(135deg, ${m.color}, ${m.color}aa)` }}>
                <div style={{ fontFamily: 'Space Mono', color: 'rgba(0,0,0,0.4)', fontSize: 12 }}>photo placeholder</div>
                <div className="merch-rarity">
                  {[1,2,3,4,5].map(n => <IconStar key={n} size={10} stroke="none" fill={n <= m.rarity ? '#C8E530' : 'transparent'} />)}
                </div>
                <div style={{ position: 'absolute', top: 10, right: 10 }}>
                  <span className="pill" style={{ fontSize: 9, background: 'rgba(0,0,0,0.6)', color: '#fff', border: 0 }}>{m.purpose}</span>
                </div>
              </div>
              <div className="merch-body">
                <div className="merch-name">{m.name}</div>
                <div className="merch-count mono">{m.available.toLocaleString()} / {m.initial.toLocaleString()} left</div>
                <div className={"bar " + lvl + " merch-bar"}><span style={{ width: pct + '%' }} /></div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function MerchPlanTab() {
  return (
    <div className="grid-2">
      <div className="card">
        <div className="card-header"><h3>Branded merch planner</h3><span className="pill lime">calc.xotski.com</span></div>
        <div className="field"><label>Expected attendees</label><input type="text" defaultValue="12,000" /></div>
        <div className="field"><label>Stations</label><input type="text" defaultValue="4" /></div>
        <div className="field"><label>Engagement rate target</label><input type="text" defaultValue="22%" /></div>
        <div className="field"><label>Avg cost per piece</label><input type="text" defaultValue="$1.85" /></div>
        <button className="btn primary" style={{ width: '100%' }}>Calculate mix →</button>
      </div>
      <div className="card">
        <div className="card-header"><h3>Recommended mix</h3><span className="pill green">Optimized</span></div>
        {[
          { n: 'Buckets Hats (Try)', q: 540, pct: 18 },
          { n: 'Holo Sunnies (Engage)', q: 320, pct: 11 },
          { n: 'Mango Tote (See)', q: 800, pct: 26 },
          { n: 'Sticker Pack (See)', q: 1200, pct: 40 },
          { n: 'Joyly Tee (Try)', q: 480, pct: 16 },
        ].map((r, i) => (
          <div key={i} className="bar-row">
            <div className="lbl">{r.n}</div>
            <div className="bar"><span style={{ width: r.pct * 2.5 + '%' }} /></div>
            <div className="num">{r.q}</div>
          </div>
        ))}
        <div className="divider" />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Space Mono', fontSize: 13 }}>
          <span style={{ color: 'var(--text-dim)' }}>Total cost</span>
          <span><strong style={{ color: 'var(--lime)' }}>$6,178</strong> · 3,340 pieces</span>
        </div>
      </div>
    </div>
  );
}

function MerchLearnTab() {
  return (
    <div>
      <div className="card">
        <div className="card-header"><h3>Planned vs actual depletion</h3><span className="pill warn">2 outliers</span></div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {[
            { n: 'Bucket Hats', planned: 540, actual: 322, color: '#ff6b9d' },
            { n: 'Holo Sunnies', planned: 320, actual: 273, color: '#6bd9ff', hot: true },
            { n: 'Mango Tote', planned: 800, actual: 358, color: '#ffd66b' },
            { n: 'Sticker Pack', planned: 1200, actual: 220, color: '#b262f5', cold: true },
            { n: 'Joyly Tee', planned: 480, actual: 168, color: '#ff6b9d' },
          ].map((r, i) => (
            <div key={i}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 13 }}>
                <span>{r.n}</span>
                <span className="mono" style={{ color: 'var(--text-dim)' }}>
                  {r.actual} / {r.planned}
                  {r.hot && <span style={{ color: 'var(--lime)', marginLeft: 8 }}>🔥 hot</span>}
                  {r.cold && <span style={{ color: 'var(--text-muted)', marginLeft: 8 }}>❄ cold</span>}
                </span>
              </div>
              <div style={{ position: 'relative', height: 18, background: 'var(--ink-3)', borderRadius: 999 }}>
                <div style={{ position: 'absolute', top: 0, left: 0, height: '100%', width: '100%', background: r.color, opacity: 0.2, borderRadius: 999 }} />
                <div style={{ position: 'absolute', top: 0, left: 0, height: '100%', width: (r.actual / r.planned * 100) + '%', background: r.color, borderRadius: 999 }} />
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ─────────────────── INSIGHTS ─────────────────── */
function InsightsPage() {
  const [tab, setTab] = React.useState('Overview');
  return (
    <div>
      <h1 className="page-title">Insights</h1>
      <p className="page-sub">Atledi tells the story. The numbers are the evidence.</p>

      <div className="tabs">
        {['Overview', 'Audience', 'Contacts', 'Cost'].map(t => (
          <button key={t} className={"tab" + (t === tab ? ' active' : '')} onClick={() => setTab(t)}>{t}</button>
        ))}
      </div>

      {tab === 'Overview' && <InsightsOverview />}
      {tab === 'Audience' && <InsightsAudience />}
      {tab === 'Contacts' && <InsightsContacts />}
      {tab === 'Cost' && <InsightsCost />}
    </div>
  );
}

function InsightsOverview() {
  return (
    <div>
      <AtlediCard
        msg={<><strong>312 people experienced Joyly</strong> at Coachella Day 1. Cost per moment came in at <strong>$1.35</strong> — 27% better than the CPG benchmark. Bilingual users completed the survey at 1.4× the English-only rate.</>}
        actions={['What worked best?', 'What should I change?', 'Export for client']}
      />
      <div className="grid-4" style={{ marginTop: 20 }}>
        {KPIS.map((k, i) => <KpiCard key={i} {...k} />)}
      </div>
      <div className="grid-2" style={{ marginTop: 20 }}>
        <div className="card">
          <div className="card-header"><h3>Hourly engagement</h3></div>
          <HourlyChart />
        </div>
        <div className="card">
          <div className="card-header"><h3>Station performance</h3></div>
          {[
            { n: 'Main Stage', plays: 412, pct: 100, top: true },
            { n: 'Polo Field', plays: 287, pct: 70 },
            { n: 'Sahara Tent', plays: 184, pct: 45 },
            { n: 'Yuma', plays: 64, pct: 16, low: true },
          ].map((s, i) => (
            <div key={i} className="bar-row">
              <div className="lbl">{s.n} {s.top && '⭐'} {s.low && '⚠'}</div>
              <div className="bar"><span style={{ width: s.pct + '%', background: s.low ? 'var(--warn)' : 'var(--lime)' }} /></div>
              <div className="num">{s.plays}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function HourlyChart() {
  const data = [12, 28, 45, 62, 84, 110, 94, 71, 58, 42];
  const max = Math.max(...data);
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 160, padding: '8px 0' }}>
      {data.map((v, i) => (
        <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <div style={{ width: '100%', height: (v/max*120) + 'px', background: i === 5 ? 'var(--lime)' : 'var(--ink-4)', borderRadius: 4, position: 'relative' }}>
            {i === 5 && <div style={{ position: 'absolute', top: -20, left: '50%', transform: 'translateX(-50%)', fontSize: 11, fontFamily: 'Space Mono', color: 'var(--lime)' }}>{v}</div>}
          </div>
          <div style={{ fontSize: 10, color: 'var(--text-muted)', fontFamily: 'Space Mono' }}>{12 + i}h</div>
        </div>
      ))}
    </div>
  );
}

function InsightsAudience() {
  return (
    <div>
      <div className="grid-2">
        <div className="card">
          <div className="card-header"><h3>Gender split</h3></div>
          <div className="donut-wrap">
            <Donut data={DEMO_GENDER} />
            <div className="donut-legend">
              {DEMO_GENDER.map((d, i) => (
                <div key={i} className="row">
                  <span className="sw" style={{ background: d.color }} />
                  <span>{d.lbl}</span>
                  <span className="mono" style={{ marginLeft: 'auto', color: 'var(--text-dim)' }}>{d.pct}%</span>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="card">
          <div className="card-header"><h3>Age distribution</h3></div>
          {DEMO_AGE.map((d, i) => (
            <div key={i} className="bar-row">
              <div className="lbl">{d.lbl}</div>
              <div className="bar"><span style={{ width: d.pct * 3 + '%' }} /></div>
              <div className="num">{d.pct}%</div>
            </div>
          ))}
        </div>
      </div>
      <div className="grid-2" style={{ marginTop: 20 }}>
        <div className="card">
          <div className="card-header"><h3>Bilingual split</h3></div>
          <div style={{ display: 'flex', height: 28, borderRadius: 999, overflow: 'hidden', marginBottom: 14 }}>
            <div style={{ flex: 62, background: 'var(--lime)', display: 'grid', placeItems: 'center', fontFamily: 'Space Mono', color: 'var(--ink)', fontWeight: 700, fontSize: 12 }}>EN 62%</div>
            <div style={{ flex: 38, background: '#ff6b9d', display: 'grid', placeItems: 'center', fontFamily: 'Space Mono', color: '#fff', fontWeight: 700, fontSize: 12 }}>ES 38%</div>
          </div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.5 }}>
            Spanish-speakers completed the survey at a <strong style={{ color: 'var(--lime)' }}>1.4× rate</strong> versus English. Consider leading with ES on Latino-majority events.
          </div>
        </div>
        <div className="card">
          <div className="card-header"><h3>Top markets</h3></div>
          {[
            { n: 'Los Angeles', pct: 31 },
            { n: 'San Diego', pct: 18 },
            { n: 'Bay Area', pct: 14 },
            { n: 'Phoenix', pct: 9 },
            { n: 'Vegas', pct: 7 },
          ].map((d, i) => (
            <div key={i} className="bar-row">
              <div className="lbl">{d.n}</div>
              <div className="bar"><span style={{ width: d.pct * 3 + '%' }} /></div>
              <div className="num">{d.pct}%</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function InsightsContacts() {
  return (
    <div>
      <div className="filter-row">
        <div className="search"><IconSearch size={14} /><input placeholder="Search contacts…" /></div>
        <button className="chip active">All · 5,217</button>
        <button className="chip">This event · 412</button>
        <button className="chip">Today · 38</button>
        <div style={{ flex: 1 }} />
        <button className="btn"><IconDownload size={14} /> CSV</button>
        <button className="btn"><IconSparkles size={14} /> Push to CRM</button>
      </div>
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <table className="tbl">
          <thead>
            <tr><th>Name</th><th>Email</th><th>Touchpoint</th><th>Event</th><th>When</th><th></th></tr>
          </thead>
          <tbody>
            {CONTACTS.map((c, i) => (
              <tr key={i}>
                <td><strong>{c.name}</strong></td>
                <td style={{ color: 'var(--text-dim)' }}>{c.email}</td>
                <td>{c.station}</td>
                <td>{c.event}</td>
                <td style={{ color: 'var(--text-muted)', fontFamily: 'Space Mono', fontSize: 12 }}>{c.when}</td>
                <td><button className="btn ghost sm">View</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function InsightsCost() {
  return (
    <div>
      <div className="grid-3">
        <KpiCard lbl="Cost per moment" val="$1.35" delta="−27% vs benchmark" dir="up" spark={[3,2.5,2.1,1.8,1.6,1.4,1.35]} />
        <KpiCard lbl="Cost per contact" val="$2.74" delta="−18% vs benchmark" dir="up" spark={[4,3.5,3.2,3.0,2.9,2.8,2.74]} />
        <KpiCard lbl="Avg time in moment" val="48s" delta="+12s vs last event" dir="up" spark={[30,35,40,42,45,46,48]} />
      </div>
      <div className="grid-2" style={{ marginTop: 20 }}>
        <div className="card">
          <div className="card-header"><h3>Cost per moment · by station</h3></div>
          {[
            { n: 'Main Stage', cost: 0.95 },
            { n: 'Polo Field', cost: 1.22 },
            { n: 'Sahara Tent', cost: 1.41 },
            { n: 'Yuma', cost: 2.84 },
          ].map((s, i) => (
            <div key={i} className="bar-row">
              <div className="lbl">{s.n}</div>
              <div className="bar"><span style={{ width: (1 - s.cost/3) * 100 + '%', background: s.cost > 2 ? 'var(--warn)' : 'var(--lime)' }} /></div>
              <div className="num mono">${s.cost.toFixed(2)}</div>
            </div>
          ))}
        </div>
        <div className="card">
          <div className="card-header"><h3>Benchmark comparison</h3></div>
          <div style={{ fontFamily: 'Space Grotesk', fontSize: 48, fontWeight: 600, color: 'var(--lime)', letterSpacing: '-0.03em' }}>27%</div>
          <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 4 }}>better than CPG industry average ($1.85/moment)</div>
          <div className="divider" />
          <div style={{ fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.6 }}>
            Your <strong style={{ color: 'var(--text)' }}>Main Stage</strong> is your most efficient station at $0.95/moment — replicate that setup at BottleRock to keep momentum.
          </div>
        </div>
      </div>
    </div>
  );
}

/* ─────────────────── REGISTER ─────────────────── */
Object.assign(window, { HomePage, BrandStudio, ProjectsPage, MyMerchPage, InsightsPage });
