// Live Artifacts — saved visual outputs (charts, agents, dashboards) created from chat.
// Pattern: Glean Agents grid · Featured / Favorites / Created by you, with filter chips on top.

// Self owns everything here — Live Artifacts is your own cowork space (Claude-projects style).
const ME = { name: 'Rian (you)', initial: 'R', color: 'oklch(0.78 0.08 50)' };

const ARTIFACTS = {
  pinned: [
    {
      id: 'cashflow-daily',
      icon: '💰',
      tint: 'oklch(0.96 0.04 145)',
      title: 'Daily Cashflow Pulse',
      desc: 'Live cashflow monitor — refresh tiap 1 jam, kirim alert kalau drop > 15%.',
      creator: ME,
      dept: 'Finance',
      updated: 'Updated 2h ago',
      runs: 'every 1h',
    },
    {
      id: 'vendor-price-tracker',
      icon: '🛒',
      tint: 'oklch(0.96 0.04 50)',
      title: 'Vendor Price Diff Tracker',
      desc: 'Bandingkan harga unit per vendor procurement, flag deviation > 10%.',
      creator: ME,
      dept: 'Procurement',
      updated: 'Updated today',
      runs: 'daily 08:00',
    },
    {
      id: 'velocity-breach',
      icon: '⚠️',
      tint: 'oklch(0.96 0.04 25)',
      title: 'Velocity Threshold Watchdog',
      desc: 'Pantau transaksi > 10k/jam — push ke risk team via WhatsApp.',
      creator: ME,
      dept: 'Risk & Fraud',
      updated: 'Updated 5m ago',
      runs: 'real-time',
    },
    {
      id: 'my-revenue-recap',
      icon: '💰',
      tint: 'oklch(0.96 0.04 145)',
      title: 'Revenue Recap · Last 30 Days',
      desc: 'Recap revenue by product line — drilldown ke top 10 deals.',
      creator: ME,
      dept: 'Finance',
      updated: 'Edited 1d ago',
      runs: 'on-demand',
    },
  ],
  scheduled: [
    {
      id: 'morning-digest-finance',
      icon: '📋',
      tint: 'oklch(0.96 0.04 95)',
      title: 'Morning Digest · Finance',
      desc: 'Ringkasan harian — cashflow, AR/AP, anomali semalam. Push ke WA tiap pagi.',
      creator: ME,
      dept: 'Finance',
      updated: 'Sent 07:30 today',
      runs: 'daily 07:30 · WA',
    },
    {
      id: 'sales-pipeline-weekly',
      icon: '📈',
      tint: 'oklch(0.96 0.04 230)',
      title: 'Sales Pipeline · Weekly Review',
      desc: 'Snapshot pipeline tiap Senin pagi — won/lost/at-risk per segment.',
      creator: ME,
      dept: 'Sales',
      updated: 'Updated 3d ago',
      runs: 'weekly Mon',
    },
    {
      id: 'access-review-q2',
      icon: '🔐',
      tint: 'oklch(0.96 0.04 268)',
      title: 'Q2 Access Review Status',
      desc: 'SOX access review per finance system — auto-nag owner via Slack.',
      creator: ME,
      dept: 'Compliance',
      updated: 'Updated yesterday',
      runs: 'daily 09:00',
    },
    {
      id: 'my-churn-watch',
      icon: '🎯',
      tint: 'oklch(0.96 0.04 25)',
      title: 'Churn Watch — Enterprise Segment',
      desc: 'Predicted churn this quarter — accounts ranked by NPS + usage drop.',
      creator: ME,
      dept: 'Sales',
      updated: 'Updated 6h ago',
      runs: 'weekly Fri',
    },
  ],
};


