// Additional pages — Repositories dashboard, Updates inbox, Templates gallery, Deployments.
const { useState: useStateP, useMemo: useMemoP } = React;
const _userLogin = window.DEVEX_INIT?.user?.login || 'org';

// ---------- Mini sparkline ----------
function Spark({ data, color = 'var(--accent)', w = 90, h = 24 }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / (max - min || 1)) * (h - 2) - 1;
    return [x, y];
  });
  const d = pts.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ');
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{ display: 'block' }}>
      <path d={d} fill="none" stroke={color} strokeWidth="1.4"/>
      <circle cx={pts.at(-1)[0]} cy={pts.at(-1)[1]} r="2" fill={color}/>
    </svg>
  );
}

// ---------- Status pill ----------
function StatusPill({ status }) {
  const map = {
    live:      { bg: 'var(--green-tint)', col: 'var(--green)', label: '● live' },
    deploying: { bg: 'var(--accent-tint)', col: 'var(--accent)', label: '◐ deploying' },
    archived:  { bg: 'var(--surface-2)', col: 'var(--muted)', label: '○ archived' },
    failed:    { bg: 'var(--accent-tint)', col: 'var(--accent)', label: '✕ failed' },
  };
  const m = map[status] || map.archived;
  return <span style={{ background: m.bg, color: m.col, fontFamily: 'var(--mono)', fontSize: 10, padding: '3px 7px', textTransform: 'uppercase', letterSpacing: '0.1em', border: `1px solid ${m.col}` }}>{m.label}</span>;
}

function CIBadge({ ci }) {
  const map = {
    success: { col: 'var(--green)', sym: '✓' },
    running: { col: 'var(--accent)', sym: '◐' },
    failed:  { col: 'var(--accent)', sym: '✕' },
    skipped: { col: 'var(--muted)', sym: '—' },
  };
  const m = map[ci] || map.skipped;
  return <span style={{ color: m.col, fontFamily: 'var(--mono)', fontSize: 12, fontWeight: 600 }}>{m.sym}</span>;
}

