/* app.jsx — toolbar + canvas + tweaks. Owns global view state and threads
   it into every board so the highlight filter lights up across the canvas. */

const LS_KEY = 'agentflows.view.v1';
function loadView() {
  try { return JSON.parse(localStorage.getItem(LS_KEY) || '{}'); } catch { return {}; }
}

const MONO = '"JetBrains Mono", monospace';
const DISP = '"Space Grotesk", sans-serif';

// ── small toolbar controls ─────────────────────────────────────────────
function Seg({ value, options, onChange }) {
  return (
    <div style={{ display: 'flex', border: `1px solid ${PAL.line}`, borderRadius: 6, overflow: 'hidden', background: '#fff' }}>
      {options.map((o) => {
        const on = o.v === value;
        return (
          <button key={o.v} onClick={() => onChange(o.v)} style={{
            border: 'none', cursor: 'pointer', padding: '6px 11px',
            font: `600 11px ${MONO}`, letterSpacing: '.04em',
            background: on ? PAL.ink : 'transparent', color: on ? '#fff' : PAL.dim,
            transition: '.12s',
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

function ToolLabel({ children }) {
  return <span style={{ font: `600 9.5px ${MONO}`, letterSpacing: '.16em', color: PAL.faint, textTransform: 'uppercase' }}>{children}</span>;
}

function App() {
  const saved = React.useRef(loadView()).current;
  const [mode, setMode] = React.useState(saved.mode || 'build');
  const [sel, setSel] = React.useState(saved.sel || '');
  const [density, setDensity] = React.useState(saved.density || 'heavy');
  const [running, setRunning] = React.useState(false);
  const [t, setT] = React.useState(0);
  const timer = React.useRef(null);

  const tw = (typeof useTweaks === 'function') ? useTweaks(window.TWEAK_DEFAULTS) : [{}, () => {}];
  const tk = tw[0], setTweak = tw[1];
  if (tk.accent && PAL.accent !== tk.accent) PAL.accent = tk.accent;

  React.useEffect(() => {
    localStorage.setItem(LS_KEY, JSON.stringify({ mode, sel, density }));
  }, [mode, sel, density]);

  // run clock
  const play = () => {
    if (timer.current) return;
    if (t >= window.GLOBAL_MAX) setT(0);
    setRunning(true);
    timer.current = setInterval(() => {
      setT((x) => Math.min(x + 0.5, window.GLOBAL_MAX));
    }, 60);
  };
  const stop = () => { setRunning(false); clearInterval(timer.current); timer.current = null; };
  const toggleRun = () => (timer.current ? stop() : play());
  React.useEffect(() => { if (t >= window.GLOBAL_MAX) stop(); }, [t]);
  React.useEffect(() => () => clearInterval(timer.current), []);

  const view = { mode, sel: sel || null, density, running: running || t > 0, t, grid: tk.grid !== false };

  // boards using the current selection
  const usedCount = React.useMemo(() => {
    if (!sel) return 0;
    let n = 0, total = 0;
    window.SECTIONS.forEach((s) => s.boards.forEach((b) => {
      if (b.kind === 'stack') return;
      total++; if (window.boardUses(window.BOARDS[b.id], sel)) n++;
    }));
    return `${n}/${total}`;
  }, [sel]);

  const canvasBg = tk.tone === 'slate' ? '#e7ebf0' : tk.tone === 'paper' ? '#f3f1ec' : '#eaeef3';

  return (
    <div style={{ height: '100vh', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* ── toolbar ── */}
      <div style={{
        flex: '0 0 auto', display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap',
        padding: '10px 18px', background: '#fff', borderBottom: `1px solid ${PAL.line}`, zIndex: 30,
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.05 }}>
          <span style={{ font: `700 15px ${DISP}`, letterSpacing: '-0.2px', color: PAL.ink }}>
            Agent Flows <span style={{ color: PAL.accent }}>·</span> build & run map
          </span>
          <span style={{ font: `400 9.5px ${MONO}`, letterSpacing: '.14em', color: PAL.faint, marginTop: 2 }}>
            LANGGRAPH ARCHITECTING PASS · 12 DIAGRAMS
          </span>
        </div>

        <div style={{ width: 1, height: 30, background: PAL.line }} />

        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <ToolLabel>colour by</ToolLabel>
          <Seg value={mode} onChange={setMode} options={[
            { v: 'build', label: 'BUILD / BUY' }, { v: 'primitive', label: 'PRIMITIVE' }, { v: 'product', label: 'PRODUCT' },
          ]} />
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 232 }}>
          <ToolLabel>highlight component {sel ? `· used in ${usedCount}` : ''}</ToolLabel>
          <div style={{ display: 'flex', gap: 6 }}>
            <select value={sel} onChange={(e) => setSel(e.target.value)} style={{
              flex: 1, font: `500 12px ${MONO}`, color: PAL.ink, background: '#fff',
              border: `1px solid ${sel ? PAL.accent : PAL.line}`, borderRadius: 6, padding: '6px 9px', cursor: 'pointer',
            }}>
              <option value="">— none —</option>
              {['Shared primitives', 'Off-the-shelf', 'Adapt a model', 'Build it (deterministic)'].map((g) => (
                <optgroup key={g} label={g}>
                  {window.REGISTRY.filter((r) => r.group === g).map((r) => (
                    <option key={r.key} value={r.key}>{r.label}</option>
                  ))}
                </optgroup>
              ))}
            </select>
            {sel && (
              <button onClick={() => setSel('')} title="clear" style={{
                border: `1px solid ${PAL.line}`, background: '#fff', borderRadius: 6, cursor: 'pointer',
                font: `600 12px ${MONO}`, color: PAL.dim, padding: '0 10px',
              }}>✕</button>
            )}
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <ToolLabel>labels</ToolLabel>
          <Seg value={density} onChange={setDensity} options={[
            { v: 'heavy', label: 'HEAVY' }, { v: 'med', label: 'MEDIUM' }, { v: 'min', label: 'MIN' },
          ]} />
        </div>

        <div style={{ flex: 1 }} />

        {/* run controls */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 280 }}>
          <ToolLabel>runtime · shared clock {Math.round(t)}s / {window.GLOBAL_MAX}s</ToolLabel>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <button onClick={toggleRun} style={{
              flex: '0 0 auto', width: 34, height: 34, borderRadius: 17, border: 'none', cursor: 'pointer',
              background: PAL.accent, color: '#fff', font: '13px sans-serif', display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>{running ? '❚❚' : '▶'}</button>
            <input type="range" min="0" max={window.GLOBAL_MAX} step="0.5" value={t}
              onChange={(e) => { stop(); setT(parseFloat(e.target.value)); }}
              style={{ flex: 1, accentColor: PAL.accent, cursor: 'pointer' }} />
            <button onClick={() => { stop(); setT(0); }} title="reset" style={{
              border: `1px solid ${PAL.line}`, background: '#fff', borderRadius: 6, cursor: 'pointer',
              font: `600 10px ${MONO}`, color: PAL.dim, padding: '7px 9px',
            }}>RESET</button>
          </div>
        </div>
      </div>

      {/* ── canvas ── */}
      <div style={{ flex: 1, minHeight: 0, position: 'relative' }}>
        <DesignCanvas style={{ height: '100%', width: '100%', background: canvasBg }}>
          {window.SECTIONS.map((s) => (
            <DCSection key={s.id} id={s.id} title={s.title} subtitle={s.subtitle}>
              {s.boards.map((b) => (
                <DCArtboard key={b.id} id={b.id} label={b.label} width={b.w} height={b.h}>
                  {b.kind === 'stack'
                    ? <StackBoard view={view} />
                    : <Board id={b.id} view={view} />}
                </DCArtboard>
              ))}
            </DCSection>
          ))}
        </DesignCanvas>
      </div>

      {typeof TweaksPanel === 'function' && (
        <TweaksPanel title="Tweaks">
          <TweakSection label="Canvas" />
          <TweakRadio label="Background" value={tk.tone || 'cool'} options={['cool', 'paper', 'slate']}
            onChange={(v) => setTweak('tone', v)} />
          <TweakToggle label="Blueprint grid" value={tk.grid !== false} onChange={(v) => setTweak('grid', v)} />
          <TweakSection label="Accent" />
          <TweakColor label="Highlight" value={tk.accent || '#2f6df6'}
            options={['#2f6df6', '#0f9d8c', '#d98a1f', '#6b5bd6']}
            onChange={(v) => setTweak('accent', v)} />
          <TweakSection label="Labels" />
          <TweakRadio label="Density" value={density} options={['heavy', 'med', 'min']}
            onChange={(v) => setDensity(v)} />
        </TweaksPanel>
      )}
    </div>
  );
}

window.TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "tone": "cool",
  "grid": true,
  "accent": "#2f6df6"
}/*EDITMODE-END*/;

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