// Shared shell pieces: sidebar, session header, transcript primitives.
const UK = window.UnknotDesignSystem_fb2a11;
const { Icon, Button, IconButton, SurfaceSwitcher, SidebarItem, NavRow, StatusPill, StatusIcon, OverflowMenu, Tooltip, ProjectPicker } = UK;

const PROJECTS = [
  { id: 'billing', name: 'acme/billing', path: '~/code/billing', waiting: 1, running: true },
  { id: 'web', name: 'acme/web', path: '~/code/web' },
  { id: 'pipeline', name: 'northwind/data-pipeline', path: '~/code/northwind/pipeline' },
];
const PROJECT_SESSIONS = {
  billing: [['Fix rounding in invoice totals', 'waiting', 'Waiting for you · 4m'], ['Stream CSV exports', 'running', 'Running · own worktree · 12m'], ['Address PR #412 review', 'done', 'Done · 1h'], ['Flaky ledger sync test', 'failed', 'Failed · provider error · 1d'], ['Upgrade vitest to 3.2', 'cancelled', 'Cancelled · 1d']],
  web: [['Pricing page copy', 'blocked', 'Blocked · waiting on design'], ['Dev server for docs', 'done', 'Done · 2d']],
  pipeline: [['Backfill March events', 'done', 'Done · 3d']],
};

const SESSIONS = {
  ask: [
    { group: 'Today', rows: [['E-invoicing start dates', 'Now'], ['Revenue recognition, multi-year deals', '2h'], ['Summarise the Northwind MSA', '4h']] },
    { group: 'Yesterday', rows: [['German version of welcome email', 'Yesterday'], ['Explain the new travel policy', 'Yesterday']] },
    { group: 'Last week', rows: [['Board meeting agenda ideas', 'Tue'], ['Pivot table formula help', 'Mon']] },
  ],
  task: [
    { group: 'Pinned', rows: [['Frankfurt data centre memo', 'running', 'Running · reviewing · 6m']] },
    { group: 'Today', rows: [['Q3 vendor spend review', 'done', 'Done · 20m'], ['Competitor pricing brief', 'running', 'Running · browsing · 14m'], ['EMEA onboarding deck', 'done', 'Done · 1h']] },
    { group: 'Yesterday', rows: [['Contract renewal tracker', 'failed', 'Failed · Salesforce sign-in expired'], ['Board memo edits', 'blocked', 'Blocked · folder not granted'], ['Travel policy FAQ', 'cancelled', 'Cancelled']] },
  ],
};

function TrafficLights() {
  return (
    <div style={{ display: 'flex', gap: 8 }}>
      {['#ff5f57', '#febc2e', '#28c840'].map((c) => <span key={c} style={{ width: 12, height: 12, borderRadius: 999, background: c }} />)}
    </div>
  );
}

function Wordmark({ theme, width = 76 }) {
  return <img src={theme === 'dark' ? '../assets/logo/unknot-wordmark-white.svg' : '../assets/logo/unknot-wordmark.svg'} alt="Unknot" style={{ width, display: 'block' }} />;
}