// ── Rich detail per artifact (for the cowork detail view) ──
const ARTIFACT_DETAIL = {
  'cashflow-daily': {
    metricLabel: 'Net cashflow', unit: 'Rp M', source: 'Postgres · transactions, NetSuite',
    series: [
      { label: 'W1', value: 5.4 }, { label: 'W2', value: 5.1 }, { label: 'W3', value: 5.6 },
      { label: 'W4', value: 4.9 }, { label: 'W5', value: 5.3 }, { label: 'W6', value: 5.0 },
      { label: 'W7', value: 4.95 }, { label: 'W8', value: 4.1 },
    ],
    triggerLine: 4.25, // 15% below prior week (5.0)
    trigger: 'Net cashflow drop ≥ 15% week-over-week',
    schedule: 'Hourly check · alert max 1×/day',
    recipients: [
      { name: 'Ibu Dewi', role: 'CFO', initial: 'D', color: 'oklch(0.6 0.13 268)' },
      { name: 'Pak Andi', role: 'Finance Head', initial: 'A', color: 'oklch(0.62 0.16 50)' },
    ],
    channels: ['Dashboard', 'WhatsApp'],
    lastTriggered: '2 jam lalu',
    current: 4.1, prevValue: 4.95,
    drivers: [
      { label: 'Vendor payment batch Q3', delta: -0.6 },
      { label: 'Refund spike (Senin)', delta: -0.3 },
      { label: 'AR collection on hold', delta: -0.2 },
    ],
    alerts: [
      { when: '2 jam lalu', sev: 'high', text: 'Cashflow turun 17% WoW → Rp 4.1 M (threshold 15%)' },
      { when: '6 hari lalu', sev: 'med', text: 'Cashflow turun 11% WoW — di bawah threshold, info only' },
      { when: '3 minggu lalu', sev: 'high', text: 'Cashflow turun 19% WoW → vendor payment batch Q3' },
    ],
    chatLog: [
      { role: 'ai', text: 'Advisory ini pantau **net cashflow** mingguan dari Postgres + NetSuite. Trigger kalau drop ≥ 15% WoW.' },
      { role: 'user', text: 'Kenapa minggu ini ke-trigger?' },
      { role: 'ai', text: 'W8 turun ke Rp 4.1 M dari Rp 4.95 M (W7) — drop **17%**, lewat threshold 15%. Penyebab utama: 3 vendor payment batch jatuh tempo barengan + refund spike Senin.' },
    ],
  },
};

// Default detail for artifacts that don't have a rich mock yet
const defaultDetail = (a) => ({
  metricLabel: a.title, unit: '', source: 'Connected sources',
  series: [
    { label: 'W1', value: 3.2 }, { label: 'W2', value: 3.6 }, { label: 'W3', value: 3.1 },
    { label: 'W4', value: 3.9 }, { label: 'W5', value: 4.2 }, { label: 'W6', value: 3.8 },
  ],
  triggerLine: null,
  trigger: a.desc,
  schedule: a.runs,
  recipients: [{ name: a.creator.name, role: 'Owner', initial: a.creator.initial, color: a.creator.color }],
  channels: ['Dashboard'],
  lastTriggered: '—',
  current: 3.8, prevValue: 4.2,
  drivers: [],
  alerts: [],
  chatLog: [
    { role: 'ai', text: `Advisory **${a.title}** — ${a.desc}` },
  ],
});

