/* DevRails epic page — shared parts */
const { useState } = React;

/* icon geometry inherited from console/atoms.jsx — 24-unit grid, sw 1.7, round caps + joins */
function Icon({ name, size = 15, sw = 1.7 }) {
  const P = {
    home: <><path d="M4 11.5 12 4l8 7.5"/><path d="M6 10v10h12V10"/><path d="M10 20v-6h4v6"/></>,
    board: <><rect x="3" y="4" width="5" height="16" rx="1"/><rect x="10" y="4" width="5" height="11" rx="1"/><rect x="17" y="4" width="4" height="7" rx="1"/></>,
    activity: <><path d="M3 12h4l2 6 4-14 2 8h6"/></>,
    approvals: <><path d="M4 6h11M4 12h11M4 18h7"/><path d="m16.5 17 2 2 3.5-4"/></>,
    deliveries: <><path d="M21 8 12 3 3 8v8l9 5 9-5z"/><path d="m3 8 9 5 9-5M12 13v8"/></>,
    settings: <><circle cx="12" cy="12" r="3"/><path d="M12 3v2.5M12 18.5V21M3 12h2.5M18.5 12H21M5.6 5.6l1.8 1.8M16.6 16.6l1.8 1.8M18.4 5.6l-1.8 1.8M7.4 16.6l-1.8 1.8"/></>,
    search: <><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></>,
    chevron: <><path d="m9 6 6 6-6 6"/></>,
    caretUD: <><path d="m8 10 4-4 4 4M8 14l4 4 4-4"/></>,
    back: <><path d="M15 6 9 12l6 6"/></>,
    check: <><path d="m5 12 4.5 4.5L19 7"/></>,
    alert: <><path d="M12 8v5"/><circle cx="12" cy="16.5" r="0.6" fill="currentColor"/><path d="M12 3 2 20h20z"/></>,
    gate: <><path d="M12 3 5 6v5c0 4 3 6.5 7 8 4-1.5 7-4 7-8V6z"/><path d="m9 11 2 2 4-4"/></>,
    spark: <><path d="M12 3v3M12 18v3M3 12h3M18 12h3M12 8a4 4 0 0 0 4 4 4 4 0 0 0-4 4 4 4 0 0 0-4-4 4 4 0 0 0 4-4z"/></>,
    doc: <><path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4M9 12h6M9 16h6"/></>,
    play: <><path d="M7 5l11 7-11 7z"/></>,
    ext: <><path d="M14 5h5v5M19 5l-8 8M11 6H6v12h12v-5"/></>,
    rows: <><rect x="3" y="4" width="18" height="4" rx="1"/><rect x="3" y="10" width="18" height="4" rx="1"/><rect x="3" y="16" width="18" height="4" rx="1"/></>,
    chevsL: <><path d="m11 6-6 6 6 6M18 6l-6 6 6 6"/></>,
  };
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">{P[name]}</svg>;
}
const I = {
  home: <Icon name="home"/>, board: <Icon name="board"/>, act: <Icon name="activity"/>,
  run: <Icon name="play"/>, appr: <Icon name="approvals"/>, ship: <Icon name="deliveries"/>,
  dec: <Icon name="rows"/>, gear: <Icon name="settings"/>, collapse: <Icon name="chevsL"/>,
  bell: <Icon name="gate" size={17}/>, spark: <Icon name="spark" size={17}/>, warn: <Icon name="alert" size={16}/>,
  chev: <Icon name="chevron" size={12}/>, chevL: <Icon name="back" size={12}/>, down: <Icon name="caretUD" size={12}/>,
  tick: <Icon name="check" size={11} sw={2.1}/>, ext: <Icon name="ext" size={11}/>,
  doc: <Icon name="doc" size={14}/>, search: <Icon name="search" size={13}/>,
  brand:<svg width="18" height="18" viewBox="0 0 64 64" fill="none"><path d="M6 16 L18 32 L6 48" stroke="#F4F1EA" strokeWidth="6" strokeLinecap="square" strokeLinejoin="miter" opacity="0.55"/><path d="M22 16 L34 32 L22 48" stroke="#F4F1EA" strokeWidth="6" strokeLinecap="square" strokeLinejoin="miter" opacity="0.8"/><path d="M38 16 L50 32 L38 48" stroke="#00D66B" strokeWidth="6" strokeLinecap="square" strokeLinejoin="miter"/></svg>,
};

