// Screen: Components — showcase the design-system primitives so admins
// and designers can see what's available. Lives at #/components.
//
// Layout: sticky-section side rail + dense card grids. Goal is to fit the
// most useful patterns in the smallest vertical space without feeling
// cramped: charts and tables get their own rows, but form controls and
// feedback widgets pack into multi-column grids.

const ComponentsScreen = () => {
  // ----- Demo state -----
  const [s_sel, setS_sel]       = React.useState("helix-7b");
  const [s_check, setS_check]   = React.useState({ a: true, b: false, c: true });
  const [s_radio, setS_radio]   = React.useState("on-demand");
  const [s_slider, setS_slider] = React.useState(40);
  const [s_step, setS_step]     = React.useState(3);
  const [s_text, setS_text]     = React.useState("");
  const [s_tab, setS_tab]       = React.useState("requests");
  const [s_seg, setS_seg]       = React.useState("30d");
  const [s_drawer, setS_drawer] = React.useState(false);
  const [s_modal, setS_modal]   = React.useState(null);
  const [s_sel_table, setS_sel_table] = React.useState(new Set(["k2"]));
  const [s_section, setS_section] = React.useState("charts");

  // Scroll-spy: highlight the section the user is currently looking at.
  React.useEffect(() => {
    const ids = ["charts", "data", "forms", "feedback", "overlays"];
    const onScroll = () => {
      const y = window.scrollY + 120;
      const items = ids
        .map(id => ({ id, el: document.getElementById("cmp-" + id) }))
        .filter(x => x.el)
        .map(x => ({ id: x.id, top: x.el.offsetTop }))
        .sort((a, b) => a.top - b.top);
      let cur = items[0]?.id || "charts";
      for (const it of items) {
        if (it.top <= y) cur = it.id;
      }
      setS_section(cur);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const jumpTo = (id) => {
    const el = document.getElementById("cmp-" + id);
    if (el) window.scrollTo({ top: el.offsetTop - 90, behavior: "smooth" });
  };

  // ----- Demo data -----
  const days = React.useMemo(() => Array.from({length: 30}, (_, i) => {
    const base = 30 + 15 * Math.sin(i / 4) + 10 * Math.cos(i / 9);
    return Math.max(2, base + (i % 7 === 3 ? 18 : 0) + (i / 4));
  }), []);
  const cpu = React.useMemo(() => Array.from({length: 24}, (_, i) =>
    30 + 25 * Math.sin(i / 3) + (i > 18 ? 20 : 0)
  ), []);
  const requests = React.useMemo(() => days.map(d => d * 1200 + 2000), [days]);

  const donutData = [
    { label: "Inference", value: 412, color: "var(--accent)" },
    { label: "Fine-tune", value: 184, color: "#0fb67e" },
    { label: "GPU hours", value: 246, color: "#e8a93b" },
    { label: "Storage",   value:  48, color: "#9aa1ad" },
  ];
  const stackData = [
    { label: "helix-70b",  value: 284, color: "var(--accent)" },
    { label: "helix-7b",   value: 192, color: "#0fb67e" },
    { label: "vision-13b", value: 124, color: "#e8a93b" },
    { label: "embed-v2",   value: 102, color: "#d63a8a" },
    { label: "code-34b",   value:  85, color: "#9aa1ad" },
  ];
  const apiKeysDemo = [
    { id: "k1", name: "prod-server",     project: "prod-inference",    created: "Apr 12", lastUsed: "12 min ago", reqs: 12480, status: "Active" },
    { id: "k2", name: "ci-pipeline",     project: "prod-inference",    created: "Apr 02", lastUsed: "1 hour ago", reqs: 8210,  status: "Active" },
    { id: "k3", name: "local-dev",       project: "research-finetune", created: "Mar 28", lastUsed: "Yesterday",  reqs: 412,   status: "Active" },
    { id: "k4", name: "research-finetune",project:"research-finetune", created: "Mar 04", lastUsed: "Feb 21",     reqs: 80,    status: "Idle" },
    { id: "k5", name: "data-export",     project: "ml-experiments",    created: "Feb 18", lastUsed: "Mar 11",     reqs: 0,     status: "Revoked" },
    { id: "k6", name: "demo-key-temp",   project: "ml-experiments",    created: "Feb 09", lastUsed: "Feb 12",     reqs: 24,    status: "Idle" },
    { id: "k7", name: "marketing-site",  project: "prod-inference",    created: "Jan 22", lastUsed: "Yesterday",  reqs: 6188,  status: "Active" },
  ];

  const sectionNav = [
    { id: "charts",   label: "Charts" },
    { id: "data",     label: "Stats & tables" },
    { id: "forms",    label: "Forms" },
    { id: "feedback", label: "Feedback" },
    { id: "overlays", label: "Overlays" },
  ];

  return (
    <div className="hx-comps">
      <ScreenHeader
        icon={<IconPalette size={20}/>}
        title="Components"
        subtitle="A working showcase of the design-system primitives — charts, tables, forms, modals, and feedback patterns — wired up with real interactions."
        right={<SegmentedControl size="sm" value={s_seg} onChange={setS_seg} options={[{label:"7d",value:"7d"},{label:"30d",value:"30d"},{label:"90d",value:"90d"}]}/>}
      />

      <div className="hx-comps-shell">
        {/* Sticky section rail */}
        <aside className="hx-comps-rail">
          <div className="hx-comps-rail-inner">
            <div className="hx-comps-rail-label">On this page</div>
            {sectionNav.map(s => (
              <button key={s.id} type="button"
                className={`hx-comps-rail-link ${s_section === s.id ? "on" : ""}`}
                onClick={() => jumpTo(s.id)}>
                {s.label}
              </button>
            ))}
          </div>
        </aside>

        <div className="hx-comps-body">

          {/* ====================== CHARTS ====================== */}
          <section id="cmp-charts" className="hx-comps-sec">
            <SecHeader title="Charts" desc="SVG-rendered, theme-aware, with axes, gridlines and hover tooltips. Use inside any Card."/>
            <div className="hx-card-grid hx-2">
              <Card title="Daily spend" subtitle="Line chart with area fill · hover for tooltip">
                <LineChart
                  data={s_seg === "7d" ? days.slice(-7) : days}
                  height={180}
                  formatValue={(v) => "$" + v.toFixed(0)}
                  axisLabels={s_seg === "7d" ? ["7d ago","","Today"] : ["30d ago","15d ago","Today"]}
                />
              </Card>
              <Card title="Requests / hour" subtitle="Bar chart with axis ticks · last 24h">
                <BarChart2
                  data={cpu.map((v, i) => ({ label: `${i.toString().padStart(2,"0")}:00`, value: v * 100 }))}
                  height={180} formatValue={(v) => fmt.compact(v)}
                />
              </Card>
            </div>

            <div className="hx-card-grid hx-2">
              <Card title="Spend by category" subtitle="Donut · with legend">
                <DonutChart
                  size={160} thickness={20}
                  data={donutData}
                  centerValue={"$" + donutData.reduce((s, d) => s + d.value, 0)}
                  centerLabel="this month"
                  formatValue={(v) => "$" + v}
                />
              </Card>
              <Card title="Budget utilization" subtitle="Progress bars · stacked bar">
                <div style={{display:"flex",flexDirection:"column",gap:14}}>
                  <StackedBar data={stackData} height={10} formatValue={(v) => "$" + v}/>
                  <ProgressBar value={84}   max={100}  label="Free-tier inference" tone="accent" format={(v) => v + "%"}/>
                  <ProgressBar value={1200} max={2500} label="GPU hours / month"  tone="warn"   format={(v) => v.toLocaleString() + " hrs"}/>
                  <ProgressBar value={48}   max={50}   label="Concurrent workers" tone="bad"    format={(v) => v + ""}/>
                </div>
              </Card>
            </div>
          </section>

          {/* ====================== STATS & TABLES ====================== */}
          <section id="cmp-data" className="hx-comps-sec">
            <SecHeader title="Stats & tables" desc="StatCard with optional trend sparkline; DataTable with sortable headers, row selection, pagination."/>

            <div className="hx-statgrid">
              <StatCard label="Requests"    value={fmt.compact(412000)} delta="+8.2%"   deltaTone="good"  trend={requests.slice(-14)}/>
              <StatCard label="Latency p95" value="184ms"               delta="−12ms"   deltaTone="good"  trend={cpu.slice(-14).map(v=>120-v/2)}/>
              <StatCard label="GPU usage"   value="68%"                 delta="+4pp"    deltaTone="warn"  trend={cpu.slice(-14)}/>
              <StatCard label="Errors / hr" value="3"                   delta="2 today" deltaTone="bad"   trend={cpu.slice(-14).map((v,i)=>i===10?14:Math.max(0,v/8-2))}/>
            </div>

            <Card padded={false} title="API keys" subtitle="Sortable headers, row selection, pagination · click a row to open"
              action={<div style={{display:"flex",gap:8}}><Btn kind="ghost" size="sm" icon={<IconDownload size={13}/>}>Export</Btn><Btn kind="primary" size="sm" icon={<IconPlus size={13}/>}>New key</Btn></div>}>
              <div style={{padding:"0 18px",borderBottom:"1px solid var(--line-2)"}}>
                <Tabs value={s_tab} onChange={setS_tab} items={[
                  { label: "All",     value: "requests", count: apiKeysDemo.length },
                  { label: "Idle",    value: "idle",     count: apiKeysDemo.filter(k => k.status === "Idle").length },
                  { label: "Revoked", value: "revoked",  count: apiKeysDemo.filter(k => k.status === "Revoked").length },
                ]}/>
              </div>
              {s_sel_table.size > 0 && (
                <div style={{padding:"10px 16px",background:"var(--accent-soft)",borderBottom:"1px solid var(--line-2)",display:"flex",alignItems:"center",gap:12,fontSize:13}}>
                  <strong style={{color:"var(--accent-strong)"}}>{s_sel_table.size} selected</strong>
                  <button className="hx-link-btn" onClick={() => window.__toast(`Revoked ${s_sel_table.size} keys`)}>Revoke</button>
                  <button className="hx-link-btn" onClick={() => window.__toast(`Exported ${s_sel_table.size} keys`)}>Export selected</button>
                  <span style={{flex:1}}/>
                  <button className="hx-link-btn" onClick={() => setS_sel_table(new Set())}>Clear</button>
                </div>
              )}
              <DataTable
                rows={s_tab === "requests" ? apiKeysDemo : apiKeysDemo.filter(k => k.status.toLowerCase() === s_tab)}
                keyField="id"
                selectable
                selected={s_sel_table}
                onSelectChange={setS_sel_table}
                rowsPerPage={4}
                defaultSort={{ key: "reqs", dir: "desc" }}
                onRowClick={(r) => window.__toast(`Open ${r.name}`)}
                columns={[
                  { key: "name", label: "Name", render: (r) => (
                    <span style={{display:"inline-flex",gap:8,alignItems:"center",fontWeight:500,color:"var(--ink)"}}>
                      <IconKey size={13} style={{color:"var(--muted)"}}/>{r.name}
                    </span>
                  )},
                  { key: "project", label: "Project", render: (r) => (
                    <span style={{fontFamily:"var(--mono)",fontSize:12.5,color:"var(--ink-2)"}}>{r.project}</span>
                  )},
                  { key: "created",  label: "Created", w: 110 },
                  { key: "lastUsed", label: "Last used", w: 130 },
                  { key: "reqs",     label: "Requests", w: 110, align: "right", mono: true,
                    render: (r) => fmt.number(r.reqs) },
                  { key: "status",   label: "Status", w: 110, render: (r) => (
                    <StatusDot tone={r.status === "Active" ? "good" : r.status === "Idle" ? "warn" : "neutral"}>{r.status}</StatusDot>
                  )},
                  { key: "_", label: "", w: 50, sortable: false, align: "right",
                    render: () => <button className="hx-icon-btn hx-dt-cell-stop" aria-label="More" onClick={(e) => e.stopPropagation()}><IconMore size={14}/></button> },
                ]}
              />
            </Card>
          </section>

          {/* ====================== FORMS ====================== */}
          <section id="cmp-forms" className="hx-comps-sec">
            <SecHeader title="Forms & controls" desc="Composable form primitives with split label/control layout, hints, and inline errors. All controls keyboard-navigable."/>
            <Card title="Create a deployment" subtitle="Live form combining every primitive">
              <FieldRow label="Deployment name" hint="Lowercase letters, numbers, and hyphens.">
                <FieldGroup cols={2}>
                  <Input placeholder="prod-inference-eu"/>
                  <Select value="us-west" onChange={()=>{}} options={["us-west","us-east","eu-central","ap-south"]}/>
                </FieldGroup>
              </FieldRow>
              <FieldRow label="Base model" hint="Pick a checkpoint to deploy.">
                <Select value={s_sel} onChange={setS_sel}
                  options={[
                    { label: "helix-7b-instruct (general)",   value: "helix-7b" },
                    { label: "helix-70b (largest)",            value: "helix-70b" },
                    { label: "helix-vision-13b (multimodal)",  value: "helix-vision" },
                    { label: "helix-code-34b (code)",          value: "helix-code" },
                    { label: "helix-embed-v2 (embeddings)",    value: "helix-embed" },
                  ]}/>
              </FieldRow>
              <FieldRow label="Compute" hint="Reserved stays warm; on-demand spins up cold per request.">
                <RadioGroup value={s_radio} onChange={setS_radio} layout="horizontal" options={[
                  { label: "On-demand", value: "on-demand", description: "Pay per call" },
                  { label: "Reserved",  value: "reserved",  description: "Cheaper · always on" },
                ]}/>
              </FieldRow>
              <FieldRow label="Capacity">
                <FieldGroup cols={2} gap={20}>
                  <div>
                    <div style={{fontSize:12,color:"var(--muted)",marginBottom:6}}>Concurrent workers</div>
                    <div style={{display:"flex",alignItems:"center",gap:12}}>
                      <NumberStepper value={s_step} onChange={setS_step} min={1} max={32} suffix="workers"/>
                      <span style={{color:"var(--muted)",fontSize:12.5,fontFamily:"var(--mono)"}}>≈ ${(s_step * 0.62).toFixed(2)}/hr</span>
                    </div>
                  </div>
                  <div>
                    <div style={{fontSize:12,color:"var(--muted)",marginBottom:6}}>Request timeout</div>
                    <Slider value={s_slider} onChange={setS_slider} min={5} max={300} step={5} suffix="s" format={(v) => v}/>
                  </div>
                </FieldGroup>
              </FieldRow>
              <FieldRow label="Features">
                <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:10}}>
                  <Checkbox checked={s_check.a} onChange={(v) => setS_check({...s_check, a: v})}
                    label="Response streaming"
                    description="Stream tokens as they're generated."/>
                  <Checkbox checked={s_check.b} onChange={(v) => setS_check({...s_check, b: v})}
                    label="Log request bodies"
                    description="Stored for 30 days."/>
                  <Checkbox checked={s_check.c} onChange={(v) => setS_check({...s_check, c: v})}
                    label="Auto-scale"
                    description="Spin up workers on queue depth."/>
                </div>
              </FieldRow>
              <FieldRow label="Notes" hint="Visible only to org admins.">
                <Textarea value={s_text} onChange={(e) => setS_text(e.target.value)} placeholder="What's this deployment for?" rows={3}/>
              </FieldRow>
              <div style={{display:"flex",justifyContent:"flex-end",gap:8,paddingTop:16}}>
                <Btn kind="ghost">Cancel</Btn>
                <Btn kind="secondary">Save draft</Btn>
                <Btn kind="primary">Create deployment</Btn>
              </div>
            </Card>
          </section>

          {/* ====================== FEEDBACK ====================== */}
          <section id="cmp-feedback" className="hx-comps-sec">
            <SecHeader title="Feedback & status" desc="Pills, banners, status indicators, avatars, loading states."/>
            <div className="hx-card-grid hx-2">
              <Card title="Pills & status" subtitle="Token-driven tones · neutral, accent, good, warn, info">
                <div className="hx-tile-set">
                  <Pill>Neutral</Pill>
                  <Pill tone="accent">Accent</Pill>
                  <Pill tone="good">Active</Pill>
                  <Pill tone="warn">Pending</Pill>
                  <Pill tone="info">Info</Pill>
                </div>
                <div className="hx-divider"/>
                <div className="hx-tile-set">
                  <StatusDot tone="good">Operational</StatusDot>
                  <StatusDot tone="warn">Degraded</StatusDot>
                  <StatusDot tone="bad">Outage</StatusDot>
                  <StatusDot tone="neutral">Idle</StatusDot>
                </div>
                <div className="hx-divider"/>
                <div className="hx-tile-set">
                  <Btn kind="primary"   size="sm">Primary</Btn>
                  <Btn kind="secondary" size="sm">Secondary</Btn>
                  <Btn kind="ghost"     size="sm">Ghost</Btn>
                  <Btn kind="danger"    size="sm">Danger</Btn>
                </div>
              </Card>

              <Card title="Banners" subtitle="Inline messages with optional links">
                <div style={{display:"flex",flexDirection:"column",gap:10}}>
                  <Banner tone="info" icon={<IconInfo size={14}/>}>
                    Maintenance: <strong>Sat 02:00 UTC</strong> · ~20 min downtime expected.
                  </Banner>
                  <Banner tone="warn" icon={<IconInfo size={14}/>}>
                    Card on file expires next month. <a className="hx-link" href="#">Update payment.</a>
                  </Banner>
                </div>
                <div className="hx-divider"/>
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
                  <Btn kind="secondary" size="sm" icon={<IconCheck size={13}/>} onClick={() => window.__toast("Saved successfully")}>Success toast</Btn>
                  <Btn kind="secondary" size="sm" icon={<IconInfo size={13}/>} onClick={() => window.__toast("Quota nearly exhausted", "warn")}>Warning toast</Btn>
                </div>
              </Card>
            </div>

            <div className="hx-card-grid hx-2">
              <Card title="People" subtitle="Avatars and stacked groups">
                <div style={{display:"flex",flexDirection:"column",gap:14}}>
                  <div className="hx-tile-set">
                    <Avatar name="Abhishek Sinha" size={32}/>
                    <Avatar name="Priya Nair" size={32}/>
                    <Avatar name="Karan Mehta" size={32}/>
                    <Avatar name="Lin Wei" size={32}/>
                  </div>
                  <AvatarGroup names={["Abhishek Sinha","Priya Nair","Karan Mehta","Lin Wei","Sasha Volkov","Demo User"]} max={4}/>
                  <KeyValueList items={[
                    { k: "Org",       v: "2bsinha_de6e" },
                    { k: "Owner",     v: "Abhishek Sinha" },
                    { k: "Members",   v: <span><strong>5</strong> · <span style={{color:"var(--muted)"}}>1 pending</span></span> },
                    { k: "Plan",      v: <Pill tone="accent">Team</Pill> },
                  ]}/>
                </div>
              </Card>

              <Card title="Loading states" subtitle="Spinner, skeleton placeholders, empty state">
                <div style={{display:"flex",gap:24,alignItems:"center",justifyContent:"flex-start"}}>
                  <Spinner size={20}/>
                  <Spinner size={28}/>
                  <Spinner size={20} tone="ink"/>
                  <span style={{color:"var(--muted)",fontSize:12.5,fontFamily:"var(--mono)"}}>{"<Spinner />"}</span>
                </div>
                <div className="hx-divider"/>
                <Skeleton lines={3}/>
                <div className="hx-divider"/>
                <Card padded title="Code">
                  <CodeBlock>{`curl https://api.helix.ai/v1/chat/completions \\
  -H "Authorization: Bearer hx-live-..." \\
  -d '{"model":"helix-7b","prompt":"hi"}'`}</CodeBlock>
                </Card>
              </Card>
            </div>

            <Card padded={false}>
              <EmptyState
                icon={<IconUpload size={36}/>}
                title="No files yet"
                description="Upload a JSONL dataset to start a finetune. Files are accessible across all projects in this org."
                action={<Btn kind="primary" icon={<IconUpload size={14}/>}>Upload file</Btn>}
              />
            </Card>
          </section>

          {/* ====================== OVERLAYS ====================== */}
          <section id="cmp-overlays" className="hx-comps-sec">
            <SecHeader title="Modals & overlays" desc="Confirmation, multi-step, destructive, side-drawer · tooltips · command palette"/>
            <Card>
              <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(220px, 1fr))",gap:12}}>
                <OverlayTile icon={<IconShield size={14}/>} title="Confirmation"  desc="Quick yes/no decision"          onClick={() => setS_modal("confirm")}/>
                <OverlayTile icon={<IconList size={14}/>}   title="Multi-step"    desc="Stepper-guided wizard"          onClick={() => setS_modal("multi")}/>
                <OverlayTile icon={<IconTrash size={14}/>}  title="Destructive"   desc="Type-to-confirm danger zone"    onClick={() => setS_modal("danger")}/>
                <OverlayTile icon={<IconChevR size={14}/>}  title="Side drawer"   desc="Slide-over panel"               onClick={() => setS_drawer(true)}/>
                <OverlayTile icon={<IconSearch size={14}/>} title="Command palette" desc="Cmd/Ctrl+K · global search"  onClick={() => window.__openPalette && window.__openPalette()}/>
                <OverlayTile icon={<IconBell size={14}/>}   title="Toast"         desc="Auto-dismissing notification"   onClick={() => window.__toast("Saved successfully")}/>
              </div>
              <div className="hx-divider" style={{marginTop:6,marginBottom:14}}/>
              <div style={{display:"flex",gap:18,alignItems:"center",flexWrap:"wrap"}}>
                <span style={{fontSize:13,color:"var(--muted)"}}>Hover for tooltip:</span>
                <Tooltip content="Top tooltip">      <Btn kind="secondary" size="sm">Top</Btn></Tooltip>
                <Tooltip content="Right tooltip" side="right"><Btn kind="secondary" size="sm">Right</Btn></Tooltip>
                <Tooltip content={<>Shortcut <kbd className="hx-kbd">⌘K</kbd></>}><Btn kind="secondary" size="sm">With kbd</Btn></Tooltip>
              </div>
            </Card>
          </section>

          {/* Modals */}
          <Modal open={s_modal === "confirm"} onClose={() => setS_modal(null)} title="Rotate API key?" width={440}
            footer={<>
              <Btn kind="secondary" onClick={() => setS_modal(null)}>Cancel</Btn>
              <Btn kind="primary" onClick={() => { setS_modal(null); window.__toast("Key rotated"); }}>Rotate now</Btn>
            </>}>
            <p style={{margin:"0 0 14px",fontSize:14,lineHeight:1.55,color:"var(--ink-2)"}}>
              The existing key will stop working in <strong>24 hours</strong>. You'll see the new key once — copy it before closing.
            </p>
            <Banner tone="warn" icon={<IconInfo size={14}/>}>Affects 3 deployments currently using this key.</Banner>
          </Modal>

          <MultiStepModal open={s_modal === "multi"} onClose={() => setS_modal(null)}/>

          <Modal open={s_modal === "danger"} onClose={() => setS_modal(null)} title="Delete deployment" width={460}
            footer={<>
              <Btn kind="secondary" onClick={() => setS_modal(null)}>Cancel</Btn>
            </>}>
            <DangerZone
              title="Delete prod-inference-eu"
              description="All endpoints return 404. In-flight requests fail. Cannot be undone."
              actionLabel="Delete"
              confirmPhrase="prod-inference-eu"
              onConfirm={() => { setS_modal(null); window.__toast("Deployment deleted", "warn"); }}/>
          </Modal>

          <Drawer open={s_drawer} onClose={() => setS_drawer(false)} title="Deployment details"
            footer={<>
              <Btn kind="secondary" onClick={() => setS_drawer(false)}>Close</Btn>
              <Btn kind="primary">Save changes</Btn>
            </>}>
            <FormSection title="Endpoint" description="Public URL receiving inference requests.">
              <Input value="https://api.helix.ai/v1/prod-inference-eu" readOnly suffix={<IconCopy size={14}/>}/>
            </FormSection>
            <div style={{height:14}}/>
            <FormSection title="Live traffic" description="Last 30 minutes.">
              <LineChart data={requests.slice(-30)} height={120} showYAxis={false} formatValue={(v) => fmt.compact(v) + " req/s"}/>
            </FormSection>
            <div style={{height:14}}/>
            <FormSection title="Properties">
              <KeyValueList items={[
                { k: "Region",  v: "us-west-2" },
                { k: "Workers", v: "4 active / 8 max" },
                { k: "Model",   v: "helix-7b-instruct@v3" },
                { k: "Status",  v: <StatusDot tone="good">Operational</StatusDot> },
              ]}/>
            </FormSection>
          </Drawer>
        </div>
      </div>

      <ComponentsScreenStyles/>
    </div>
  );
};