// Colored line icon per dept — light tint of its own color (ChatGPT-agents style).
const ART_ICON = {
  'Finance':      { icon: 'wallet',          fg: 'oklch(0.5 0.13 150)',  bg: 'oklch(0.95 0.045 150)' },
  'Procurement':  { icon: 'shopping-cart',   fg: 'oklch(0.55 0.15 55)',  bg: 'oklch(0.95 0.055 55)' },
  'Risk & Fraud': { icon: 'shield-alert',    fg: 'oklch(0.55 0.18 25)',  bg: 'oklch(0.95 0.05 25)' },
  'Sales':        { icon: 'trending-up',     fg: 'oklch(0.52 0.15 235)', bg: 'oklch(0.95 0.045 235)' },
  'People Ops':   { icon: 'users-round',     fg: 'oklch(0.55 0.15 350)', bg: 'oklch(0.95 0.04 350)' },
  'Compliance':   { icon: 'clipboard-check', fg: 'oklch(0.5 0.12 195)',  bg: 'oklch(0.95 0.04 195)' },
};
const ArtIcon = ({ dept, size = 36 }) => {
  const s = ART_ICON[dept] || { icon: 'bolt', fg: 'var(--ink-3)', bg: 'var(--bg-sunken)' };
  return (
    <div style={{
      width: size, height: size, borderRadius: Math.round(size * 0.26),
      background: s.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
    }}>
      <iconify-icon icon={'lucide:' + s.icon} style={{ fontSize: Math.round(size * 0.5), color: s.fg }} />
    </div>
  );
};

const ArtifactCard = ({ a, onOpen }) => (
  <div className="nx-card" onClick={() => onOpen && onOpen(a)} style={{
    padding: 14, cursor: 'pointer',
    transition: 'transform .14s, border-color .14s',
    display: 'flex', flexDirection: 'column', gap: 10,
    minHeight: 158,
  }}
    onMouseEnter={(e) => {
      e.currentTarget.style.transform = 'translateY(-1px)';
      e.currentTarget.style.borderColor = 'var(--line-strong)';
    }}
    onMouseLeave={(e) => {
      e.currentTarget.style.transform = 'translateY(0)';
      e.currentTarget.style.borderColor = 'var(--line)';
    }}>
    {/* Top row: icon + badges */}
    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
      <ArtIcon dept={a.dept} size={36} />
      {a.dept && (
        <span className="nx-chip" style={{ background: 'var(--bg-sunken)', color: 'var(--ink-3)', borderColor: 'var(--line)', height: 18, fontSize: 10 }}>
          {a.dept}
        </span>
      )}
    </div>

    {/* Title + desc */}
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.3, marginBottom: 4 }}>
        {a.title}
      </div>
      <div style={{
        fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.45,
        display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
        overflow: 'hidden',
      }}>
        {a.desc}
      </div>
    </div>

    {/* Footer: meta */}
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      paddingTop: 8, borderTop: '0.5px solid var(--line)',
    }}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: 'var(--ink-4)', flex: 1 }}>
        <Icon name="clock" size={11} />
        {a.updated}
      </span>
      <span style={{
        display: 'flex', alignItems: 'center', gap: 3,
        fontSize: 10.5, color: 'var(--accent-ink)',
        fontFamily: 'var(--font-mono)',
        padding: '2px 6px', background: 'var(--accent-soft)', borderRadius: 4,
      }}>
        <span className="nx-pulse-dot" style={{ margin: 0 }} />
        {a.runs}
      </span>
    </div>
  </div>
);

const ArtifactSection = ({ title, items, onOpen }) => (
  <div style={{ marginBottom: 26 }}>
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      marginBottom: 10,
    }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-2)' }}>
        {title}
      </div>
      <button className="nx-btn ghost sm" style={{ color: 'var(--ink-3)' }}>
        See all <Icon name="chevron-right" size={11} />
      </button>
    </div>
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
      gap: 12,
    }}>
      {items.map(a => <ArtifactCard key={a.id} a={a} onOpen={onOpen} />)}
    </div>
  </div>
);

