function StatCard({ label, value, sub, tone }) {
  const str = String(value);
  const fontSize = str.length > 12 ? 'var(--text-lg)' : str.length > 9 ? 'var(--text-xl)' : str.length > 6 ? 'var(--text-2xl)' : 'var(--text-3xl)';
  return (
    <div style={{ flex: 1, minWidth: 180, background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: '18px 20px', overflow: 'hidden' }}>
      <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', letterSpacing: 'var(--tracking-wide)', textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontFamily: 'var(--font-display)', fontSize, fontWeight: 700, marginTop: 8, color: tone || 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</div>
      {sub && <div style={{ fontSize: 'var(--text-sm)', color: 'var(--text-muted)', marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

function SubEventCard({ s, onOpen }) {
  const catColor = window.catColorMap[s.category] || 'var(--brand-primary)';
  const pct = s.capacity ? Math.round((s.booked / s.capacity) * 100) : 0;
  return (
    <div onClick={onOpen} style={{ flex: '1 1 220px', minWidth: 220, background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', overflow: 'hidden', cursor: 'pointer', transition: 'box-shadow 150ms ease, transform 150ms ease' }}
      onMouseEnter={(e) => { e.currentTarget.style.boxShadow = 'var(--shadow-md)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
      onMouseLeave={(e) => { e.currentTarget.style.boxShadow = 'var(--shadow-sm)'; e.currentTarget.style.transform = 'none'; }}>
      <div style={{ position: 'relative', height: 110, backgroundColor: catColor, backgroundImage: s.photo ? 'linear-gradient(180deg, color-mix(in srgb, ' + catColor + ' 15%, transparent) 40%, color-mix(in srgb, ' + catColor + ' 78%, black) 100%), url(' + s.photo + ')' : 'repeating-linear-gradient(135deg, color-mix(in srgb, ' + catColor + ' 45%, transparent) 0px, color-mix(in srgb, ' + catColor + ' 45%, transparent) 10px, transparent 10px, transparent 20px)', backgroundSize: 'cover', backgroundPosition: 'center' }}>
        <span style={{ position: 'absolute', top: 10, left: 12, fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', color: 'white', textShadow: '0 1px 3px rgba(0,0,0,0.5)' }}>{s.num}</span>
        <span style={{ position: 'absolute', bottom: 10, left: 12, right: 12, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-base)', color: 'white', lineHeight: 1.2 }}>{s.title}</span>
      </div>
      <div style={{ padding: '12px 16px 16px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 'var(--text-sm)', color: 'var(--text-secondary)' }}>
          <span>{s.date}</span><span>{s.booked}/{s.capacity} booked</span>
        </div>
        <div style={{ height: 4, background: 'var(--gray-100)', borderRadius: 'var(--radius-pill)', marginTop: 10, overflow: 'hidden' }}>
          <div style={{ height: '100%', width: pct + '%', background: catColor }} />
        </div>
      </div>
    </div>
  );
}

function BarChart({ data, valueFmt }) {
  if (!data.length) return <div style={{ fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>No revenue yet.</div>;
  const max = Math.max.apply(null, data.map((d) => d.value));
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {data.map((d) => (
        <div key={d.label}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 'var(--text-sm)', marginBottom: 6 }}>
            <span>{d.label}</span><span style={{ fontWeight: 600 }}>{valueFmt(d.value)}</span>
          </div>
          <div style={{ height: 8, background: 'var(--gray-100)', borderRadius: 'var(--radius-pill)', overflow: 'hidden' }}>
            <div style={{ height: '100%', width: (d.value / max * 100) + '%', background: 'var(--brand-primary)', borderRadius: 'var(--radius-pill)' }} />
          </div>
        </div>
      ))}
    </div>
  );
}

function OverviewScreen({ onOpenEvent, onGotoEvents }) {
  const { Badge, Button } = window.TheUpperDeckDesignSystem_4d3294;
  const [orders, setOrders] = React.useState(null);
  const [mainEvents, setMainEvents] = React.useState(null);

  React.useEffect(() => {
    Promise.all([window.fetchOrdersLive(), window.fetchMainEventsLive()]).then(([o, m]) => { setOrders(o); setMainEvents(m); });
  }, []);

  if (!orders || !mainEvents) return <div style={{ padding: 32, color: 'var(--text-muted)' }}>Loading…</div>;

  const paidOrders = orders.filter((o) => o.status === 'paid');
  const totalRevenue = paidOrders.reduce((s, o) => s + o.amount, 0);
  const activeEvents = mainEvents.filter((m) => m.status === 'published').length;
  const checkedInRate = paidOrders.length ? Math.round(paidOrders.filter((o) => o.checkedIn).length / paidOrders.length * 100) : 0;

  const revenueByMain = {};
  paidOrders.forEach((o) => { revenueByMain[o.mainTitle] = (revenueByMain[o.mainTitle] || 0) + o.amount; });
  const topEvents = Object.keys(revenueByMain).map((k) => ({ label: k, value: revenueByMain[k] })).sort((a, b) => b.value - a.value).slice(0, 5);

  const withSubs = mainEvents.filter((m) => m.subEvents.length > 0);
  const latest = withSubs[withSubs.length - 1] || mainEvents[mainEvents.length - 1];
  const today = new Date().toISOString().slice(0, 10);
  const upcoming = mainEvents.flatMap((m) => m.subEvents.map((s) => ({ ...s, mainId: m.id }))).filter((s) => s.dateIso >= today).sort((a, b) => a.dateIso.localeCompare(b.dateIso)).slice(0, 6);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,2fr) minmax(0,1fr)', gap: 24 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 24, minWidth: 0 }}>
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
          <StatCard label="Total revenue" value={window.fmtUSD(totalRevenue)} sub={paidOrders.length + ' paid orders'} tone="var(--brand-primary)" />
          <StatCard label="Total bookings" value={orders.length} sub={paidOrders.length + ' paid'} />
          <StatCard label="Active events" value={activeEvents} sub={mainEvents.length + ' total'} />
          <StatCard label="Check-in rate" value={checkedInRate + '%'} sub="of paid orders" />
        </div>

        {latest && (
          <div style={{ position: 'relative', borderRadius: 'var(--radius-lg)', overflow: 'hidden', background: 'var(--gradient-navy)', color: 'white', padding: '32px 36px', boxShadow: 'var(--shadow-md)' }}>
            <Badge tone="brand">Latest main event</Badge>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-3xl)', margin: '14px 0 6px', maxWidth: 460 }}>{latest.title}</h2>
            <div style={{ color: 'var(--text-on-dark-muted)', marginBottom: 20 }}>{latest.dateRange || 'No sub-events scheduled'} · {latest.venue}</div>
            <Button variant="primary" onClick={() => onOpenEvent(latest.id)}>View event</Button>
          </div>
        )}

        {latest && latest.subEvents.length > 0 && (
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-lg)', marginBottom: 12 }}>Sub-events under {latest.title}</div>
            <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
              {latest.subEvents.map((s) => <SubEventCard key={s.id} s={{ ...s, booked: orders.filter((o) => o.eventId === s.id && o.status === 'paid').length }} onOpen={() => onOpenEvent(latest.id)} />)}
            </div>
          </div>
        )}

        <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 20 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-lg)' }}>Recent orders</div>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 'var(--text-sm)' }}>
            <thead><tr style={{ textAlign: 'left', color: 'var(--text-muted)', fontSize: 'var(--text-xs)', textTransform: 'uppercase' }}>
              <th style={{ padding: '6px 8px' }}>Ref</th><th style={{ padding: '6px 8px' }}>Buyer</th><th style={{ padding: '6px 8px' }}>Event</th><th style={{ padding: '6px 8px' }}>Amount</th><th style={{ padding: '6px 8px' }}>Status</th>
            </tr></thead>
            <tbody>
              {orders.slice(0, 6).map((o) => (
                <tr key={o.ref} className="ud-row">
                  <td style={{ padding: '10px 8px', fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)' }}>{o.ref.slice(0, 8)}</td>
                  <td style={{ padding: '10px 8px' }}>{o.buyer}</td>
                  <td style={{ padding: '10px 8px', color: 'var(--text-secondary)' }}>{o.eventTitle}</td>
                  <td style={{ padding: '10px 8px' }}>{window.fmtUSD(o.amount)}</td>
                  <td style={{ padding: '10px 8px' }}><Badge tone={o.status === 'paid' ? 'success' : o.status === 'refunded' ? 'error' : 'warning'}>{o.status}</Badge></td>
                </tr>
              ))}
              {orders.length === 0 && <tr><td colSpan={5} style={{ padding: '10px 8px', color: 'var(--text-muted)' }}>No orders yet.</td></tr>}
            </tbody>
          </table>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 20 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-lg)', marginBottom: 16 }}>Top events by revenue</div>
          <BarChart data={topEvents} valueFmt={window.fmtUSD} />
        </div>
        <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 20 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-lg)', marginBottom: 14 }}>Upcoming sessions</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {upcoming.map((u) => (
              <div key={u.id} onClick={() => onOpenEvent(u.mainId)} style={{ display: 'flex', alignItems: 'center', gap: 10, paddingBottom: 10, borderBottom: '1px solid var(--border-default)', cursor: 'pointer' }}>
                <div style={{ width: 8, height: 8, borderRadius: '50%', background: window.catColorMap[u.category] || 'var(--brand-primary)', flex: '0 0 auto' }} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 'var(--text-sm)', fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{u.title}</div>
                  <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>{u.date}</div>
                </div>
              </div>
            ))}
            {upcoming.length === 0 && <div style={{ fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>No upcoming sessions.</div>}
          </div>
        </div>
        <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 20 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-lg)', marginBottom: 14 }}>All main events</div>
          {mainEvents.length === 0 ? (
            <div style={{ borderRadius: 'var(--radius-md)', border: '1px dashed var(--border-strong)', padding: '32px 20px', textAlign: 'center' }}>
              <div style={{ color: 'var(--text-muted)', fontSize: 'var(--text-sm)', marginBottom: 14 }}>No events yet.</div>
              <Button variant="secondary" onClick={onGotoEvents}>Want to create event?</Button>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {mainEvents.map((m) => (
                <div key={m.id} onClick={() => onOpenEvent(m.id)} style={{ display: 'flex', justifyContent: 'space-between', gap: 8, fontSize: 'var(--text-sm)', cursor: 'pointer' }}>
                  <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.title}</span>
                  <Badge tone={m.status === 'published' ? 'success' : 'warning'}>{m.status}</Badge>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.OverviewScreen = OverviewScreen;