// ----- Section header -----
const SecHeader = ({ title, desc }) => (
  <header className="hx-comps-sec-head">
    <h2>{title}</h2>
    {desc && <p>{desc}</p>}
  </header>
);

// ----- StatusDot (colored dot + label) -----
const StatusDot = ({ tone = "neutral", children }) => {
  const c = {
    good:    "var(--good)",
    warn:    "var(--warn)",
    bad:     "var(--bad)",
    accent:  "var(--accent)",
    neutral: "var(--muted-2)",
  }[tone];
  return (
    <span style={{display:"inline-flex",alignItems:"center",gap:6,fontSize:12.5,color:"var(--ink-2)"}}>
      <span style={{width:7,height:7,borderRadius:"50%",background:c,boxShadow:`0 0 0 3px color-mix(in oklab, ${c} 22%, transparent)`}}/>
      {children}
    </span>
  );
};

// ----- AvatarGroup (stacked overlapping avatars) -----
const AvatarGroup = ({ names = [], max = 5, size = 28 }) => {
  const shown = names.slice(0, max);
  const more  = Math.max(0, names.length - max);
  return (
    <div style={{display:"inline-flex",alignItems:"center"}}>
      {shown.map((n, i) => (
        <span key={i} style={{marginLeft: i === 0 ? 0 : -8, border: "2px solid var(--panel)", borderRadius: "50%"}}>
          <Avatar name={n} size={size}/>
        </span>
      ))}
      {more > 0 && (
        <span style={{
          marginLeft: -8, width: size, height: size,
          borderRadius: "50%", border: "2px solid var(--panel)",
          background: "var(--line-2)", color: "var(--ink-2)",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          fontSize: size * 0.34, fontWeight: 600,
        }}>+{more}</span>
      )}
    </div>
  );
};