// ---------- Repositories Dashboard ----------
function ReposPage() {
  const I = window.I;
  const { REPOS, DEPLOY_SPARK } = window.DEVEX_DATA;
  const [filter, setFilter] = useStateP('all');
  const [query, setQuery] = useStateP('');

  const filtered = useMemoP(() => REPOS.filter(r => {
    if (filter !== 'all' && r.status !== filter) return false;
    if (query && !r.name.includes(query.toLowerCase())) return false;
    return true;
  }), [filter, query]);

  const featured = REPOS.slice(0, 3);

  return (
    <>
      <div className="page-head">
        <h1 className="page-title">Repository<br/><span className="accent">registry.</span></h1>
        <p className="page-sub">// every repo, ownership, deploy state.</p>
      </div>

      {/* Filters */}
      <div className="card">
        <div className="card-head">
          <div className="card-title"><span className="pre">▍</span> All repositories</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div className="input-wrap" style={{ height: 32 }}>
              <span className="input-prefix" style={{ padding: '6px 10px' }}><I.Search size={12}/></span>
              <input className="input" style={{ padding: '6px 10px', fontSize: 12 }} placeholder="filter…" value={query} onChange={e => setQuery(e.target.value)}/>
            </div>
            <div className="seg">
              {['all','live','deploying','archived'].map(f => (
                <button key={f} className={`seg-opt ${filter === f ? 'active' : ''}`} onClick={() => setFilter(f)}>{f}</button>
              ))}
            </div>
          </div>
        </div>
        <div style={{ overflow: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'var(--mono)', fontSize: 12 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--border)', background: 'var(--surface)' }}>
                {['Repo','Template','Owner','Endpoint','CI','Status','Version',''].map(h => (
                  <th key={h} style={{ textAlign: 'left', padding: '10px 14px', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--muted)', fontWeight: 500 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map(r => (
                <tr key={r.id} style={{ borderBottom: '1px solid var(--border)' }}>
                  <td style={{ padding: '12px 14px', fontWeight: 600 }}>
                    <span style={{ color: 'var(--muted)' }}>{_userLogin}/</span>{r.name}
                  </td>
                  <td style={{ padding: '12px 14px', color: 'var(--text-2)' }}>{r.template}</td>
                  <td style={{ padding: '12px 14px', color: 'var(--text-2)' }}>{r.owner}</td>
                  <td style={{ padding: '12px 14px' }}>
                    {r.endpoint !== '—' ? <a href="#" style={{ color: 'var(--accent)', textDecoration: 'none' }}>{r.endpoint}</a> : <span style={{ color: 'var(--muted)' }}>—</span>}
                  </td>
                  <td style={{ padding: '12px 14px' }}><CIBadge ci={r.ci}/></td>
                  <td style={{ padding: '12px 14px' }}><StatusPill status={r.status}/></td>
                  <td style={{ padding: '12px 14px', color: 'var(--text-2)' }}>
                    {r.version}
                    {r.updateAvail && <span style={{ marginLeft: 6, color: 'var(--accent)', fontSize: 10 }}>● update</span>}
                  </td>
                  <td style={{ padding: '12px 14px', textAlign: 'right' }}>
                    <button className="ghost-btn" style={{ padding: '5px 10px', fontSize: 10 }}><I.ExternalLink size={11}/> Open</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

// ---------- Updates Inbox ----------
function UpdatesPage() {
  const I = window.I;
  const { UPDATES } = window.DEVEX_DATA;
  const [active, setActive] = useStateP(UPDATES[0].id);
  const current = UPDATES.find(u => u.id === active);

  const kindColor = { security: 'var(--accent)', breaking: 'var(--accent)', patch: 'var(--green)', feature: 'var(--text)' };

  return (
    <>
      <div className="page-head">
        <h1 className="page-title">Stack<br/><span className="accent">drift.</span></h1>
        <p className="page-sub">// pending update PRs. review, apply, dismiss.</p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 5fr) minmax(0, 7fr)', gap: 24 }}>
        {/* Inbox list */}
        <div className="card">
          <div className="card-head">
            <div className="card-title"><span className="pre">▍</span> Inbox</div>
            <div className="hint">{UPDATES.length} open</div>
          </div>
          {UPDATES.map(u => (
            <div key={u.id} onClick={() => setActive(u.id)} style={{
              padding: '14px 18px',
              borderBottom: '1px solid var(--border)',
              cursor: 'pointer',
              background: active === u.id ? 'var(--accent-tint)' : 'var(--bg)',
              borderLeft: active === u.id ? '3px solid var(--accent)' : '3px solid transparent',
              display: 'flex', flexDirection: 'column', gap: 6,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontFamily: 'var(--mono)', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.12em', color: kindColor[u.kind], border: `1px solid ${kindColor[u.kind]}`, padding: '2px 5px' }}>{u.kind}</span>
                <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>{u.id}</span>
                <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--muted)' }}>{u.opened}</span>
              </div>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 13, fontWeight: 600 }}>{u.title}</div>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>
                {_userLogin}/{u.repo} · {u.from} → <span style={{ color: 'var(--accent)' }}>{u.to}</span>
              </div>
              <div style={{ display: 'flex', gap: 10, fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--muted)' }}>
                <span>{u.files} files</span>
                <span style={{ color: 'var(--green)' }}>+{u.additions}</span>
                <span style={{ color: 'var(--accent)' }}>−{u.deletions}</span>
              </div>
            </div>
          ))}
        </div>

        {/* Diff preview */}
        <div className="card" style={{ alignSelf: 'start', position: 'sticky', top: 80 }}>
          <div className="card-head">
            <div className="card-title">
              <span className="pre">▍</span> {current.id} · {current.title}
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button className="ghost-btn" style={{ padding: '6px 10px', fontSize: 10 }}><I.X size={11}/> Dismiss</button>
              <button className="cta" style={{ width: 'auto' }}>
                <span className="cta-main" style={{ padding: '8px 14px', fontSize: 11 }}>
                  <I.Check size={12}/> Apply PR
                </span>
              </button>
            </div>
          </div>
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'flex', gap: 14, fontFamily: 'var(--mono)', fontSize: 11 }}>
            <div><span style={{ color: 'var(--muted)' }}>repo · </span><span style={{ fontWeight: 600 }}>{_userLogin}/{current.repo}</span></div>
            <div><span style={{ color: 'var(--muted)' }}>from · </span>{current.from}</div>
            <div><span style={{ color: 'var(--muted)' }}>to · </span><span style={{ color: 'var(--accent)', fontWeight: 600 }}>{current.to}</span></div>
            <div style={{ marginLeft: 'auto' }}><span style={{ color: 'var(--muted)' }}>by · </span>devex-bot</div>
          </div>
          {current.diff.map((d, i) => (
            <div key={i} style={{ borderBottom: i < current.diff.length - 1 ? '1px solid var(--border)' : 0 }}>
              <div style={{ padding: '8px 14px', background: 'var(--surface)', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--text-2)', display: 'flex', alignItems: 'center', gap: 6 }}>
                <I.Doc size={11}/> {d.f}
              </div>
              <pre style={{ margin: 0, padding: '14px 18px', background: '#0a0a0a', color: '#e8e8e8', fontFamily: 'var(--mono)', fontSize: 12, lineHeight: 1.55, overflow: 'auto' }}>
{d.d.split('\n').map((line, j) => (
  <div key={j} style={{
    color: line.startsWith('+') ? '#00d97f' : line.startsWith('-') ? '#ff7060' : '#888',
    background: line.startsWith('+') ? 'rgba(0, 217, 127, 0.08)' : line.startsWith('-') ? 'rgba(255, 112, 96, 0.08)' : 'transparent',
    padding: '0 4px',
  }}>{line || '\u00a0'}</div>
))}
              </pre>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

// ---------- Templates Gallery ----------
function TemplatesPage() {
  const I = window.I;
  const { TEMPLATES_EXPANDED } = window.DEVEX_DATA;
  const [cat, setCat] = useStateP('all');
  const cats = ['all', ...new Set(TEMPLATES_EXPANDED.map(t => t.category || 'Stack'))];
  const list = TEMPLATES_EXPANDED.filter(t => cat === 'all' || (t.category || 'Stack') === cat);

  return (
    <>
      <div className="page-head">
        <h1 className="page-title">Template<br/><span className="accent">library.</span></h1>
        <p className="page-sub">// curated, versioned scaffolds.</p>
      </div>

      <div className="seg" style={{ marginBottom: 20 }}>
        {cats.map(c => (
          <button key={c} className={`seg-opt ${cat === c ? 'active' : ''}`} onClick={() => setCat(c)}>{c}</button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 16 }}>
        {list.map(t => (
          <div key={t.id} className="card" style={{ display: 'flex', flexDirection: 'column' }}>
            <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 10, flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <I.Cube size={22}/>
                <div style={{ fontFamily: 'var(--display)', fontSize: 22, textTransform: 'uppercase', letterSpacing: '0.02em' }}>{t.name}</div>
                {t.author === 'devex-core' && <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--accent)', border: '1px solid var(--accent)', padding: '2px 5px', textTransform: 'uppercase', letterSpacing: '0.1em' }}>core</span>}
              </div>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)', lineHeight: 1.5 }}>{t.desc}</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>
                {(t.stack || []).map(s => <span key={s} className="stack-chip">{s}</span>)}
              </div>
            </div>
            <div style={{ borderTop: '1px solid var(--border)', padding: '10px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--muted)' }}>
              <span>{t.usage ? `${t.usage} uses` : 'new'}</span>
              <span>{t.author || 'devex-core'}</span>
              <button className="ghost-btn" style={{ padding: '4px 10px', fontSize: 10 }}>
                <I.Plus size={11}/> Use
              </button>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

// ---------- Deployments (lightweight) ----------
function DeploymentsPage() {
  const I = window.I;
  const { REPOS } = window.DEVEX_DATA;
  const live = REPOS.filter(r => r.status === 'live' || r.status === 'deploying');
  return (
    <>
      <div className="page-head">
        <h1 className="page-title">Deploy<br/><span className="accent">timeline.</span></h1>
        <p className="page-sub">// every workflow run.</p>
      </div>
      <div className="card">
        {live.map((r, i) => (
          <div key={r.id} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '16px 20px', borderBottom: i < live.length - 1 ? '1px solid var(--border)' : 0 }}>
            <div style={{ width: 80, fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--muted)' }}>{r.created}</div>
            <CIBadge ci={r.ci}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 13, fontWeight: 600 }}>{_userLogin}/{r.name}</div>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>{r.template} · {r.endpoint}</div>
            </div>
            <StatusPill status={r.status}/>
            <button className="ghost-btn" style={{ padding: '6px 10px', fontSize: 10 }}>logs <I.Arrow size={11}/></button>
          </div>
        ))}
      </div>
    </>
  );
}

window.ReposPage = ReposPage;
window.UpdatesPage = UpdatesPage;
window.TemplatesPage = TemplatesPage;
window.DeploymentsPage = DeploymentsPage;
