// Events list — rich cards with sales state
const EventsList = ({ setRoute }) => {
  const [view, setView] = React.useState('grid');
  const [filter, setFilter] = React.useState('all');

  const events = [
    { name: 'Apparat — LP5 Live', date: 'Sa, 24. Mai · 22:00', city: 'Berghain, Berlin', sold: 1420, total: 1700, revenue: 58400, status: 'live', hue: 20, pill: 'Concert', featured: true,
      ai: { health: 'over', reason: '78% sold in week 1 vs 62% benchmark', boost: { title: 'Raise GA to €45', impact: '+€2,140' } } },
    { name: 'Hot Chip · Astra', date: 'Do, 12. Jun · 20:00', city: 'Astra Kulturhaus, Berlin', sold: 3240, total: 5000, revenue: 128400, status: 'live', hue: 65, pill: 'Concert',
      ai: { health: 'risk', reason: 'Velocity 38% below benchmark · IG ad paused 2d ago', boost: { title: 'WhatsApp lookalike', impact: '+€23,800' } } },
    { name: 'Open Air · Tempelhof', date: 'Mo, 28. Jul · 18:00', city: 'Tempelhof Feld, Berlin', sold: 1410, total: 2600, revenue: 48320, status: 'live', hue: 275, pill: 'Festival',
      ai: { health: 'track', reason: 'On pace for 92% sell-through · matches comparable festivals', boost: { title: 'VIP price tweak', impact: '+€1,320' } } },
    { name: 'Nachtgalerie · Rooftop', date: 'Mo, 02. Jun · 18:00', city: 'Klunkerkranich, Berlin', sold: 0, total: 800, revenue: 0, status: 'draft', hue: 340, pill: 'Party',
      ai: null },
    { name: 'Sommerbrunch · Kreuzberg', date: 'Fr, 15. Aug · 12:00', city: 'Markthalle Neun, Berlin', sold: 186, total: 240, revenue: 9840, status: 'live', hue: 160, pill: 'Food',
      ai: { health: 'over', reason: 'Sold 78% in 5 days · likely sell-out 4 weeks early', boost: { title: 'Add capacity tier', impact: '+€3,800' } } },
    { name: 'Roosevelt — Ghosts Tour', date: 'Fr, 20. Sep · 20:00', city: 'Columbiahalle, Berlin', sold: 2580, total: 2600, revenue: 149200, status: 'almost-sold-out', hue: 40, pill: 'Concert',
      ai: { health: 'over', reason: '99% sold · refund rate up 2.4x — review listing', boost: { title: 'Open waitlist', impact: '+€2,200' } } },
    { name: 'Fred again.. — Europe Tour', date: 'Sa, 11. Okt · 19:00', city: 'Ziggo Dome, Amsterdam', sold: 0, total: 15000, revenue: 0, status: 'scheduled', hue: 220, pill: 'Concert',
      ai: { health: 'track', reason: 'On-sale opens in 3d · 28k waitlist signups predict full demand', boost: { title: 'Pre-sale to waitlist', impact: '+€84k' } } },
    { name: 'Oktoberfest · Afterparty', date: 'Di, 21. Okt · 19:00', city: 'Messe Frankfurt Halle 9', sold: 1120, total: 1800, revenue: 62800, status: 'live', hue: 50, pill: 'Cultural',
      ai: { health: 'risk', reason: 'Soft on Frankfurt · cross-city retarget recommended', boost: { title: 'Retarget Frankfurt buyers', impact: '+€6,400' } } },
  ];

  const healthMap = {
    over: { color: 'var(--success)', bg: 'oklch(0.95 0.05 150)', label: 'Overperforming' },
    track: { color: 'var(--ink-2)', bg: 'var(--bg-muted)', label: 'On track' },
    risk: { color: 'var(--warning)', bg: 'oklch(0.95 0.06 75)', label: 'At risk' },
  };
  const healthPill = (h) => h && (
    <div title={healthMap[h].label + (h === 'risk' ? ' — needs attention' : '')} style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '2px 7px', borderRadius: 99,
      background: healthMap[h].bg,
    }}>
      <span style={{ width: 5, height: 5, borderRadius: 99, background: healthMap[h].color }}/>
      <span style={{ fontSize: 9.5, fontWeight: 700, color: healthMap[h].color, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{healthMap[h].label}</span>
    </div>
  );

  const filtered = events.filter(e => {
    if (filter === 'all') return true;
    if (filter === 'live') return e.status === 'live' || e.status === 'almost-sold-out';
    if (filter === 'draft') return e.status === 'draft';
    if (filter === 'scheduled') return e.status === 'scheduled';
    return true;
  });

  const statusChip = (s) => {
    if (s === 'live') return <Chip tone="success" size="sm"><span style={{ width: 6, height: 6, borderRadius: 99, background: 'oklch(0.58 0.12 155)' }}/>On sale</Chip>;
    if (s === 'almost-sold-out') return <Chip tone="warning" size="sm">Almost sold out</Chip>;
    if (s === 'draft') return <Chip tone="outline" size="sm" icon="draft">Draft</Chip>;
    if (s === 'scheduled') return <Chip tone="indigo" size="sm">Scheduled</Chip>;
    return null;
  };

  const fmt = (n) => n === 0 ? '—' : euro(n, { compact: true });

  return (
    <div style={{ padding: '28px 36px 80px', maxWidth: 1400, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 24 }}>
        <div>
          <h1 className="display" style={{ margin: 0, fontSize: 30, fontWeight: 500, letterSpacing: '-0.02em' }}>Events</h1>
          <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>24 total · 7 on sale · 2 drafts</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button variant="secondary" icon="download" size="md">Export</Button>
          <Button variant="primary" icon="plus" size="md" onClick={() => setRoute('create')}>Create event</Button>
        </div>
      </div>

      {/* AI portfolio health */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap',
        padding: '12px 16px', marginBottom: 18,
        border: '1px solid oklch(0.85 0.06 280)',
        background: 'linear-gradient(135deg, oklch(0.985 0.01 280) 0%, oklch(0.97 0.025 320) 100%)',
        borderRadius: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon name="sparkle" size={13} style={{ color: 'var(--accent)' }}/>
          <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--accent-ink)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Portfolio health</span>
        </div>
        <div style={{ height: 24, width: 1, background: 'oklch(0.85 0.06 280 / 0.6)' }}/>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5 }}>
          <span style={{ width: 7, height: 7, borderRadius: 99, background: 'var(--success)' }}/>
          <span className="mono" style={{ fontWeight: 700 }}>3</span>
          <span style={{ color: 'var(--ink-3)' }}>overperforming</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5 }}>
          <span style={{ width: 7, height: 7, borderRadius: 99, background: 'var(--ink-2)' }}/>
          <span className="mono" style={{ fontWeight: 700 }}>2</span>
          <span style={{ color: 'var(--ink-3)' }}>on track</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5 }}>
          <span style={{ width: 7, height: 7, borderRadius: 99, background: 'var(--warning)' }}/>
          <span className="mono" style={{ fontWeight: 700 }}>2</span>
          <span style={{ color: 'var(--ink-3)' }}>at risk</span>
        </div>
        <div style={{ height: 24, width: 1, background: 'oklch(0.85 0.06 280 / 0.6)' }}/>
        <div style={{ fontSize: 12.5 }}>
          <span style={{ color: 'var(--ink-3)' }}>Total uplift if you act on all: </span>
          <span className="mono" style={{ fontWeight: 700, color: 'var(--success)' }}>+€124k</span>
        </div>
        <div style={{ flex: 1 }}/>
        <Button variant="secondary" size="sm" icon="sparkle" onClick={() => setRoute('intelligence')}>Open AI plan</Button>
      </div>

      {/* Toolbar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18, flexWrap: 'wrap' }}>
        <Tabs value={filter} onChange={setFilter} options={[
          { value: 'all', label: 'All', count: 24 },
          { value: 'live', label: 'On sale', count: 7 },
          { value: 'scheduled', label: 'Scheduled', count: 5 },
          { value: 'draft', label: 'Drafts', count: 2 },
          { value: 'past', label: 'Past', count: 10 },
        ]} style={{ borderBottom: 0, flex: 1 }}/>
        <div style={{ flex: 1 }}/>
        <Input prefix={<Icon name="search" size={14}/>} placeholder="Search events..." style={{ width: 240, height: 34 }}/>
        <Button variant="secondary" icon="filter" size="sm">Filters</Button>
        <SegControl value={view} onChange={setView} options={[
          { value: 'grid', icon: 'grid', label: '' },
          { value: 'list', icon: 'list', label: '' },
        ]}/>
      </div>

      {/* Grid view */}
      {view === 'grid' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 16 }}>
          {filtered.map((e, i) => (
            <Card key={i} pad={0} onClick={() => setRoute('event-detail')} style={{ overflow: 'hidden', cursor: 'pointer' }}>
              <div style={{ position: 'relative' }}>
                <Placeholder label={e.pill + ' cover'} aspect="16/10" hue={e.hue} rounded={0} />
                <div style={{ position: 'absolute', top: 10, left: 10, display: 'flex', gap: 6 }}>
                  {statusChip(e.status)}
                  {e.featured && <Chip tone="ink" size="sm" icon="sparkle">Featured</Chip>}
                </div>
                <button style={{
                  position: 'absolute', top: 10, right: 10,
                  width: 28, height: 28, borderRadius: 99, border: 0,
                  background: 'rgba(255,255,255,0.9)', backdropFilter: 'blur(8px)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  cursor: 'pointer',
                }}><Icon name="more" size={14}/></button>
              </div>
              <div style={{ padding: 16 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                  <span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500, fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.03em' }}>{e.date}</span>
                  <div style={{ flex: 1 }}/>
                  {healthPill(e.ai && e.ai.health)}
                </div>
                <div style={{ fontSize: 14.5, fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1.3, marginBottom: 4, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{e.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 4, marginBottom: 12 }}>
                  <Icon name="pin" size={12}/>{e.city}
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>
                    <span style={{ fontWeight: 600, color: 'var(--ink)' }}>{e.sold.toLocaleString()}</span> / {e.total.toLocaleString()} sold
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-display)' }}>{fmt(e.revenue)}</div>
                </div>
                <div style={{ height: 4, background: 'var(--bg-muted)', borderRadius: 99, overflow: 'hidden' }}>
                  <div style={{ width: `${(e.sold/e.total)*100}%`, height: '100%', background: e.status === 'almost-sold-out' ? 'var(--warning)' : 'var(--accent)' }}/>
                </div>
                {e.ai && e.ai.boost && (
                  <div onClick={ev => ev.stopPropagation()} style={{
                    display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, padding: '8px 10px',
                    borderRadius: 8,
                    border: '1px solid oklch(0.88 0.05 280)',
                    background: 'linear-gradient(135deg, oklch(0.985 0.01 280) 0%, oklch(0.97 0.025 320) 100%)',
                  }}>
                    <Icon name="sparkle" size={11} style={{ color: 'var(--accent)' }}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.ai.boost.title}</div>
                      <div className="mono" style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--success)' }}>{e.ai.boost.impact}</div>
                    </div>
                    <button onClick={() => setRoute('intelligence')} style={{
                      padding: '4px 10px', borderRadius: 6, border: 0,
                      background: 'linear-gradient(135deg, var(--accent), var(--indigo))', color: '#fff',
                      fontFamily: 'inherit', fontSize: 11, fontWeight: 600, cursor: 'pointer',
                    }}>Boost</button>
                  </div>
                )}
                {e.ai && e.ai.reason && (
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)', marginTop: 8, lineHeight: 1.4, display: 'flex', alignItems: 'flex-start', gap: 4 }}>
                    <Icon name="sparkle" size={9} style={{ color: 'var(--accent)', marginTop: 2, flexShrink: 0 }}/>
                    <span>{e.ai.reason}</span>
                  </div>
                )}
              </div>
            </Card>
          ))}
        </div>
      )}

      {/* List view */}
      {view === 'list' && (
        <Card pad={0}>
          <div style={{ display: 'grid', gridTemplateColumns: '48px 1.8fr 1fr 0.9fr 1fr 1fr 1.4fr 40px', gap: 14, padding: '12px 18px', borderBottom: '1px solid var(--line)', fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
            <div></div><div>Event</div><div>Date & venue</div><div>Status</div><div>Sold</div><div style={{ textAlign: 'right' }}>Revenue</div><div>AI health · Boost</div><div></div>
          </div>
          {filtered.map((e, i) => (
            <div key={i} onClick={() => setRoute('event-detail')} style={{
              display: 'grid', gridTemplateColumns: '48px 1.8fr 1fr 0.9fr 1fr 1fr 1.4fr 40px', gap: 14,
              padding: '12px 18px', alignItems: 'center',
              borderBottom: i < filtered.length - 1 ? '1px solid var(--line)' : 'none',
              cursor: 'pointer',
            }}
            onMouseEnter={ev => ev.currentTarget.style.background = 'var(--bg-sunken)'}
            onMouseLeave={ev => ev.currentTarget.style.background = 'transparent'}
            >
              <Placeholder label="" aspect="1/1" hue={e.hue} rounded={6} style={{ width: 48, height: 48 }}/>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.name}</div>
                <Chip tone="neutral" size="sm" style={{ marginTop: 4 }}>{e.pill}</Chip>
              </div>
              <div style={{ fontSize: 12 }}>
                <div>{e.date}</div>
                <div style={{ color: 'var(--ink-3)', fontSize: 11.5, marginTop: 2 }}>{e.city}</div>
              </div>
              <div>{statusChip(e.status)}</div>
              <div>
                <div style={{ fontSize: 12, marginBottom: 4 }}>{e.sold.toLocaleString()} / {e.total.toLocaleString()}</div>
                <div style={{ height: 3, background: 'var(--bg-muted)', borderRadius: 99, overflow: 'hidden' }}>
                  <div style={{ width: `${(e.sold/e.total)*100}%`, height: '100%', background: 'var(--accent)' }}/>
                </div>
              </div>
              <div style={{ fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-display)', textAlign: 'right' }}>{fmt(e.revenue)}</div>
              <div style={{ minWidth: 0 }}>
                {e.ai ? (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    {healthPill(e.ai.health)}
                    {e.ai.boost && (
                      <button onClick={ev => { ev.stopPropagation(); setRoute('intelligence'); }} style={{
                        display: 'flex', alignItems: 'center', gap: 4,
                        padding: '3px 8px', borderRadius: 6, border: 0,
                        background: 'linear-gradient(135deg, var(--accent), var(--indigo))', color: '#fff',
                        fontFamily: 'inherit', fontSize: 10.5, fontWeight: 600, cursor: 'pointer', minWidth: 0,
                      }} title={e.ai.boost.title + ' · ' + e.ai.boost.impact}>
                        <Icon name="sparkle" size={9}/>
                        <span style={{ whiteSpace: 'nowrap' }}>Boost {e.ai.boost.impact}</span>
                      </button>
                    )}
                  </div>
                ) : (
                  <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>—</span>
                )}
              </div>
              <Icon name="more" size={16} style={{ color: 'var(--ink-3)' }}/>
            </div>
          ))}
        </Card>
      )}
    </div>
  );
};

window.EventsList = EventsList;