function Rail({ hot = 2 }) {
  const items = [
    ['home', 'Epics', '35', true], ['board', 'Task board', '', false], ['act', 'Activity', '', false],
    ['run', 'Runs', '12', false], ['appr', 'Approvals', String(hot), false, true],
    ['ship', 'Deliveries', '', false], ['dec', 'Decisions', '', false],
  ];
  return (
    <div className="rail">
      <div className="rail-brand">{I.brand}<span className="word">devrails<i>.ai</i></span></div>
      <div className="rail-ws"><span className="mk">H</span><div style={{ minWidth: 0 }}><div className="nm">happily</div><div className="sub">WORKSPACE</div></div></div>
      <div className="rail-k">Work</div>
      {items.map(([ic, lbl, n, on, isHot]) => (
        <div className={'rail-i' + (on ? ' on' : '')} key={lbl}>
          <span className="gl">{I[ic]}</span><span className="lbl">{lbl}</span>
          {n && <span className={'n' + (isHot ? ' hot' : '')}>{n}</span>}
        </div>
      ))}
      <div className="rail-k">Project</div>
      <div className="rail-i"><span className="gl">{I.gear}</span><span className="lbl">Configure</span></div>
      <div className="rail-sp" />
      <div className="rail-collapse"><span className="gl">{I.collapse}</span><span className="lbl">Collapse</span></div>
      <div className="rail-u"><span className="av">R</span><div style={{ minWidth: 0 }}><div className="un">raghu.rajah</div><div className="ur">owner · happily</div></div></div>
    </div>
  );
}

/* micro workflow — one dot per step of THIS item's own workflow */
function Micro({ n, cur, fail, cap = 7 }) {
  const show = Math.min(n, cap), over = n - show;
  return <span className="mf">{Array.from({ length: show }).map((_, i) =>
    <i key={i} className={fail && i === cur ? 'f' : i < cur ? 'd' : i === cur ? 'c' : ''} />)}
    {over > 0 && <em>+{over}</em>}</span>;
}

const AG = { arch: 'ARCH', code: 'CODE', docs: 'DOCS', rsch: 'RSCH', dsgn: 'DSGN', you: 'YOU' };

function TreeRow({ n }) {
  /* an area — one row, its questions open in the canvas, not here */
  if (n.kind === 'area') return (
    <div className={'trow area' + (n.sel ? ' sel' : '') + (n.openCount ? ' you' : '')}>
      <span className={'qg ' + (n.openCount ? 'you' : 'done')} />
      <div className="tn"><div className="tt">{n.name}</div>{n.sub && <div className="ts"><span className="tsx">{n.sub}</span></div>}</div>
      <div className="tr">{n.openCount ? <span className="qn you">{n.openCount} open</span> : <span className="qn">{n.total}</span>}</div>
    </div>
  );
  /* a document — an artifact of the epic, not agent work */
  if (n.kind === 'doc') return (
    <div className={'trow doc' + (n.sel ? ' sel' : '') + (n.state === 'you' ? ' you' : '')}>
      <span className="dg">{I.doc}</span>
      <div className="tn"><div className="tt">{n.name}</div><div className="ts"><span className="tsx">{n.by}</span></div></div>
      <div className="tr">{n.state === 'you' && <span className="pill you">you</span>}{n.state === 'now' && <span className="live" />}</div>
    </div>
  );
  return (
    <div className={'trow l' + n.lvl + (n.sel ? ' sel' : '') + (n.state === 'you' ? ' you' : '')}>
      <span className={'g ' + n.state + (n.kind === 'child' ? ' sq' : '')} />
      <div className="tn">
        <div className="tt">{n.name}</div>
        {(n.agent || n.sub) && <div className="ts">
          {n.agent && <span className={'ag ' + n.agent}>{n.who || AG[n.agent]}</span>}
          {n.sub && <span className="tsx">{n.sub}</span>}
        </div>}
      </div>
      <div className="tr">
        {n.flow && <Micro n={n.flow} cur={n.cur} fail={n.state === 'fail'} />}
        {n.kind === 'child' && <span style={{ color: 'var(--ink-4)', display: 'grid' }}>{I.ext}</span>}
      </div>
    </div>
  );
}