// ── Cowork detail view — Claude-style: chat rail (left) + live artifact doc (right) ──
const ArtifactDetail = ({ a, onBack }) => {
  const d = ARTIFACT_DETAIL[a.id] || defaultDetail(a);
  const sevColor = { high: 'var(--err)', med: 'var(--warn)', low: 'var(--ink-4)' };
  const wow = d.prevValue ? ((d.current - d.prevValue) / d.prevValue) * 100 : 0;
  const down = wow < 0;

  // Cowork chat — reuses the main chat's ConversationView component.
  const ConversationView = window.ConversationView;
  const [chatLog, setChatLog] = React.useState(d.chatLog);
  const [input, setInput] = React.useState('');
  const [panelOpen, setPanelOpen] = React.useState(true);
  const inputRef = React.useRef(null);
  const scrollRef = React.useRef(null);
  React.useEffect(() => { setChatLog(d.chatLog); }, [a.id]);
  React.useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [chatLog]);
  const send = (q) => {
    const text = (q ?? input).trim();
    if (!text) return;
    setInput('');
    setChatLog(l => [...l, { role: 'user', text }, { role: 'ai', streaming: true }]);
    setTimeout(() => setChatLog(l => l.map((m, i) => i === l.length - 1
      ? { role: 'ai', text: 'Oke — aku terapkan perubahan itu. Hasilnya langsung kelihatan di panel kanan, dan aku update jadwal + recipient-nya sesuai permintaanmu.' }
      : m)), 1400);
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* Top bar */}
      <div style={{
        flexShrink: 0, height: 52, display: 'flex', alignItems: 'center', gap: 10,
        padding: '0 20px', borderBottom: '0.5px solid var(--line)',
      }}>
        <button onClick={onBack} className="nx-btn sm ghost"><Icon name="arrow-left" size={13} /> Live Artifacts</button>
        <Icon name="chevron-right" size={12} style={{ color: 'var(--ink-5)' }} />
        <ArtIcon dept={a.dept} size={22} />
        <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{a.title}</span>
        <span className="nx-chip ok" style={{ height: 20, fontSize: 10.5 }}><span className="nx-pulse-dot" /> Live</span>
        <div style={{ flex: 1 }} />
        <button className="nx-btn sm ghost" title="Refresh"><Icon name="refresh" size={13} /></button>
        <button className="nx-btn sm"><Icon name="external" size={12} /> Share</button>
      </div>

      {/* Split panes */}
      <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
        {/* LEFT · chat — the real ConversationView component */}
        <div style={{
          flex: 1, minWidth: 0,
          borderRight: panelOpen ? '0.5px solid var(--line)' : 'none',
          display: 'flex', flexDirection: 'column', minHeight: 0,
          background: 'var(--bg)',
          ...(panelOpen ? { maxWidth: 560, flex: '1 1 42%', minWidth: 360 } : {}),
        }}>
          {ConversationView && (
            <ConversationView
              messages={(() => {
                let shown = false;
                return chatLog.map(m => {
                  if (m.role === 'user') return { role: 'user', content: m.text };
                  if (!shown) { shown = true; return { ...m, artifact: { title: a.title, dept: a.dept } }; }
                  return m;
                });
              })()}
              scrollRef={scrollRef}
              input={input} setInput={setInput} send={send}
              inputRef={inputRef}
              incognito={false}
              onOpenArtifact={() => setPanelOpen(true)} />
          )}
        </div>

        {/* RIGHT · live artifact — opens like a Claude artifact panel */}
        {panelOpen && (
        <div style={{ flex: '1 1 58%', overflowY: 'auto', background: 'var(--bg)', minWidth: 0 }}>
          {/* Doc header strip */}
          <div style={{ padding: '18px 28px', borderBottom: '0.5px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
            <div>
              <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em' }}>{a.title}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 2 }}>Updated {d.lastTriggered} · auto every {d.schedule.split('·')[0].replace(/check|Hourly/gi, '').trim() || '1h'}</div>
            </div>
            <button onClick={() => setPanelOpen(false)} title="Close panel" className="nx-btn sm ghost" style={{ width: 28, padding: 0, justifyContent: 'center' }}>
              <Icon name="x" size={14} />
            </button>
          </div>

          {/* Dashboard body */}
          <div style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 18 }}>
            {/* Hero KPI strip */}
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 24, flexWrap: 'wrap' }}>
              <div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginBottom: 4 }}>{d.metricLabel} · this week</div>
                <div style={{ fontSize: 40, fontWeight: 600, color: 'var(--ink)', lineHeight: 1, letterSpacing: '-0.02em' }}>
                  {d.unit === 'Rp M' ? `Rp ${d.current} M` : d.current}
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 5, paddingBottom: 5, color: down ? 'var(--err)' : 'var(--ok)', fontSize: 15, fontWeight: 600 }}>
                <Icon name="arrow-up-right" size={15} style={{ transform: down ? 'rotate(90deg)' : 'none' }} />
                {Math.abs(wow).toFixed(0)}% WoW
              </div>
              {d.triggerLine && (
                <div style={{ paddingBottom: 6, fontSize: 11.5, color: 'var(--ink-4)' }}>
                  threshold <b style={{ color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>Rp {d.triggerLine} M</b>
                </div>
              )}
            </div>

            {/* Chart card */}
            <div className="nx-card" style={{ padding: '20px 22px' }}>
              <Chart series={d.series} triggerLine={d.triggerLine} unit={d.unit} />
            </div>

            {/* 2-col: drivers + recent alerts */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              {/* Drivers */}
              {d.drivers && d.drivers.length > 0 && (
                <div className="nx-card" style={{ padding: 18 }}>
                  <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--ink-4)', marginBottom: 12 }}>What drove this</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    {d.drivers.map((dr, i) => (
                      <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <span style={{ flex: 1, fontSize: 12.5, color: 'var(--ink-2)' }}>{dr.label}</span>
                        <span style={{ fontSize: 12.5, fontWeight: 600, fontFamily: 'var(--font-mono)', color: dr.delta < 0 ? 'var(--err)' : 'var(--ok)' }}>
                          {dr.delta < 0 ? '−' : '+'}Rp {Math.abs(dr.delta)} M
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Recent alerts */}
              {d.alerts.length > 0 && (
                <div className="nx-card" style={{ padding: 18 }}>
                  <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--ink-4)', marginBottom: 12 }}>Recent alerts · {d.alerts.length}</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
                    {d.alerts.map((al, i) => (
                      <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                        <div style={{ width: 7, height: 7, borderRadius: '50%', background: sevColor[al.sev], marginTop: 5, flexShrink: 0 }} />
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.45 }}>{al.text}</div>
                          <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 1 }}>{al.when}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Config strip */}
            <div className="nx-card" style={{ padding: '14px 18px', background: 'var(--bg-sunken)', display: 'flex', flexWrap: 'wrap', gap: '8px 22px', fontSize: 12, color: 'var(--ink-4)' }}>
              <span><b style={{ color: 'var(--ink-3)' }}>Trigger</b> · {d.trigger}</span>
              <span><b style={{ color: 'var(--ink-3)' }}>Source</b> · {d.source}</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                <b style={{ color: 'var(--ink-3)' }}>To</b>
                {d.recipients.map((r, i) => (
                  <span key={i} style={{ width: 16, height: 16, borderRadius: '50%', background: r.color, color: 'white', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 8.5, fontWeight: 600 }}>{r.initial}</span>
                ))}
                via {d.channels.join(', ')}
              </span>
            </div>
          </div>
        </div>
        )}
      </div>
    </div>
  );
};

