// ─────────────────────────────────────────────────────────────
// Living tree prototype — shell.
// Canvas (threaded chat, edges + visible root branching) ⇄ Tree
// (sustainable expand/collapse). Controls: Author/Activity colour
// (A2 heatmap), a depth stepper (Collapse ⊖ / Expand ⊕), and Live.
// Default view draws ~500 nodes; the long tail stays collapsed as fronds.
// ─────────────────────────────────────────────────────────────
const PW = 390, PH = 760;
const STATUS = 38, HEADER = 60, CTRL = 40, CRUMB = 32;
const DFULL = window.LT;
const DEFAULT_LEVEL = DFULL.levelFor(500);   // depth that surfaces ~500 nodes

function Seg({ options, value, onChange }) {
  return (
    <div style={{ display: 'inline-flex', padding: 2, gap: 2, background: '#0F1A09',
      border: '0.5px solid #2D3A22', borderRadius: 999 }}>
      {options.map(([v, l]) => {
        const a = v === value;
        return (
          <button key={v} onClick={() => onChange(v)} style={{ padding: '4px 9px', borderRadius: 999, cursor: 'pointer',
            font: `${a ? 600 : 500} 10.5px var(--font-sans)`, background: a ? '#2C5F2E' : 'transparent',
            color: a ? '#F2EDE4' : '#586552', border: a ? '0.5px solid #4F8E51' : '0.5px solid transparent' }}>{l}</button>
        );
      })}
    </div>
  );
}

