// Design System — navigable component library with live demos
const DesignSystem = ({ setRoute }) => {
  const sections = [
    { id: 'foundations', label: 'Foundations' },
    { id: 'motion',      label: 'Motion' },
    { id: 'buttons',     label: 'Buttons' },
    { id: 'forms',       label: 'Forms' },
    { id: 'pickers',     label: 'Pickers' },
    { id: 'overlays',    label: 'Overlays' },
    { id: 'navigation',  label: 'Navigation' },
    { id: 'data',        label: 'Data' },
    { id: 'feedback',    label: 'Feedback' },
    { id: 'media',       label: 'Media' },
  ];
  const [active, setActive] = React.useState('foundations');
  const toast = useToast();

  // Demo states
  const [modalOpen, setModalOpen] = React.useState(false);
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const [confirmOpen, setConfirmOpen] = React.useState(false);
  const [cmdOpen, setCmdOpen] = React.useState(false);
  const [confetti, setConfetti] = React.useState(false);
  const [date, setDate] = React.useState(new Date());
  const [time, setTime] = React.useState('18:30');
  const [seg, setSeg] = React.useState('upcoming');
  const [tab, setTab] = React.useState('overview');
  const [page, setPage] = React.useState(3);
  const [slider, setSlider] = React.useState(60);
  const [color, setColor] = React.useState('#D97757');
  const [toggle, setToggle] = React.useState(true);
  const [combo, setCombo] = React.useState('berlin');
  const [tableSel, setTableSel] = React.useState(null);

  // Observe scroll
  React.useEffect(() => {
    const obs = new IntersectionObserver(
      entries => {
        const visible = entries.filter(e => e.isIntersecting).sort((a,b) => a.boundingClientRect.top - b.boundingClientRect.top)[0];
        if (visible) setActive(visible.target.id);
      },
      { rootMargin: '-80px 0px -60% 0px', threshold: 0.1 }
    );
    sections.forEach(s => {
      const el = document.getElementById(s.id);
      if (el) obs.observe(el);
    });
    return () => obs.disconnect();
  }, []);

  const scroll = id => {
    const el = document.getElementById(id);
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 70;
      window.scrollTo({ top, behavior: 'smooth' });
    }
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '200px 1fr', gap: 0, alignItems: 'flex-start' }}>
      {/* TOC */}
      <aside style={{
        position: 'sticky', top: 20, alignSelf: 'start',
        padding: '28px 20px 28px 36px', display: 'flex', flexDirection: 'column', gap: 2,
      }}>
        <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10 }}>On this page</div>
        {sections.map(s => (
          <button key={s.id} onClick={() => scroll(s.id)}
            style={{
              padding: '6px 10px', border: 0, borderRadius: 6, cursor: 'pointer',
              background: active === s.id ? 'var(--bg-muted)' : 'transparent',
              color: active === s.id ? 'var(--ink)' : 'var(--ink-3)',
              fontFamily: 'inherit', fontSize: 13, fontWeight: active === s.id ? 600 : 500,
              textAlign: 'left',
              borderLeft: `2px solid ${active === s.id ? 'var(--ink)' : 'transparent'}`,
              paddingLeft: 12, transition: 'all 140ms',
            }}>{s.label}</button>
        ))}
      </aside>

      <div style={{ padding: '28px 36px 80px', maxWidth: 1040 }}>
        <FadeSlide>
          <div style={{ marginBottom: 40 }}>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', marginBottom: 8 }}>v1.0 · 42 components</div>
            <h1 className="display" style={{ fontSize: 48, margin: 0, fontWeight: 500, letterSpacing: '-0.03em', lineHeight: 1.05 }}>The Tixwerk design system.</h1>
            <p style={{ fontSize: 16, color: 'var(--ink-2)', maxWidth: 600, marginTop: 12, lineHeight: 1.6 }}>
              A warm, focused library for building organizer tools that feel calm under pressure.
              Components are copy-paste, motion is purposeful, and every decision is tuned for European event workflows.
            </p>
          </div>
        </FadeSlide>

        {/* FOUNDATIONS */}
        <Section id="foundations" title="Foundations" desc="Color, type, space, and radii. The atomic layer.">
          <SubHeading>Accent palette</SubHeading>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 10 }}>
            {[
              { name: 'Saffron', v: 'var(--accent)', h: 'oklch(0.66 0.15 40)' },
              { name: 'Ink',     v: 'var(--ink)',    h: 'oklch(0.22 0.012 60)' },
              { name: 'Indigo',  v: 'var(--indigo)', h: 'oklch(0.52 0.12 265)' },
              { name: 'Success', v: 'var(--success)', h: 'oklch(0.58 0.12 155)' },
              { name: 'Danger',  v: 'var(--danger)', h: 'oklch(0.58 0.18 22)' },
            ].map(s => (
              <div key={s.name} style={{ border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden' }}>
                <div style={{ background: s.v, height: 60 }}/>
                <div style={{ padding: '8px 10px' }}>
                  <div style={{ fontSize: 12, fontWeight: 600 }}>{s.name}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>{s.h}</div>
                </div>
              </div>
            ))}
          </div>

          <SubHeading>Neutral scale</SubHeading>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 6 }}>
            {['--bg','--bg-sunken','--bg-muted','--line','--ink-4','--ink'].map(v => (
              <div key={v}>
                <div style={{ background: `var(${v})`, border: '1px solid var(--line)', height: 48, borderRadius: 8 }}/>
                <div style={{ fontSize: 10.5, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', marginTop: 6 }}>{v}</div>
              </div>
            ))}
          </div>

          <SubHeading>Typography</SubHeading>
          <Card>
            <h1 className="display" style={{ fontSize: 56, margin: 0, fontWeight: 500, letterSpacing: '-0.03em', lineHeight: 1 }}>An evening of ghazals.</h1>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', marginTop: 6 }}>Newsreader · 56/1 · -3%</div>
            <div style={{ height: 20 }}/>
            <h2 className="display" style={{ fontSize: 32, margin: 0, fontWeight: 500, letterSpacing: '-0.02em' }}>Tonight's lineup</h2>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', marginTop: 6 }}>Newsreader · 32 · -2%</div>
            <div style={{ height: 20 }}/>
            <div style={{ fontSize: 16, lineHeight: 1.6, maxWidth: 520 }}>Body text sits at 14–16 with relaxed line-height. We use General Sans for UI — its humanist curves feel grounded but unfussy.</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', marginTop: 6 }}>General Sans · 16/1.6</div>
            <div style={{ height: 20 }}/>
            <div style={{ fontSize: 13, fontFamily: 'var(--font-mono)', color: 'var(--ink-2)' }}>EVT-2856 · 12.450,00 € · 16:32</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', marginTop: 6 }}>JetBrains Mono · 13</div>
          </Card>

          <SubHeading>Radii & shadows</SubHeading>
          <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
            {[
              { r: 6, name: 'sm · 6' }, { r: 10, name: 'md · 10' }, { r: 14, name: 'lg · 14' }, { r: 20, name: 'xl · 20' }, { r: 99, name: 'pill' },
            ].map(s => (
              <div key={s.r} style={{ textAlign: 'center' }}>
                <div style={{ width: 72, height: 72, borderRadius: s.r, background: 'var(--bg-raised)', border: '1px solid var(--line)', boxShadow: 'var(--shadow)' }}/>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6, fontFamily: 'var(--font-mono)' }}>{s.name}</div>
              </div>
            ))}
          </div>
        </Section>

        {/* MOTION */}
        <Section id="motion" title="Motion" desc="Duration, easing, and springs. Exits are faster than entries; everything is interruptible.">
          <Card>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
              {Object.entries(MOTION.dur).map(([k, v]) => (
                <div key={k} style={{ padding: 10, background: 'var(--bg-sunken)', borderRadius: 8 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, fontFamily: 'var(--font-mono)' }}>{k}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{v}ms</div>
                </div>
              ))}
            </div>
          </Card>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14, marginTop: 14 }}>
            <Card>
              <Label>Pressable · spring settle</Label>
              <div style={{ marginTop: 12 }}>
                <Pressable onClick={() => toast?.({ title: 'Pressed', tone: 'success' })}>
                  <div style={{ padding: '20px 24px', background: 'var(--ink)', color: 'var(--bg)', borderRadius: 10, fontWeight: 600 }}>Press me</div>
                </Pressable>
              </div>
            </Card>
            <Card>
              <Label>AnimateNumber</Label>
              <div style={{ fontSize: 40, fontWeight: 600, fontFamily: 'var(--font-display)', marginTop: 8 }}>
                <AnimateNumber value={slider * 124}/> €
              </div>
              <Slider value={slider} onChange={setSlider} format={v => `${v}%`}/>
            </Card>
            <Card>
              <Label>HoverLift</Label>
              <div style={{ marginTop: 12 }}>
                <HoverLift style={{ padding: 18, border: '1px solid var(--line)', borderRadius: 12, background: 'var(--bg-raised)' }}>
                  <div style={{ fontWeight: 600 }}>Hover to lift</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>Gentle translate + shadow reveal</div>
                </HoverLift>
              </div>
            </Card>
            <Card>
              <Label>Stagger entry</Label>
              <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }} key={Math.random()}>
                <Stagger from="left" delay={60}>
                  {['One', 'Two', 'Three', 'Four'].map(s => (
                    <div key={s} style={{ padding: '8px 12px', background: 'var(--bg-muted)', borderRadius: 7, fontSize: 13 }}>{s}</div>
                  ))}
                </Stagger>
              </div>
            </Card>
          </div>
        </Section>

        {/* BUTTONS */}
        <Section id="buttons" title="Buttons" desc="Six variants × three sizes. Loading, icon-only, and grouped forms.">
          <Row>
            <Button variant="primary">Publish event</Button>
            <Button variant="accent">Sell tickets</Button>
            <Button variant="secondary">Save draft</Button>
            <Button variant="ghost">Cancel</Button>
            <Button variant="soft">Duplicate</Button>
            <Button variant="danger">Delete</Button>
          </Row>
          <Row>
            <Button icon="plus">Create</Button>
            <Button icon="download" variant="secondary">Export CSV</Button>
            <Button iconRight="arrow" variant="accent">Continue</Button>
            <Button icon="qr" variant="ghost">Scan</Button>
            <Button variant="secondary" style={{ width: 36, padding: 0 }}><Icon name="more" size={16}/></Button>
          </Row>
          <Row>
            <Button size="sm">Small</Button>
            <Button size="md">Medium</Button>
            <Button size="lg">Large</Button>
            <Button disabled>Disabled</Button>
          </Row>
          <SubHeading>Chips & badges</SubHeading>
          <Row>
            <Chip tone="neutral" icon="draft">Draft</Chip>
            <Chip tone="accent" icon="sparkles">Selling fast</Chip>
            <Chip tone="success" icon="check">Live</Chip>
            <Chip tone="warning" icon="clock">Ends soon</Chip>
            <Chip tone="danger" icon="alert">Sold out</Chip>
            <Chip tone="indigo">Pro</Chip>
            <Chip tone="ink">Featured</Chip>
            <Chip tone="outline">Archived</Chip>
          </Row>
        </Section>

        {/* FORMS */}
        <Section id="forms" title="Forms" desc="Inputs, toggles, segmented controls, validation.">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
            <Field label="Event title" hint="This is what attendees will see on the ticket.">
              <Input placeholder="Sunday Brunch Jazz" defaultValue="Sommernacht 2026"/>
            </Field>
            <Field label="Price" right={<span style={{ fontSize: 11, color: 'var(--ink-3)' }}>EUR</span>}>
              <Input prefix="€" suffix=",00" placeholder="0" defaultValue="45"/>
            </Field>
            <Field label="Capacity" error="Must be greater than 0">
              <Input type="number" defaultValue="0"/>
            </Field>
            <Field label="Category">
              <Select value="music" onChange={()=>{}} options={[
                { value: 'music', label: 'Music · Concert' },
                { value: 'food',  label: 'Food & drink' },
                { value: 'tech',  label: 'Tech · Meetup' },
              ]}/>
            </Field>
          </div>
          <SubHeading>Textarea & rich text</SubHeading>
          <Field label="Description">
            <RichText defaultValue="<p>Join us for an unforgettable night of <b>live music</b> under the stars…</p>"/>
          </Field>
          <SubHeading>Toggle · segmented · slider</SubHeading>
          <Card>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <Toggle checked={toggle} onChange={setToggle} label="Hide from public" desc="Event will be accessible only via direct link"/>
              <SegControl value={seg} onChange={setSeg} options={[
                { value: 'upcoming', label: 'Upcoming', icon: 'calendar' },
                { value: 'past',     label: 'Past' },
                { value: 'draft',    label: 'Drafts' },
              ]}/>
              <Slider value={slider} onChange={setSlider} format={v => `${v}% sold`}/>
            </div>
          </Card>
          <SubHeading>Color</SubHeading>
          <Card><ColorInput value={color} onChange={setColor}/></Card>
        </Section>

        {/* PICKERS */}
        <Section id="pickers" title="Pickers" desc="Date, time, file upload, combobox.">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
            <Field label="Event date"><DatePicker value={date} onChange={setDate}/></Field>
            <Field label="Start time"><TimePicker value={time} onChange={setTime}/></Field>
          </div>
          <SubHeading>Combobox</SubHeading>
          <Field label="Venue city">
            <Combobox value={combo} onChange={setCombo} options={[
              { value: 'berlin',    label: 'Berlin',    icon: 'pin', hint: 'Germany' },
              { value: 'hamburg',   label: 'Hamburg',   icon: 'pin', hint: 'Germany' },
              { value: 'munich',    label: 'München',   icon: 'pin', hint: 'Germany' },
              { value: 'frankfurt', label: 'Frankfurt', icon: 'pin', hint: 'Germany' },
              { value: 'cologne',   label: 'Köln',      icon: 'pin', hint: 'Germany' },
              { value: 'vienna',    label: 'Wien',      icon: 'pin', hint: 'Austria' },
            ]}/>
          </Field>
          <SubHeading>File upload</SubHeading>
          <FileUpload/>
        </Section>

        {/* OVERLAYS */}
        <Section id="overlays" title="Overlays" desc="Modal, drawer, popover, tooltip, toast. Focus-trapped and keyboard-accessible.">
          <Row>
            <Button variant="secondary" icon="eye" onClick={() => setModalOpen(true)}>Modal</Button>
            <Button variant="secondary" icon="sliders" onClick={() => setDrawerOpen(true)}>Drawer</Button>
            <Button variant="secondary" icon="alert" onClick={() => setConfirmOpen(true)}>Confirm dialog</Button>
            <Button variant="secondary" icon="search" onClick={() => setCmdOpen(true)}>Command palette · <Kbd>⌘K</Kbd></Button>
          </Row>
          <Row>
            <Button variant="soft" onClick={() => toast?.({ title: 'Event published', desc: 'Sommernacht 2026 is now live.', tone: 'success', icon: 'check' })}>Success toast</Button>
            <Button variant="soft" onClick={() => toast?.({ title: 'Payout failed', desc: 'Check your bank details.', tone: 'danger', icon: 'alert' })}>Error toast</Button>
            <DropdownMenu
              trigger={<Button variant="soft" iconRight="chevronDown">Dropdown menu</Button>}
              items={[
                { section: 'Event' },
                { label: 'Edit', icon: 'edit', kbd: 'E' },
                { label: 'Duplicate', icon: 'copy', kbd: '⌘D' },
                { label: 'Preview', icon: 'eye' },
                '---',
                { label: 'Delete', icon: 'trash', danger: true, kbd: '⌘⌫' },
              ]}/>
            <Tooltip label="This is a tooltip · ⌘B">
              <Button variant="soft">Hover me</Button>
            </Tooltip>
          </Row>
        </Section>

        {/* NAVIGATION */}
        <Section id="navigation" title="Navigation" desc="Tabs, breadcrumbs, stepper, pagination.">
          <Card>
            <Tabs value={tab} onChange={setTab} options={[
              { value: 'overview', label: 'Overview' },
              { value: 'tickets',  label: 'Tickets', count: 3 },
              { value: 'bookings', label: 'Bookings', count: 1821 },
              { value: 'attendees', label: 'Attendees' },
              { value: 'settings', label: 'Settings' },
            ]}/>
          </Card>
          <SubHeading>Breadcrumb</SubHeading>
          <Card><Breadcrumb items={[
            { label: 'Events', onClick: ()=>{} },
            { label: 'Sommernacht 2026', onClick: ()=>{} },
            { label: 'Tickets' },
          ]}/></Card>
          <SubHeading>Stepper</SubHeading>
          <Card><Stepper steps={['Basics', 'Location', 'Tickets', 'Review', 'Publish']} current={2}/></Card>
          <SubHeading>Pagination</SubHeading>
          <Card style={{ display: 'flex', justifyContent: 'center' }}>
            <Pagination page={page} pages={12} onChange={setPage}/>
          </Card>
        </Section>

        {/* DATA */}
        <Section id="data" title="Data" desc="Table with sorting, selection, bulk actions.">
          <DataTable
            selectable
            columns={[
              { key: 'event', label: 'Event', sortable: true, render: r => (
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <Placeholder hue={r.hue} style={{ width: 44, height: 32, aspectRatio: 'auto', flexShrink: 0 }} rounded={6} label=""/>
                  <div>
                    <div style={{ fontWeight: 550 }}>{r.event}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{r.date}</div>
                  </div>
                </div>
              )},
              { key: 'status', label: 'Status', render: r => <Chip tone={r.statusTone} size="sm">{r.status}</Chip> },
              { key: 'sold', label: 'Sold', sortable: true, align: 'right', render: r => (
                <span style={{ fontFamily: 'var(--font-mono)' }}>{r.sold} / {r.cap}</span>
              )},
              { key: 'revenue', label: 'Revenue', sortable: true, align: 'right', render: r => (
                <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{r.revenue} €</span>
              )},
            ]}
            rows={[
              { id: 1, event: 'Sommernacht 2026',  date: '1. Nov · Berlin',   status: 'Live', statusTone: 'success', sold: 842, cap: 1000, revenue: '38.290', hue: 40 },
              { id: 2, event: 'Apparat · LP5 Live',  date: '24. Mai · Berlin', status: 'Selling fast', statusTone: 'accent', sold: 1420, cap: 1700, revenue: '58.400', hue: 275 },
              { id: 3, event: 'Tempelhof Open Air',  date: '28. Jul · Berlin', status: 'Draft', statusTone: 'neutral', sold: 0, cap: 15000, revenue: '0', hue: 160 },
              { id: 4, event: 'Roosevelt · Tour',   date: '20. Sep · Berlin', status: 'Live', statusTone: 'success', sold: 512, cap: 800, revenue: '29.440', hue: 20 },
            ]}
            onRowClick={r => setTableSel(r)}
          />
        </Section>

        {/* FEEDBACK */}
        <Section id="feedback" title="Feedback" desc="Banners, progress, skeletons, empty states, success.">
          <Banner tone="info" title="VAT filing reminder" desc="Your Q2 filing is due on 31 July." action={<Button size="sm" variant="secondary">File now</Button>}/>
          <div style={{ height: 8 }}/>
          <Banner tone="success" title="Event published" desc="Sommernacht 2026 is now live on Tixwerk."/>
          <div style={{ height: 8 }}/>
          <Banner tone="warning" title="Only 24 tickets left" desc="Consider releasing a waitlist."/>
          <div style={{ height: 8 }}/>
          <Banner tone="danger" title="Payout failed" desc="We couldn't process your settlement. Update your bank details." action={<Button size="sm" variant="secondary">Fix</Button>}/>

          <SubHeading>Progress</SubHeading>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 14 }}>
            <Card>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <Progress value={82} label="VIP · 820 of 1,000 sold" tone="accent" showValue/>
                <Progress value={40} label="Early bird" tone="success" showValue/>
                <Progress value={92} label="General · nearly sold out" tone="warning" showValue/>
              </div>
            </Card>
            <Card style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 20 }}>
              <CircularProgress value={72} size={80} stroke={7}/>
              <div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', fontWeight: 500 }}>Checked in</div>
                <div style={{ fontSize: 22, fontWeight: 600, fontFamily: 'var(--font-display)' }}>612 / 842</div>
              </div>
            </Card>
          </div>

          <SubHeading>Skeleton</SubHeading>
          <Card>
            <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <Skeleton w={48} h={48} r={10}/>
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
                <Skeleton w="60%" h={14}/>
                <Skeleton w="40%" h={10}/>
              </div>
            </div>
          </Card>

          <SubHeading>Empty state</SubHeading>
          <Card pad={0}>
            <EmptyState
              icon="calendar"
              title="No events yet"
              desc="Create your first event in under 2 minutes. Set a date, add tickets, and share the link."
              action={<Button icon="plus" variant="accent" onClick={() => setRoute('create')}>Create event</Button>}
            />
          </Card>

          <SubHeading>Success moment</SubHeading>
          <Card style={{ textAlign: 'center', padding: 32 }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 12 }}>
              <AnimatedCheck size={44}/>
            </div>
            <div className="display" style={{ fontSize: 22, fontWeight: 500 }}>Ticket sent</div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>Confirmation delivered to priya@rhythm-events.de</div>
            <div style={{ marginTop: 14 }}>
              <Button variant="accent" icon="sparkles" onClick={() => { setConfetti(true); setTimeout(() => setConfetti(false), 2200); }}>
                Trigger celebration
              </Button>
            </div>
          </Card>
        </Section>

        {/* MEDIA */}
        <Section id="media" title="Media" desc="Avatars, placeholders, sparklines.">
          <SubHeading>Avatars</SubHeading>
          <Row>
            <Avatar name="Priya Menon" size={48}/>
            <Avatar name="Jonas Richter" size={48}/>
            <Avatar name="Lena Weber" size={48}/>
            <Avatar name="Finn W" size={48}/>
            <div style={{ display: 'flex' }}>
              {['Priya', 'Jonas', 'Lena', 'Finn'].map((n, i) => (
                <Avatar key={n} name={n} size={32} style={{ marginLeft: i === 0 ? 0 : -10, border: '2px solid var(--bg)' }}/>
              ))}
              <div style={{
                width: 32, height: 32, borderRadius: '50%',
                background: 'var(--bg-muted)', border: '2px solid var(--bg)',
                marginLeft: -10, display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 11, fontWeight: 600, color: 'var(--ink-2)',
              }}>+8</div>
            </div>
          </Row>
          <SubHeading>Placeholders</SubHeading>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
            <Placeholder label="hero" hue={40}/>
            <Placeholder label="venue" hue={265}/>
            <Placeholder label="artist" hue={155}/>
          </div>
          <SubHeading>Sparklines</SubHeading>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
            <Card>
              <Label>Revenue · 14d</Label>
              <div style={{ marginTop: 8 }}><Sparkline data={[20, 32, 24, 40, 52, 48, 62, 58, 74, 82, 76, 88, 94, 110]} width={220}/></div>
            </Card>
            <Card>
              <Label>Tickets · 14d</Label>
              <div style={{ marginTop: 8 }}><Sparkline data={[42, 38, 44, 52, 48, 56, 62, 58, 72, 68, 76, 82, 88, 92]} color="var(--indigo)" width={220}/></div>
            </Card>
            <Card>
              <Label>Check-ins · today</Label>
              <div style={{ marginTop: 8 }}><Sparkline data={[0, 5, 12, 28, 62, 120, 180, 240, 310, 380, 420, 480, 510, 520]} color="var(--success)" width={220}/></div>
            </Card>
          </div>
        </Section>
      </div>

      {/* DEMOS */}
      <Modal open={modalOpen} onClose={() => setModalOpen(false)}
        title="Send announcement"
        desc="Reach all confirmed attendees for this event."
        footer={<>
          <Button variant="ghost" onClick={() => setModalOpen(false)}>Cancel</Button>
          <Button variant="accent" icon="send" onClick={() => { setModalOpen(false); toast?.({ title: 'Announcement scheduled', desc: 'Sending to 842 attendees', tone: 'success', icon: 'check' }); }}>Send to 842</Button>
        </>}>
        <Field label="Subject"><Input placeholder="Venue update" defaultValue="Gate opens at 6:30 PM"/></Field>
        <div style={{ height: 10 }}/>
        <Field label="Message"><Textarea rows={5} defaultValue="Hi there,&#10;&#10;A quick update ahead of tonight's show — gates open at 6:30 PM and we recommend arriving early to find parking."/></Field>
        <div style={{ height: 10 }}/>
        <Toggle checked label="Also send SMS" desc="Uses 3 credits per recipient"/>
      </Modal>

      <Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)}
        title="Attendee · Lena Weber"
        desc="Booked 12. Nov · Sommernacht 2026">
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, paddingBottom: 16, borderBottom: '1px solid var(--line)' }}>
          <Avatar name="Lena Weber" size={52}/>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 600 }}>Lena Weber</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>lena.weber@gmail.com · +49 151 2345 6789</div>
          </div>
          <Chip tone="success" icon="check" size="sm">Checked in</Chip>
        </div>
        <div style={{ padding: '16px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <div><Label>Ticket type</Label><div style={{ fontWeight: 600, marginTop: 4 }}>VIP</div></div>
          <div><Label>Amount</Label><div style={{ fontWeight: 600, marginTop: 4, fontFamily: 'var(--font-mono)' }}>45,00 €</div></div>
          <div><Label>Booking ID</Label><div style={{ fontFamily: 'var(--font-mono)', marginTop: 4, fontSize: 13 }}>TX-28475</div></div>
          <div><Label>Payment</Label><div style={{ fontWeight: 600, marginTop: 4 }}>Stripe · SEPA</div></div>
        </div>
        <Banner tone="info" icon="info" title="Attended previous events" desc="This is their 4th event with you. Consider a loyalty discount."/>
        <div style={{ height: 16 }}/>
        <Label>Activity</Label>
        <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            { icon: 'check', t: 'Checked in', s: '7:12 PM · Gate 2' },
            { icon: 'send', t: 'Ticket emailed', s: 'Nov 12 · 3:42 PM' },
            { icon: 'money', t: 'Payment received', s: 'Nov 12 · 3:40 PM' },
          ].map(a => (
            <div key={a.t} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--bg-muted)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name={a.icon} size={13}/>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 550 }}>{a.t}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{a.s}</div>
              </div>
            </div>
          ))}
        </div>
      </Drawer>

      <ConfirmDialog
        open={confirmOpen}
        onClose={() => setConfirmOpen(false)}
        onConfirm={() => toast?.({ title: 'Event deleted', tone: 'neutral', icon: 'trash' })}
        title="Delete this event?"
        desc="This will permanently delete the event and refund all 842 attendees. This action cannot be undone."
        confirmLabel="Delete & refund 842"
        danger
      />

      <CommandPalette open={cmdOpen} onClose={() => setCmdOpen(false)} onNavigate={r => setRoute?.(r)}/>
      <Confetti show={confetti}/>
    </div>
  );
};

const Section = ({ id, title, desc, children }) => (
  <section id={id} style={{ marginBottom: 64, scrollMarginTop: 80 }}>
    <div style={{ marginBottom: 20, paddingBottom: 14, borderBottom: '1px solid var(--line)' }}>
      <h2 className="display" style={{ margin: 0, fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em' }}>{title}</h2>
      {desc && <p style={{ margin: '4px 0 0', fontSize: 14, color: 'var(--ink-3)', maxWidth: 560 }}>{desc}</p>}
    </div>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>{children}</div>
  </section>
);

const SubHeading = ({ children }) => (
  <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginTop: 10 }}>{children}</div>
);

const Label = ({ children }) => (
  <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{children}</div>
);

const Row = ({ children }) => (
  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>{children}</div>
);

window.DesignSystem = DesignSystem;