const STAGES = ['Groom', 'Plan', 'Build', 'Validate', 'Ship'];
function EpicStage({ at, done }) {
  return (
    <div className="estage">
      {STAGES.map((s, i) => {
        const st = done || i < at ? 'done' : i === at ? 'now' : '';
        return <div className={'es ' + st} key={s}><i /><span>{s}</span></div>;
      })}
    </div>
  );
}

/* epic-level spend: what the agents have burned, and what is left */
function Meter({ cells }) {
  return <div className="meter">{cells.map((c, i) =>
    <div className="mc" key={i}><span className="mk">{c[0]}</span><span className="ml">{c[1]}</span></div>)}</div>;
}

function Tree({ title, id, sub, stage = 0, stageDone, filter = 'All', nodes, footNote, meter, filters = ['All', 'Needs you', 'Running'] }) {
  return (
    <div className="tree">
      <div className="tree-h">
        <div className="back">{I.chevL} All epics</div>
        <div className="nm">{title}</div>
        <div className="sub"><span className="mono">{id}</span><span style={{ color: 'var(--line-3)' }}>·</span><span>{sub}</span></div>
        <EpicStage at={stage} done={stageDone} />
        {meter && <Meter cells={meter} />}
      </div>
      <div className="tree-filter">
        {filters.map((f, i) => <span key={f} className={'tf' + (f === filter ? (f === 'Needs you' ? ' you' : ' on') : '')}>{f}</span>)}
      </div>
      <div className="tree-body">
        {nodes.map((n, i) => n.grp ? <div className="tgrp" key={i}>{n.grp}</div> : <TreeRow n={n} key={i} />)}
      </div>
      {footNote && <div className="tree-f"><span className="meta">{footNote}</span></div>}
    </div>
  );
}

/* per-item workflow — past steps are the ones with something to open;
   upcoming steps hold nothing yet, so they collapse into one dim preview */
function Flow({ steps, cur, restLabel, showPast = 3 }) {
  const past = steps.slice(0, cur), ahead = steps.slice(cur + 1);
  const shown = past.slice(-showPast), folded = past.length - shown.length;
  return (
    <div className="wf">
      {folded > 0 && <><div className="st past fold"><span className="tick">{Array.from({ length: Math.min(folded, 3) }).map((_, i) => <i key={i} />)}</span><div><div className="sn">+{folded} earlier</div><div className="sw">open any of them</div></div></div><span className="sep">{I.chev}</span></>}
      {shown.map((s, i) => <React.Fragment key={i}>
        <div className="st past"><span className="vd done">{I.tick}</span><div><div className="sn">{s.n}</div><div className="sw">{s.out || 'done'}</div></div></div>
        <span className="sep">{I.chev}</span>
      </React.Fragment>)}
      <div className="st cur"><div><div className="sn">{steps[cur].n}</div><div className="sw">{steps[cur].w}</div></div></div>
      {ahead.length > 0 && <>
        <span className="sep">{I.chev}</span>
        <div className="st ahead">
          <div><div className="sn">{ahead.map(s => s.n).join(' · ')}</div><div className="sw">not started — nothing to open yet</div></div>
          {ahead.some(s => s.gate) && <span className="pill you">you, later</span>}
        </div>
      </>}
      <div style={{ flex: 1 }} />
      <div className="st rest"><span className="sn">{restLabel}</span></div>
    </div>
  );
}

function Att({ tone = 'you', k, t, s, actions }) {
  return (
    <div className="att">
      <span className={'ic' + (tone === 'calm' ? ' calm' : '')}>{tone === 'calm' ? I.spark : I.bell}</span>
      <div className="m"><div className="k2">{k}</div><div className="t">{t}</div>{s && <div className="s">{s}</div>}</div>
      <div className="a">{actions}</div>
    </div>
  );
}

function WorkTop({ crumb, right }) {
  return (
    <div className="work-top">
      <div className="crumb">{crumb.map((c, i) => <React.Fragment key={i}>{i > 0 && <span style={{ color: 'var(--line-3)' }}>/</span>}<b>{c}</b></React.Fragment>)}</div>
      <div className="sp" />{right}
    </div>
  );
}

