/* Desk UI Kit — interactive workspace shell (recreation of the real app). */
const { useState, useEffect, useRef } = React;
const D = window.DESK_DATA;
const DS = window.DeskDesignSystem_d7d84e || {};
const { Telemetry, Badge } = DS;

/* Lucide icon helper — renders <i data-lucide> and lets a global pass swap it. */
function Ico({ name, size = 16, color }) {
  return <i data-lucide={name} style={{ width: size, height: size, color }} />;
}
function useLucide(dep) {
  useEffect(() => { try { window.lucide && window.lucide.createIcons(); } catch (e) {} });
}

function renderTerm(segs) {
  const lines = []; let cur = [];
  segs.forEach((s, i) => {
    if (s[0] === 'br') { lines.push(cur); cur = []; return; }
    if (s[0] === 'caret') { cur.push(<span key={i} className="caret" />); return; }
    cur.push(<span key={i} className={s[0]}>{s[1]}</span>);
  });
  lines.push(cur);
  return lines.map((l, i) => <div key={i} className="ln">{l}</div>);
}

/* ---------- Topbar ---------- */
function Topbar({ onKill }) {
  return (
    <div className="workspaceTopbar">
      <div className="topbarPrimary">
        <div className="brand">
          <strong>DESK</strong>
          <span>~/projects/desk · main</span>
        </div>
        <div />
        <div className="toolbar">
          <button className="thinButton"><Ico name="refresh-cw" size={13} /> <span>Refresh</span></button>
          <button className="thinButton"><Ico name="chevron-up" size={13} /> <span>Up</span></button>
          <button className="thinButton danger" onClick={onKill}><Ico name="power" size={13} /> <span>Kill</span></button>
          <button className="thinButton"><Ico name="bell" size={13} /></button>
          <button className="thinButton"><Ico name="settings" size={13} /></button>
        </div>
      </div>
      <div className="topbarTelemetry">
        {[
          ['HOST', 'lin-deck', 'up 4d 02h', ''],
          ['CPU', '42%', '8 cores', ''],
          ['RAM', '11.4G', 'of 32G', 'warn'],
          ['GPU', '61%', 'RTX 4090', 'ok'],
          ['NET', '2.1MB/s', '↓ down', ''],
        ].map(([l, v, s, tone]) => Telemetry
          ? <Telemetry key={l} label={l} value={v} sub={s} tone={tone || undefined} />
          : <div key={l} className={`dsk-telemetry ${tone ? 'dsk-telemetry--' + tone : ''}`}>
              <span className="dsk-telemetry__label">{l}</span>
              <strong className="dsk-telemetry__value">{v}</strong>
              <small className="dsk-telemetry__sub">{s}</small>
            </div>
        )}
      </div>
    </div>
  );
}

/* ---------- App rail ---------- */
const SUBSYSTEMS = [
  { id: 'terminals', icon: 'terminal' },
  { id: 'channels', icon: 'messages-square' },
  { id: 'editor', icon: 'folder-tree' },
  { id: 'git', icon: 'git-branch', compact: true },
  { id: 'projects', icon: 'kanban' },
  { id: 'notes', icon: 'notebook-pen' },
];
function AppRail({ view, setView }) {
  return (
    <div className="appRail">
      {SUBSYSTEMS.map((s) => (
        <button key={s.id} className={`subsystemButton ${view === s.id ? 'selected' : ''} ${s.compact ? 'compact' : ''}`}
          title={s.id} onClick={() => setView(s.id)}>
          <span className="bar" />
          <Ico name={s.icon} size={19} />
        </button>
      ))}
    </div>
  );
}