// ----- KeyValueList (definition list) -----
const KeyValueList = ({ items }) => (
  <dl style={{margin:0,display:"flex",flexDirection:"column",gap:0}}>
    {items.map((it, i) => (
      <div key={i} style={{display:"grid",gridTemplateColumns:"120px 1fr",gap:14,padding:"8px 0",borderBottom: i === items.length - 1 ? "none" : "1px dashed var(--line-2)",fontSize:13}}>
        <dt style={{color:"var(--muted)"}}>{it.k}</dt>
        <dd style={{margin:0,color:"var(--ink)"}}>{it.v}</dd>
      </div>
    ))}
  </dl>
);

// ----- Spinner -----
const Spinner = ({ size = 20, tone = "accent" }) => {
  const color = tone === "ink" ? "var(--ink)" : "var(--accent)";
  return (
    <span className="hx-spin" style={{width:size,height:size,borderColor:`color-mix(in oklab, ${color} 25%, transparent)`,borderTopColor: color}}>
      <style>{`
        @keyframes hxspin { to { transform: rotate(360deg); } }
        .hx-spin { display: inline-block; border-style: solid; border-width: 2px; border-radius: 50%; animation: hxspin .8s linear infinite; }
      `}</style>
    </span>
  );
};

// ----- Skeleton (loading placeholder) -----
const Skeleton = ({ lines = 1, height, width, style }) => {
  const ws = ["100%", "92%", "84%", "76%"];
  return (
    <div style={{display:"flex",flexDirection:"column",gap:8, ...style}}>
      {Array.from({length: lines}).map((_, i) => (
        <div key={i} className="hx-skel" style={{height: height || 12, width: width || ws[i % ws.length], borderRadius: 4}}/>
      ))}
      <style>{`
        .hx-skel {
          background: linear-gradient(90deg,
            var(--line-2) 0%,
            color-mix(in oklab, var(--line-2) 60%, var(--panel)) 50%,
            var(--line-2) 100%);
          background-size: 200% 100%;
          animation: hxskel 1.4s ease-in-out infinite;
        }
        @keyframes hxskel { from { background-position: 200% 0; } to { background-position: -200% 0; } }
      `}</style>
    </div>
  );
};