// Bar chart with gridlines, value labels, threshold line
const Chart = ({ series, triggerLine, unit }) => {
  const max = Math.max(...series.map(s => s.value), triggerLine || 0) * 1.12;
  return (
    <div style={{ position: 'relative', height: 180, display: 'flex', alignItems: 'flex-end', gap: 10, paddingTop: 4 }}>
      {/* gridlines */}
      {[0.25, 0.5, 0.75, 1].map((g, i) => (
        <div key={i} style={{ position: 'absolute', left: 0, right: 0, bottom: `${g * 100 * 0.88}%`, borderTop: '0.5px solid var(--line)', zIndex: 0 }} />
      ))}
      {/* threshold */}
      {triggerLine && (
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: `${(triggerLine / max) * 88}%`, zIndex: 2 }}>
          <div style={{ borderTop: '1.5px dashed var(--err)', opacity: 0.7 }} />
          <span style={{ position: 'absolute', right: 0, top: -8, fontSize: 9.5, color: 'var(--err)', background: 'var(--bg-elev)', padding: '0 4px', fontFamily: 'var(--font-mono)' }}>
            threshold {triggerLine}
          </span>
        </div>
      )}
      {series.map((s, i) => {
        const breach = triggerLine && s.value < triggerLine;
        const last = i === series.length - 1;
        return (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, height: '100%', justifyContent: 'flex-end', zIndex: 1 }}>
            <span style={{ fontSize: 10, fontWeight: 600, color: breach ? 'var(--err)' : (last ? 'var(--ink-2)' : 'var(--ink-4)') }}>{s.value}</span>
            <div style={{
              width: '100%', maxWidth: 38, borderRadius: '4px 4px 0 0',
              height: `${(s.value / max) * 88}%`,
              background: breach ? 'var(--err)' : 'var(--accent)',
              opacity: breach ? 0.9 : (last ? 0.95 : 0.5),
              transition: 'height .3s',
            }} />
            <span style={{ fontSize: 10, color: 'var(--ink-4)' }}>{s.label}</span>
          </div>
        );
      })}
    </div>
  );
};