function Picker({ surface, onPicker, project, setProject, projects, setProjects }) {
  if (surface === 'ask') return null;
  const PP = window.UnknotDesignSystem_fb2a11.ProjectPicker;
  if (surface === 'project' && !PP) { const c = projects.find((x) => x.id === project) || projects[0]; return <div className="uk-ppick"><span className="uk-ppick__tile"><Icon name="folder" size={15} /></span><span className="uk-ppick__text"><span className="uk-ppick__name">{c.name}</span><span className="uk-ppick__path">{c.path}</span></span></div>; }
  if (surface === 'project') return <PP projects={projects} value={project} onChange={setProject} onAdd={() => { const id = 'new' + projects.length; setProjects([{ id, name: 'litware/reports', path: '~/Documents/litware-reports' }, ...projects]); setProject(id); }} />;
  const p = { icon: 'landmark', title: 'Finance workspace', sub: '2 granted folders', tint: true };
  return (
    <button type="button" onClick={onPicker} style={{ display: 'flex', alignItems: 'center', gap: 10, borderRadius: 'var(--radius-card)', border: '1px solid var(--color-border)', background: 'var(--color-card)', padding: '8px 10px', textAlign: 'left', boxShadow: 'var(--shadow-xs)', cursor: 'pointer', fontFamily: 'var(--font-sans)', color: 'var(--color-foreground)' }}>
      <span style={{ width: 28, height: 28, borderRadius: 'var(--radius-md)', background: p.tint ? 'var(--color-accent-soft)' : 'var(--color-muted)', display: 'grid', placeItems: 'center', color: p.tint ? 'var(--color-accent)' : 'var(--color-foreground-secondary)' }}><Icon name={p.icon} size={15} /></span>
      <span style={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0, lineHeight: 1.35 }}>
        <span style={{ fontSize: 'var(--font-size-base)', fontWeight: 600 }}>{p.title}</span>
        <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-muted-foreground)' }}>{p.sub}</span>
      </span>
      <Icon name="chevrons-up-down" size={13} style={{ color: 'var(--color-muted-foreground)' }} />
    </button>
  );
}

function Sidebar({ narrow, surface, onSurface, theme, onTheme, current, onOpen, onNew, onPalette, project, setProject }) {
  const [projects, setProjects] = React.useState(PROJECTS);
  const cur = projects.find((p) => p.id === project) || projects[0];
  const groups = surface === 'project' ? [{ group: cur.name, rows: PROJECT_SESSIONS[cur.id] || [] }] : SESSIONS[surface];
  return (
    <aside aria-label="Sessions" style={{ width: narrow ? 'var(--size-sidebar-narrow)' : 'var(--size-sidebar)', flexShrink: 0, display: 'flex', flexDirection: 'column', background: 'var(--color-sidebar)', borderRight: '1px solid var(--color-border)' }}>
      <div style={{ height: 44, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 12px 0 14px', flexShrink: 0 }}>
        <TrafficLights />
        <IconButton small icon="panel-left" label="Hide sidebar" shortcut="⌘\" />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, padding: '0 12px' }}>
        <div style={{ padding: '2px 4px' }}><Wordmark theme={theme} /></div>
        <SurfaceSwitcher value={surface} onChange={onSurface} />
        <Picker surface={surface} project={cur.id} setProject={setProject} projects={projects} setProjects={setProjects} />
        <div style={{ display: 'flex', gap: 6 }}>
          <Tooltip text="New session" shortcut="⌘N">
            <Button variant="primary" icon="plus" style={{ width: narrow ? 170 : 194, justifyContent: 'flex-start' }} onClick={onNew}>
              New session<span style={{ marginLeft: 'auto', fontSize: 'var(--font-size-sm)', color: 'var(--color-primary-meta)' }}>⌘N</span>
            </Button>
          </Tooltip>
          <IconButton icon="search" label="Search sessions" shortcut="⌘F" variant="secondary" onClick={onPalette} />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <NavRow icon="inbox" label="Inbox" count={3} />
          <NavRow icon="workflow" label="Workflows" />
        </div>
      </div>
      <nav aria-label="Session list" style={{ marginTop: 12, flex: 1, minHeight: 0, overflowY: 'auto', borderTop: '1px solid var(--color-border)', padding: '16px 12px 12px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        {groups.length && groups[0].rows.length === 0 ? <p style={{ margin: 0, padding: '0 8px', fontSize: 'var(--font-size-base)', color: 'var(--color-muted-foreground)' }}>No sessions yet.</p> : groups.map((g) => (
          <section key={g.group}>
            <h2 className="caps" style={{ margin: '0 0 6px', padding: '0 8px', color: 'var(--color-muted-foreground)' }}>{g.group}</h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {g.rows.map((r, i) => surface === 'ask'
                ? <SidebarItem key={r[0]} title={r[0]} icon="message-circle" meta={r[1]} current={current === r[0]} onClick={() => onOpen(r[0])} />
                : <SidebarItem key={r[0]} title={r[0]} status={r[1]} meta={r[2]} current={current === r[0]} onClick={() => onOpen(r[0])} />)}
            </div>
          </section>
        ))}
      </nav>
      <div style={{ height: 56, flexShrink: 0, display: 'flex', alignItems: 'center', gap: 4, borderTop: '1px solid var(--color-border)', padding: '0 12px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, minWidth: 0 }}>
          <span style={{ width: 28, height: 28, borderRadius: 999, background: 'var(--color-muted-strong)', display: 'grid', placeItems: 'center', fontSize: 'var(--font-size-sm)', fontWeight: 600, color: 'var(--color-foreground-secondary)' }}>MR</span>
          <span style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.3 }}>
            <span style={{ fontSize: 'var(--font-size-base)', fontWeight: 500 }}>Maya Reis</span>
            <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-muted-foreground)', display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="building-2" size={12} />Managed by Acme</span>
          </span>
        </div>
        <IconButton small icon="settings" label="Settings" shortcut="⌘," />
        <IconButton small icon={theme === 'dark' ? 'sun' : 'moon'} label="Toggle theme" onClick={onTheme} />
      </div>
    </aside>
  );
}