// ----- CodeBlock -----
const CodeBlock = ({ children, language }) => (
  <pre className="hx-code">
    {language && <span className="hx-code-lang">{language}</span>}
    <code>{children}</code>
    <style>{`
      .hx-code {
        margin: 0;
        background: var(--panel-2); border: 1px solid var(--line);
        border-radius: 8px; padding: 12px 14px;
        font-family: var(--mono); font-size: 12.5px;
        color: var(--ink); line-height: 1.55;
        overflow-x: auto; white-space: pre;
        position: relative;
      }
      .hx-code-lang {
        position: absolute; top: 6px; right: 10px;
        font-size: 10.5px; color: var(--muted); letter-spacing: .04em; text-transform: uppercase;
      }
    `}</style>
  </pre>
);

// ----- OverlayTile (button-card for the overlay catalogue) -----
const OverlayTile = ({ icon, title, desc, onClick }) => (
  <button type="button" className="hx-otile" onClick={onClick}>
    <span className="hx-otile-icon">{icon}</span>
    <span className="hx-otile-text">
      <span className="hx-otile-title">{title}</span>
      <span className="hx-otile-desc">{desc}</span>
    </span>
    <IconChevR size={12}/>
    <style>{`
      .hx-otile {
        display: flex; align-items: center; gap: 12px;
        padding: 12px 14px; background: var(--panel-2);
        border: 1px solid var(--line); border-radius: 10px;
        cursor: pointer; font: inherit; text-align: left; color: var(--ink);
        transition: border-color .12s, background .12s, transform .04s;
      }
      .hx-otile:hover { border-color: color-mix(in oklab, var(--accent) 60%, var(--line)); background: var(--panel); }
      .hx-otile:active { transform: translateY(.5px); }
      .hx-otile-icon { width: 32px; height: 32px; border-radius: 8px; background: var(--accent-soft); color: var(--accent); display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; }
      .hx-otile-text { display: flex; flex-direction: column; gap: 1px; flex: 1; min-width: 0; }
      .hx-otile-title { font-size: 13.5px; font-weight: 500; color: var(--ink); }
      .hx-otile-desc { font-size: 12px; color: var(--muted); }
    `}</style>
  </button>
);