const ScreenArtifacts = () => {
  const [selected, setSelected] = React.useState(null);
  const [search, setSearch] = React.useState('');

  if (selected) return <ArtifactDetail a={selected} onBack={() => setSelected(null)} />;

  const q = search.trim().toLowerCase();
  const match = (a) => !q || a.title.toLowerCase().includes(q) || (a.desc || '').toLowerCase().includes(q) || (a.dept || '').toLowerCase().includes(q);
  const pinned = ARTIFACTS.pinned.filter(match);
  const scheduled = ARTIFACTS.scheduled.filter(match);
  const total = ARTIFACTS.pinned.length + ARTIFACTS.scheduled.length;

  return (
    <div className="nx-page" style={{
      padding: '24px 32px 40px',
      maxWidth: 1280, margin: '0 auto',
    }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 500, letterSpacing: '-0.01em' }}>
            Live Artifacts
          </h1>
          <span style={{ fontSize: 13.5, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)' }}>
            ({total.toLocaleString()})
          </span>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="nx-btn ghost sm" style={{ color: 'var(--ink-3)' }}>
            <Icon name="info" size={12} /> How artifacts work
          </button>
          <button className="nx-btn accent">
            <Icon name="plus" size={12} /> Create artifact
          </button>
        </div>
      </div>

      {/* Search */}
      <div style={{ position: 'relative', marginBottom: 22 }}>
        <Icon name="search" size={13} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-4)' }} />
        <input value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search artifacts"
          style={{
            width: '100%', height: 36, padding: '0 12px 0 34px',
            border: '0.5px solid var(--line)', borderRadius: 8,
            background: 'var(--bg-elev)', fontSize: 13, fontFamily: 'inherit',
            color: 'var(--ink)', outline: 0,
          }} />
      </div>

      {/* Sections — all yours, grouped by lifecycle */}
      {pinned.length > 0 && <ArtifactSection title="Pinned" items={pinned} onOpen={setSelected} />}
      {scheduled.length > 0 && <ArtifactSection title="Scheduled" items={scheduled} onOpen={setSelected} />}
      {pinned.length === 0 && scheduled.length === 0 && (
        <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-4)', fontSize: 13, background: 'var(--bg-sunken)', borderRadius: 9 }}>
          No artifacts match "{search}"
        </div>
      )}
    </div>
  );
};

window.ScreenArtifacts = ScreenArtifacts;