function Sec({ h, c, right }) {
  return <div className="sec"><h3>{h}</h3>{c && <span className="c">{c}</span>}<span className="sp" />{right}</div>;
}

/* storyline drawer */
function Ev({ e }) {
  return (
    <div className={'ev' + (e.dec ? ' dec' : '') + (e.bad ? ' bad' : '')}>
      <span className="dot" />
      <div className="eh"><span className="en">{e.who}</span>{e.tag && <span className={'pill ' + (e.tagK || '')}>{e.tag}</span>}<span className="ew">{e.when}</span></div>
      <div className="eb">{e.body}</div>
      {e.dec && <div className="decd"><span className="kk">Decision recorded</span>{e.dec}</div>}
      {e.more && <span className="more">{e.more}</span>}
    </div>
  );
}

function Story({ mode = 'shut', count, days, ask }) {
  if (mode === 'shut') return (
    <div className="story shut">
      <span style={{ color: 'var(--ink-3)', display: 'grid' }}>{I.chevL}</span>
      <span className="vlabel">Storyline</span>
      <span className="vc">{count}</span>
    </div>
  );
  return (
    <div className={'story ' + mode}>
      <div className="story-h">
        <div className="t">Storyline<span className="pill">{count}</span><span style={{ flex: 1 }} /><span style={{ color: 'var(--ink-4)', display: 'grid' }}>{I.chev}</span></div>
        <div className="s">Everything the agents did on this epic, newest first.</div>
      </div>
      <div className="story-b">
        {days.map((d, i) => (
          <React.Fragment key={i}>
            <div className="sday">{d.day}</div>
            {d.events.map((e, j) => <Ev e={e} key={j} />)}
          </React.Fragment>
        ))}
      </div>
      {ask && <div className="story-ask">
        <div className="q"><span style={{ color: 'var(--ink-4)', display: 'grid' }}>{I.search}</span><span className="inp">{ask.q}</span></div>
        {ask.a && <div className="ans"><div className="at">{ask.a}</div><div className="src">{ask.src.map((s, i) => <span className="pill" key={i}>{s}</span>)}</div></div>}
      </div>}
    </div>
  );
}

function TaskPanel({ task, tab = 'Task', days }) {
  return (
    <div className="story open tp">
      <div className="tp-tabs">
        <b className={tab === 'Task' ? 'on' : ''}>Task</b>
        <b className={tab === 'Storyline' ? 'on' : ''}>Storyline</b>
        <span style={{ flex: 1 }} />
        <span className="tp-x">{I.chev}</span>
      </div>
      <div className="tp-h">
        <div className="tp-nm">{task.nm}</div>
        <div className="tp-sub"><span className="mono">{task.id}</span><span style={{ color: 'var(--line-3)' }}>·</span><span className={'pill ' + task.pillK}>{task.state}</span></div>
      </div>
      <div className="story-b tp-b">
        <div className="tp-sec">Agent</div>
        <div className="tp-agent">
          <span className={'ag ' + task.agK}>{task.agent}</span>
          <div><div className="tp-an">{task.agentName}</div><div className="meta">{task.machine}</div></div>
        </div>
        <div className="tp-sec">Its workflow</div>
        <div className="vf">{task.flow.map((s, i) =>
          <div className={'vs ' + (i < task.cur ? 'done' : i === task.cur ? (task.fail ? 'fail' : 'cur') : '')} key={i}>
            <span className="vd">{i < task.cur ? I.tick : ''}</span>
            <div><div className="vn">{s.n}</div><div className="vw">{s.w}</div></div>
          </div>)}
        </div>
        <div className="tp-sec">Spent on this task</div>
        <div className="tp-grid">{task.spend.map((s, i) =>
          <div key={i}><span className="mk">{s[0]}</span><span className="ml">{s[1]}</span></div>)}
        </div>
        {task.note && <><div className="tp-sec">{task.noteK}</div><div className="log">{task.note}</div></>}
        <div className="tp-sec">Runs on this task</div>
        {days.map((e, i) => <Ev e={e} key={i} />)}
      </div>
      <div className="tp-f">{task.actions}</div>
    </div>
  );
}

Object.assign(window, { I, Icon, Rail, Meter, EpicStage, TaskPanel, Tree, TreeRow, Micro, Flow, Att, WorkTop, Sec, Story, Ev, AG });