// ----- MultiStepModal -----
const MultiStepModal = ({ open, onClose }) => {
  const [step, setStep] = React.useState(0);
  const stepsLbl = ["Source", "Model", "Review"];
  const [src, setSrc] = React.useState("dataset");
  const [model, setModel] = React.useState("helix-7b");
  React.useEffect(() => { if (open) setStep(0); }, [open]);
  return (
    <Modal open={open} onClose={onClose} title="Start a finetune" width={540}
      footer={<>
        {step > 0
          ? <Btn kind="ghost" onClick={() => setStep(s => s - 1)} icon={<IconArrowL size={13}/>}>Back</Btn>
          : <Btn kind="ghost" onClick={onClose}>Cancel</Btn>}
        <span style={{flex:1}}/>
        {step < stepsLbl.length - 1
          ? <Btn kind="primary" onClick={() => setStep(s => s + 1)} iconRight={<IconChevR size={13}/>}>Continue</Btn>
          : <Btn kind="primary" onClick={() => { onClose(); window.__toast("Finetune job queued"); }} icon={<IconCheck size={14}/>}>Start job</Btn>}
      </>}>
      <Stepper current={step} steps={stepsLbl}/>
      <div style={{marginTop: 20}}>
        {step === 0 && (
          <RadioGroup value={src} onChange={setSrc} layout="vertical" options={[
            { label: "Existing dataset",     value: "dataset", description: "Re-use a JSONL file you've already uploaded." },
            { label: "Upload new file",      value: "upload",  description: "Drop a JSONL of {prompt, completion} pairs." },
            { label: "From production logs", value: "logs",    description: "Filter the last 30 days of API traffic." },
          ]}/>
        )}
        {step === 1 && (
          <div>
            <FieldRow label="Base model" hint="Start from one of the standard checkpoints.">
              <Select value={model} onChange={setModel} options={[
                { label: "helix-7b-instruct", value: "helix-7b" },
                { label: "helix-13b",          value: "helix-13b" },
                { label: "helix-vision-13b",   value: "helix-vision" },
              ]}/>
            </FieldRow>
            <FieldRow label="Job name"><Input placeholder="ft-2026-05-eu"/></FieldRow>
            <FieldRow label="Epochs"><NumberStepper value={3} onChange={()=>{}} min={1} max={20}/></FieldRow>
          </div>
        )}
        {step === 2 && (
          <KeyValueList items={[
            { k: "Source",         v: src === "dataset" ? "finetune_train_v3.jsonl" : src === "upload" ? "(new upload)" : "Last 30 days API logs" },
            { k: "Base model",     v: model },
            { k: "Estimated time", v: "2h 14m" },
            { k: "Estimated cost", v: "$72.40" },
          ]}/>
        )}
      </div>
    </Modal>
  );
};