function SessionHeader({ title, status, statusLabel, context, panelOpen, onTogglePanel }) {
  return (
    <header style={{ height: 'var(--size-header)', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 10, padding: '0 16px 0 28px', borderBottom: '1px solid var(--color-border)' }}>
      <h1 style={{ margin: 0, fontSize: 'var(--font-size-md)', fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</h1>
      <StatusPill status={status} label={statusLabel} />
      <span style={{ flex: 1 }} />
      {context}
      <OverflowMenu label="Session actions" items={[{ label: 'Rename', icon: 'pencil' }, { label: 'Memory', icon: 'brain' }, { label: 'Pin session', icon: 'pin' }, { separator: true }, { label: 'Delete session', icon: 'trash-2', danger: true }]} />
      {!panelOpen ? <IconButton icon="panel-right" label="Show side panel" shortcut="⌘J" onClick={onTogglePanel} /> : null}
    </header>
  );
}

function ContextChip({ icon, children, tone }) {
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 'var(--font-size-base-sm)', color: tone === 'accent' ? 'var(--color-accent)' : 'var(--color-foreground-secondary)', fontFamily: tone === 'mono' ? 'var(--font-mono)' : undefined }}><Icon name={icon} size={13} />{children}</span>;
}

/* Transcript primitives */
function Activity({ icon, verb, children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, fontSize: 'var(--font-size-base)', color: 'var(--color-muted-foreground)', lineHeight: 1.5 }}>
      <Icon name={icon} size={13} style={{ marginTop: 3 }} />
      <span><span style={{ color: 'var(--color-foreground-secondary)', fontWeight: 500 }}>{verb}</span>&nbsp; {children}</span>
    </div>
  );
}

function UserMessage({ children }) {
  return <div style={{ alignSelf: 'flex-end', maxWidth: '88%', background: 'var(--color-bubble-user)', borderRadius: 'var(--radius-card)', padding: '9px 13px', lineHeight: 1.55 }}>{children}</div>;
}

function Prose({ children }) {
  return <div style={{ lineHeight: 1.6 }}>{children}</div>;
}