function App() {
  const [mode, setMode] = React.useState('canvas');
  const [color, setColor] = React.useState('author');
  const [live, setLive] = React.useState(false);
  const [focus, setFocus] = React.useState(DFULL.root.id);
  const [level, setLevel] = React.useState(DEFAULT_LEVEL);
  const [reveal, setReveal] = React.useState(null);   // node to surface when opened from Canvas
  const [chatFocus, setChatFocus] = React.useState(null); // message to thread to when opened from Tree
  const [openKey, setOpenKey] = React.useState(0);
  const [rendered, setRendered] = React.useState(0);
  const TD = DFULL;

  const openTree = (id) => { setReveal(id); setFocus(TD.root.id); setLevel(DEFAULT_LEVEL); setOpenKey((k) => k + 1); setMode('tree'); };
  const focusBranch = (id) => { setReveal(null); setFocus(id); setLevel(DEFAULT_LEVEL); setOpenKey((k) => k + 1); setMode('tree'); };
  const openChat = (id) => { setChatFocus(id); setMode('canvas'); };
  const back = () => {
    if (mode !== 'tree') return;
    if (focus !== TD.root.id) setFocus(TD.byId[focus].parent >= 0 ? TD.byId[focus].parent : TD.root.id);
    else setMode('canvas');
  };

  const isTree = mode === 'tree';
  const bodyH = PH - STATUS - HEADER - CTRL - (isTree ? CRUMB : 0);
  // breadcrumb: ALWAYS keep the root ("whole tree") clickable, truncate the middle
  const path = TD.pathTo(focus);
  const shown = path.length <= 4 ? path : [path[0], '…', ...path.slice(path.length - 2)];
  const subtitle = isTree
    ? `drawing ${rendered.toLocaleString()} of ${TD.total.toLocaleString()} nodes`
    : `${DFULL.total.toLocaleString()} nodes · chat${live ? ' · growing' : ''}`;

  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'radial-gradient(140% 100% at 50% 0%, #16241a 0%, #0a120a 60%)', padding: 24, boxSizing: 'border-box' }}>
      <div style={{ width: PW, height: PH, background: '#07100A', borderRadius: 40, overflow: 'hidden',
        boxShadow: '0 40px 100px rgba(0,0,0,0.6), 0 0 0 1px #2D3A22', position: 'relative', display: 'flex', flexDirection: 'column' }}>

        {/* status */}
        <div style={{ height: STATUS, flexShrink: 0, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 24px', color: '#F2EDE4' }}>
          <span style={{ font: '600 14px var(--font-sans)' }}>03:03</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
            <svg width="14" height="11" viewBox="0 0 14 11" fill="none"><path d="M1 4c1.5-1.4 3.7-2.2 6-2.2s4.5.8 6 2.2" stroke="#F2EDE4" strokeWidth="1.2" strokeLinecap="round"/><circle cx="7" cy="9" r="1" fill="#F2EDE4"/></svg>
            <svg width="14" height="11" viewBox="0 0 14 11" fill="none"><rect x="0" y="8" width="2" height="3" fill="#F2EDE4"/><rect x="3" y="6" width="2" height="5" fill="#F2EDE4"/><rect x="6" y="3" width="2" height="8" fill="#F2EDE4"/><rect x="9" y="0" width="2" height="11" fill="#F2EDE4"/></svg>
            <span style={{ font: '600 10px var(--font-sans)', padding: '1.5px 6px', border: '1px solid #F2EDE4', borderRadius: 999 }}>100</span>
          </span>
        </div>

        {/* header */}
        <div style={{ height: HEADER, flexShrink: 0, display: 'flex', alignItems: 'center', gap: 10, padding: '0 14px', borderBottom: '0.5px solid #14210C' }}>
          <button onClick={back} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#C9D2BB', padding: 4, display: 'flex' }}>
            <FLIcons.ChevronLeft size={20} color="#C9D2BB"/>
          </button>
          <div style={{ width: 34, height: 34, borderRadius: '50%', background: '#1F4520', border: '0.5px solid #2C5F2E', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#F2EDE4', font: '500 13px var(--font-mono)', flexShrink: 0 }}>M</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ font: '500 15px var(--font-mono)', color: '#F2EDE4' }}>marina_k</div>
            <div style={{ font: 'italic 400 11px var(--font-serif)', color: '#8A9678' }}>{subtitle}</div>
          </div>
          <div style={{ display: 'inline-flex', padding: 3, gap: 2, background: '#0F1A09', border: '0.5px solid #2D3A22', borderRadius: 999 }}>
            {[['canvas', 'Canvas'], ['tree', 'Tree']].map(([m, label]) => {
              const a = mode === m;
              return <button key={m} onClick={() => m === 'tree' ? openTree(null) : (setChatFocus(null), setMode('canvas'))} style={{ padding: '6px 13px', borderRadius: 999, cursor: 'pointer', font: `${a ? 600 : 500} 12.5px var(--font-sans)`, background: a ? '#2C5F2E' : 'transparent', color: a ? '#F2EDE4' : '#586552', border: a ? '0.5px solid #4F8E51' : '0.5px solid transparent' }}>{label}</button>;
            })}
          </div>
        </div>

        {/* control strip */}
        <div style={{ height: CTRL, flexShrink: 0, display: 'flex', alignItems: 'center', gap: 8, padding: '0 14px', borderBottom: '0.5px solid #14210C' }}>
          {isTree && <Seg options={[['author', 'Author'], ['heat', 'Activity']]} value={color} onChange={setColor}/>}
          {isTree && (
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 2, padding: 2, background: '#0F1A09', border: '0.5px solid #2D3A22', borderRadius: 999 }}>
              <button onClick={() => setLevel((l) => Math.max(1, l - 1))} title="Collapse a level" style={{ width: 24, height: 24, borderRadius: '50%', cursor: 'pointer', background: 'transparent', border: 'none', color: '#C9D2BB', font: '600 15px var(--font-sans)', lineHeight: 1 }}>⊖</button>
              <span style={{ font: '600 10px var(--font-mono)', color: '#8A9678', minWidth: 44, textAlign: 'center' }}>depth {level}</span>
              <button onClick={() => setLevel((l) => Math.min(TD.maxDepth, l + 1))} title="Expand a level" style={{ width: 24, height: 24, borderRadius: '50%', cursor: 'pointer', background: 'transparent', border: 'none', color: '#C9D2BB', font: '600 15px var(--font-sans)', lineHeight: 1 }}>⊕</button>
            </div>
          )}
          <span style={{ flex: 1 }}/>
          <button onClick={() => setLive((l) => !l)} style={{ cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '5px 12px', borderRadius: 999, font: '600 11px var(--font-sans)',
            background: live ? '#2C5F2E' : '#0F1A09', border: `0.5px solid ${live ? '#4F8E51' : '#2D3A22'}`,
            color: live ? '#F4DCA0' : '#8A9678' }}>
            {live ? <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#D4960C' }}/> : '▶'}
            {live ? 'Live' : 'Go live'}
          </button>
        </div>

        {/* breadcrumb (tree) */}
        {isTree && (
          <div style={{ height: CRUMB, flexShrink: 0, display: 'flex', alignItems: 'center', gap: 4, padding: '0 14px', overflow: 'hidden', borderBottom: '0.5px solid #14210C' }}>
            {shown.map((id, i) => {
              if (id === '…') return <span key="ell" style={{ color: '#586552', font: '400 12px var(--font-mono)' }}>›&nbsp;…</span>;
              const n = TD.byId[id], isRoot = id === TD.root.id, last = id === focus;
              const label = isRoot ? '⌂ whole tree' : (n.text.length > 13 ? n.text.slice(0, 12) + '…' : n.text);
              return (
                <React.Fragment key={id}>
                  {i > 0 && <span style={{ color: '#3A4A30', font: '400 11px var(--font-sans)' }}>›</span>}
                  <button onClick={() => setFocus(id)} style={{ cursor: 'pointer', background: isRoot && !last ? '#0F1A09' : 'transparent', border: isRoot && !last ? '0.5px solid #2D3A22' : 'none', padding: '3px 8px', borderRadius: 999, whiteSpace: 'nowrap', font: `${last ? 600 : 500} 11.5px var(--font-sans)`, color: last ? '#F4DCA0' : '#76AB78' }}>{label}</button>
                </React.Fragment>
              );
            })}
          </div>
        )}

        {/* body */}
        <div style={{ flex: 1, position: 'relative', minHeight: 0 }}>
          {!isTree
            ? <CanvasChat data={DFULL} live={live} threadTo={chatFocus} onOpenBranch={(id) => focusBranch(id)}/>
            : <TreeView key={openKey} data={TD} colorMode={color} live={live} level={level}
                focusId={focus} revealId={reveal} size={{ w: PW, h: bodyH }} onFocus={setFocus}
                onHome={() => setFocus(TD.root.id)} onOpenChat={openChat} onStats={setRendered}/>}
        </div>
      </div>
    </div>
  );
}

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