const Stepper = ({ current, steps }) => (
  <div className="hx-stp">
    {steps.map((s, i) => {
      const state = i < current ? "done" : i === current ? "on" : "todo";
      return (
        <React.Fragment key={i}>
          <div className={`hx-stp-item hx-stp-${state}`}>
            <span className="hx-stp-circle">{state === "done" ? <IconCheck size={12}/> : i + 1}</span>
            <span className="hx-stp-lbl">{s}</span>
          </div>
          {i < steps.length - 1 && <span className={`hx-stp-line hx-stp-line-${state}`}/>}
        </React.Fragment>
      );
    })}
    <style>{`
      .hx-stp { display: flex; align-items: center; gap: 10px; }
      .hx-stp-item { display: inline-flex; align-items: center; gap: 8px; }
      .hx-stp-circle {
        width: 24px; height: 24px; border-radius: 50%;
        display: inline-flex; align-items: center; justify-content: center;
        font-size: 12px; font-weight: 600;
        border: 1.5px solid var(--line); background: var(--panel); color: var(--muted);
      }
      .hx-stp-on .hx-stp-circle,
      .hx-stp-done .hx-stp-circle { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
      .hx-stp-lbl { font-size: 13px; color: var(--muted); font-weight: 500; }
      .hx-stp-on .hx-stp-lbl, .hx-stp-done .hx-stp-lbl { color: var(--ink); }
      .hx-stp-line { flex: 1; height: 1.5px; background: var(--line); border-radius: 1px; }
      .hx-stp-line-done { background: var(--accent); }
    `}</style>
  </div>
);