function ToolCall({ label = 'Ran command', command, result, tone = 'danger', output, defaultOpen = false }) {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div style={{ border: '1px solid var(--color-border)', borderRadius: 'var(--radius-card)', background: 'var(--color-card)', overflow: 'hidden' }}>
      <button type="button" onClick={() => setOpen(!open)} aria-expanded={open} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 8, height: 36, padding: '0 12px', border: 0, background: 'transparent', cursor: 'pointer', fontFamily: 'var(--font-sans)', color: 'var(--color-foreground)' }}>
        <Icon name={open ? 'chevron-down' : 'chevron-right'} size={13} style={{ color: 'var(--color-muted-foreground)' }} />
        <Icon name="square-terminal" size={13} style={{ color: 'var(--color-muted-foreground)' }} />
        <span style={{ fontSize: 'var(--font-size-base)', fontWeight: 600 }}>{label}</span>
        <span className="mono" style={{ fontSize: 'var(--font-size-base-sm)', color: 'var(--color-foreground-secondary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{command}</span>
        <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 'var(--font-size-sm)', color: tone === 'danger' ? 'var(--color-danger)' : 'var(--color-success)', whiteSpace: 'nowrap' }}>
          <Icon name={tone === 'danger' ? 'circle-x' : 'circle-check'} size={12} />{result}
        </span>
      </button>
      {open ? <pre style={{ margin: 0, padding: '10px 14px 12px 32px', borderTop: '1px solid var(--color-border-subtle)', fontSize: 'var(--font-size-base-sm)', lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>{output}</pre> : null}
    </div>
  );
}

function Helpers({ title = 'Helpers', count, rows }) {
  const [open, setOpen] = React.useState(true);
  return (
    <div style={{ border: '1px solid var(--color-border)', borderRadius: 'var(--radius-card)', background: 'var(--color-card)', padding: '10px 14px' }}>
      <button type="button" onClick={() => setOpen(!open)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 8, border: 0, background: 'transparent', padding: 0, cursor: 'pointer', fontFamily: 'var(--font-sans)', color: 'var(--color-foreground)' }}>
        <Icon name="network" size={13} style={{ color: 'var(--color-muted-foreground)' }} />
        <span style={{ fontSize: 'var(--font-size-base)', fontWeight: 600 }}>{title}</span>
        <span style={{ fontSize: 'var(--font-size-base-sm)', color: 'var(--color-muted-foreground)' }}>{count}</span>
        <Icon name={open ? 'chevron-up' : 'chevron-down'} size={13} style={{ marginLeft: 'auto', color: 'var(--color-muted-foreground)' }} />
      </button>
      {open ? (
        <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 4 }}>
          {rows.map((r, i) => (
            <div key={i} className="tabular" style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 'var(--font-size-base)', paddingLeft: r.child ? 24 : 0 }}>
              {r.child ? <span style={{ color: 'var(--color-faint-foreground)', marginLeft: -14, marginRight: -2 }}>└</span> : null}
              <StatusIcon status={r.status} />
              <span style={{ color: r.status === 'idle' ? 'var(--color-muted-foreground)' : 'var(--color-foreground)' }}>{r.name}</span>
              <span style={{ color: r.status === 'waiting' ? 'var(--color-warning)' : 'var(--color-muted-foreground)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>· {r.detail}</span>
              <span style={{ marginLeft: 'auto', color: 'var(--color-foreground-secondary)' }}>{r.cost}</span>
            </div>
          ))}
        </div>
      ) : null}
    </div>
  );
}

function PanelHeader({ tabs, value, onChange, onClose }) {
  return (
    <div style={{ height: 'var(--size-header)', flexShrink: 0, display: 'flex', alignItems: 'stretch', padding: '0 12px 0 10px', borderBottom: '1px solid var(--color-border)' }}>
      <UK.Tabs tabs={tabs} value={value} onChange={onChange} />
      <span style={{ flex: 1 }} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
        <OverflowMenu label="Pane actions" items={[{ label: 'Memory', icon: 'brain' }, { label: 'Artifacts', icon: 'shapes' }]} />
        <IconButton icon="panel-right-close" label="Hide side panel" shortcut="⌘J" onClick={onClose} />
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, SessionHeader, ContextChip, Activity, UserMessage, Prose, ToolCall, Helpers, PanelHeader, Wordmark, TrafficLights });