/* ---------- Sidebar tree ---------- */
function Sidebar({ selected, setSelected }) {
  return (
    <div className="agentsSidebar">
      <div className="sidebarHeader">
        <span className="railTitle"><Ico name="server" size={13} /> Sessions</span>
        <button className="thinButton"><Ico name="plus" size={12} /></button>
      </div>
      <div className="projectTree">
        {D.projects.map((p) => (
          <div className="projectNode" key={p.id}>
            <div className="projectRow"><div className="treeMain"><Ico name="chevron-down" size={13} /><span>{p.name}</span></div></div>
            <div className="groupBranch">
              {p.groups.map((g) => (
                <div key={g.id}>
                  <div className="treeMain"><Ico name="chevron-down" size={13} /><span>{g.name}</span><small>{g.sessions.length}</small></div>
                  <div className="sessionBranch">
                    {g.sessions.map((s) => (
                      <div key={s.id} className={`sessionRow ${selected === s.id ? 'selected' : ''}`} onClick={() => setSelected(s.id)}>
                        <span className={`statusDot2 ${s.status}`} />
                        <span>{s.name}</span>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Terminals (multiplexer) ---------- */
function TerminalsView({ focus, setFocus }) {
  const cells = D.projects[0].groups[0].sessions;
  return (
    <div className="subsystemSurface">
      <div className="subsystemHeader"><Ico name="terminal" size={13} /> web · multiplexer <span className="layoutBadge">2 × 2</span></div>
      <div className="multiplexerGrid g4">
        {cells.map((s) => (
          <div key={s.id} className={`cellChrome ${focus === s.id ? 'focused' : ''}`} onClick={() => setFocus(s.id)}>
            <div className="cellBorder" />
            <div className="cellBody">
              <div className="cellTabs">
                <span className={`statusDot2 ${s.status}`} />
                <span className="cellTab selected">{s.agent} · {s.name}</span>
              </div>
              <div className="term">{renderTerm(D.terminals[s.id] || [['d','idle'],['caret']])}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Editor ---------- */
function FileTree({ nodes, depth = 0 }) {
  return nodes.map((n, i) => (
    <div key={i}>
      <div className={`fileNode ${n.active ? 'active' : ''}`}>
        <span className={`fi ${n.dir ? 'dir' : ''}`}><Ico name={n.dir ? (n.open ? 'folder-open' : 'folder') : 'file'} size={13} /></span>
        <span>{n.name}</span>
      </div>
      {n.dir && n.children && n.open !== false ? <div className="fileBranch"><FileTree nodes={n.children} depth={depth + 1} /></div> : null}
    </div>
  ));
}
const CODE = [
  ['cm', '/* desk shell tokens */'],
  ['', ''],
  ['kw', ':root', ' {'],
  ['', '  --desk-bg: ', 'st', 'hsl(188, 45%, 4%)', '', ';'],
  ['', '  --desk-accent: ', 'st', 'hsl(48, 90%, 62%)', '', ';'],
  ['', '  --desk-line-strong: ', 'st', 'hsl(180, 95%, 58%)', '', ';'],
  ['', '}'],
  ['', ''],
  ['kw', '.deskCmd', ' {'],
  ['', '  clip-path: ', 'fn', 'octagon', '', '(6px);'],
  ['', '  box-shadow: inset 0 0 0 1px ', 'nm2', 'var(--desk-line)', '', ';'],
  ['', '}'],
];
function EditorView() {
  return (
    <div className="subsystemPanels">
      <div className="agentsSidebar">
        <div className="sidebarHeader"><span className="railTitle"><Ico name="folder-tree" size={13} /> Explorer</span><button className="thinButton"><Ico name="search" size={12} /></button></div>
        <div className="projectTree"><FileTree nodes={D.files} /></div>
      </div>
      <div className="subsystemSurface" style={{ gridTemplateRows: 'minmax(0,1fr)' }}>
        <div className="editorWrap">
          <div className="editorTabs">
            <div className="editorTab"><Ico name="file-code" size={12} /> theme.ts</div>
            <div className="editorTab active"><span className="tb" /><Ico name="file-code" size={12} /> styles.css <span className="dot" /></div>
            <div className="editorTab"><Ico name="file-text" size={12} /> README.md</div>
          </div>
          <div className="codePane">
            {CODE.map((parts, i) => (
              <div className="codeLine" key={i}>
                <span className="gut">{i + 1}</span>
                <span>{parts.length <= 2 ? <span className={parts[0]}>{parts[1] || '\u00a0'}</span> :
                  parts.reduce((acc, _, j) => j % 2 === 0 ? [...acc, <span key={j} className={parts[j]}>{parts[j + 1]}</span>] : acc, [])}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Git ---------- */
function GitView() {
  const { staged, unstaged } = D.changes;
  return (
    <div className="subsystemPanels">
      <div className="agentsSidebar">
        <div className="sidebarHeader"><span className="railTitle"><Ico name="git-branch" size={13} /> main</span>{Badge ? <Badge tone="warn" square>↑2 ↓0</Badge> : null}</div>
        <div className="projectTree" style={{ padding: 0 }}>
          <div className="commitBox"><textarea defaultValue="" placeholder="Commit message  (⌘↵)"></textarea></div>
          <div className="gitGroupHeader">Staged · {staged.length}</div>
          {staged.map((c, i) => <div className="gitChangeRow" key={i}><span className={`gitBadge ${c.b}`}>{c.b.toUpperCase()}</span><span>{c.n} <span className="gitDir">{c.dir}</span></span><Ico name="minus" size={12} /></div>)}
          <div className="gitGroupHeader">Changes · {unstaged.length}</div>
          {unstaged.map((c, i) => <div className="gitChangeRow" key={i}><span className={`gitBadge ${c.b}`}>{c.b.toUpperCase()}</span><span>{c.n} <span className="gitDir">{c.dir}</span></span><Ico name="plus" size={12} /></div>)}
        </div>
      </div>
      <div className="subsystemSurface">
        <div className="subsystemHeader"><Ico name="git-commit-horizontal" size={13} /> History</div>
        <div className="projectTree">
          {D.commits.map((c, i) => (
            <div className="commitRow" key={i}>
              <span className="graphNode" />
              <span style={{ color: 'var(--text-dim)', fontSize: 10 }}>{c.h}</span>
              <span>{c.s} {c.head ? <span className="refChip head">HEAD</span> : null}</span>
              <span style={{ color: 'var(--text-dim)', fontSize: 10 }}>{c.who} · {c.t}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Placeholder({ icon, label }) {
  return <div className="subsystemSurface"><div className="subsystemHeader"><Ico name={icon} size={13} /> {label}</div>
    <div className="emptyCell" style={{ background: 'transparent' }}>{label} subsystem</div></div>;
}

/* ---------- Projects (GitHub Projects v2 — kanban) ---------- */
function ProjectsView() {
  const b = D.board;
  const total = b.columns.reduce((n, c) => n + c.cards.length, 0);
  const [dragId, setDragId] = useState(null);
  return (
    <div className="subsystemSurface">
      <div className="subsystemHeader"><Ico name="kanban" size={13} /> {b.name}
        <span className="layoutBadge">{total} items</span></div>
      <div className="kanban">
        {b.columns.map((col) => (
          <div className="kanColumn" key={col.id}>
            <div className="kanColHead"><span className={`kanDot ${col.id}`} /> {col.name} <small>{col.cards.length}</small></div>
            <div className="kanCards">
              {col.cards.map((c) => (
                <div key={c.id}
                  className={`kanCard ${c.tone ? 'tone-' + c.tone : ''} ${dragId === c.id ? 'lift' : ''}`}
                  onMouseDown={() => setDragId(c.id)} onMouseUp={() => setDragId(null)} onMouseLeave={() => setDragId(null)}>
                  <div className="kanCardTop"><span className="kanId">{c.id}</span><span className="kanEst">{c.est}pt</span></div>
                  <div className="kanCardTitle">{c.t}</div>
                  <div className="kanCardFoot">
                    {c.tags.map((t) => <span className="kanTag" key={t}>{t}</span>)}
                    <span className="kanAva">{c.who}</span>
                  </div>
                </div>
              ))}
              <div className="kanAdd"><Ico name="plus" size={12} /> add card</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Notes (sidebar + markdown) ---------- */
function renderNote(body) {
  return body.map((blk, i) => {
    const [k, t] = blk;
    if (k === 'h') return <h1 key={i} className="ndH1">{t}</h1>;
    if (k === 'h2') return <h2 key={i} className="ndH2">{t}</h2>;
    if (k === 'li') return <div key={i} className="ndLi"><span className="ndBul">▸</span><span>{t}</span></div>;
    if (k === 'code') return <pre key={i} className="ndCode">{t}</pre>;
    return <p key={i} className="ndP">{t}</p>;
  });
}
function NotesView() {
  const [active, setActive] = useState(D.notes.find((n) => n.active)?.id || D.notes[0].id);
  const note = D.notes.find((n) => n.id === active) || D.notes[0];
  return (
    <div className="subsystemPanels">
      <div className="agentsSidebar">
        <div className="sidebarHeader"><span className="railTitle"><Ico name="notebook-pen" size={13} /> Notes</span>
          <button className="thinButton"><Ico name="plus" size={12} /></button></div>
        <div className="projectTree">
          {D.notes.map((n) => (
            <div key={n.id} className={`noteRow ${active === n.id ? 'selected' : ''}`} onClick={() => setActive(n.id)}>
              <Ico name="file-text" size={13} />
              <div className="noteRowMeta"><span className="noteTitle">{n.title}</span><small>{n.tag} · {n.edited}</small></div>
            </div>
          ))}
        </div>
      </div>
      <div className="subsystemSurface">
        <div className="subsystemHeader"><Ico name="notebook-pen" size={13} /> {note.title}
          <span className="layoutBadge"><Ico name="check" size={10} /> autosaved</span></div>
        <div className="noteDoc">{renderNote(note.body)}<span className="caret" /></div>
      </div>
    </div>
  );
}

/* ---------- Status bar ---------- */
function StatusBar({ view, selected }) {
  const sess = D.projects.flatMap(p => p.groups.flatMap(g => g.sessions)).find(s => s.id === selected);
  return (
    <div className="statusBar">
      <div style={{ display: 'flex' }}>
        <span className="statusSeg"><Ico name="square-terminal" size={11} /> {view}</span>
        {sess ? <span className="statusSeg ok"><Ico name="circle-dot" size={11} /> {sess.agent} · {sess.name}</span> : null}
      </div>
      <div className="statusRight">
        <span className="statusSeg warn"><Ico name="bell-dot" size={11} /> 1 attention</span>
        <span className="statusSeg"><Ico name="volume-x" size={11} /> muted</span>
        <span className="statusSeg"><Ico name="clock" size={11} /> 14:32</span>
      </div>
    </div>
  );
}

/* ---------- Shell ---------- */
function Workspace() {
  const [view, setView] = useState('terminals');
  const [selected, setSelected] = useState('s2');
  const [focus, setFocus] = useState('s2');
  useLucide([view, selected, focus]);

  return (
    <div className="deskShell">
      <div className="terminalFrame">
        <Topbar onKill={() => {}} />
        <div className="deskContent">
          <AppRail view={view} setView={setView} />
          {view === 'terminals' ? (
            <div className="subsystemPanels">
              <Sidebar selected={selected} setSelected={(id) => { setSelected(id); setFocus(id); }} />
              <TerminalsView focus={focus} setFocus={(id) => { setFocus(id); setSelected(id); }} />
            </div>
          ) : view === 'channels' ? <window.ChannelsView />
            : view === 'editor' ? <EditorView />
            : view === 'git' ? <GitView />
            : view === 'projects' ? <ProjectsView />
            : view === 'notes' ? <NotesView />
            : <div className="subsystemPanels single"><Placeholder icon={SUBSYSTEMS.find(s=>s.id===view).icon} label={view} /></div>}
        </div>
        <StatusBar view={view} selected={selected} />
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<Workspace />);