// ===== Layout / typography =====
const ComponentsScreenStyles = () => (
  <style>{`
    .hx-comps { display: flex; flex-direction: column; gap: 20px; }

    .hx-comps-shell { display: grid; grid-template-columns: 180px minmax(0, 1fr); gap: 32px; align-items: start; }
    .hx-comps-rail { position: sticky; top: 76px; align-self: start; }
    .hx-comps-rail-inner {
      display: flex; flex-direction: column; gap: 2px;
      padding: 8px;
      border-left: 1px solid var(--line-2);
    }
    .hx-comps-rail-label {
      font-size: 11px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase;
      color: var(--muted); padding: 4px 12px 8px;
    }
    .hx-comps-rail-link {
      text-align: left; background: transparent; border: none; cursor: pointer;
      font: inherit; font-size: 13px; color: var(--muted);
      padding: 7px 12px; border-radius: 6px;
      transition: color .12s, background .12s;
    }
    .hx-comps-rail-link:hover { color: var(--ink); background: var(--hover); }
    .hx-comps-rail-link.on { color: var(--accent); background: var(--accent-soft); font-weight: 500; }

    .hx-comps-body { display: flex; flex-direction: column; gap: 36px; min-width: 0; }
    .hx-comps-sec { display: flex; flex-direction: column; gap: 14px; scroll-margin-top: 100px; }
    .hx-comps-sec-head h2 { margin: 0; font-size: 18px; font-weight: 600; letter-spacing: -.01em; color: var(--ink); }
    .hx-comps-sec-head p  { margin: 4px 0 0; font-size: 13.5px; color: var(--muted); line-height: 1.55; max-width: 720px; }

    /* Dense stat grid */
    .hx-statgrid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }

    /* Set of inline tiles (pills, buttons, dots) */
    .hx-tile-set { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
    .hx-divider { height: 1px; background: var(--line-2); margin: 14px -2px; }

    @media (max-width: 1023px) {
      .hx-comps-shell { grid-template-columns: 1fr; gap: 18px; }
      .hx-comps-rail { position: static; }
      .hx-comps-rail-inner { flex-direction: row; flex-wrap: wrap; border-left: none; border-bottom: 1px solid var(--line-2); padding: 0 0 10px; gap: 4px; }
      .hx-comps-rail-label { width: 100%; padding: 0 0 4px; }
      .hx-statgrid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
    }
    @media (max-width: 640px) {
      .hx-statgrid { grid-template-columns: 1fr; }
    }
  `}</style>
);

Object.assign(window, { ComponentsScreen, MultiStepModal, Stepper, StatusDot, AvatarGroup, KeyValueList, Spinner, Skeleton, CodeBlock });
