// Terminal — shell.jsx: the wrapping "OS" — window chrome, tmux-style
// split-pane layout with a tmux status bar, boot sequence + login, nav
// sidebar (click → inject command into focused pane), konami code.

function TerminalSite() {
  const C = window.TERM_PALETTE;
  const T = window.TERM_CONTENT;

  const [booted, setBooted] = React.useState(false);
  const [bootLines, setBootLines] = React.useState([]);
  const [splitRight, setSplitRight] = React.useState(false);
  const [splitBottom, setSplitBottom] = React.useState(false);
  const [focusedPane, setFocusedPane] = React.useState('main');
  const [clock, setClock] = React.useState(new Date());
  const [konami, setKonami] = React.useState(0);
  const paneReqRef = React.useRef({}); // pane -> queued command
  const [paneReqs, setPaneReqs] = React.useState({});

  // clock
  React.useEffect(() => { const t = setInterval(() => setClock(new Date()), 1000); return () => clearInterval(t); }, []);

  // boot sequence
  React.useEffect(() => {
    if (booted) return;
    const steps = [
      [C.dim,   '[    0.000000] Booting mfaceOS 26.04 LTS'],
      [C.dim,   '[    0.012312] Memory: 32768M available'],
      [C.dim,   '[    0.038120] CPU: 16 cores online'],
      [C.dim,   '[    0.212004] systemd-udevd[211]: starting'],
      [C.dim,   '[    0.481020] eth0: link up (1000Mbps/Full)'],
      [C.green, '[  OK  ] Started Load Kernel Modules.'],
      [C.green, '[  OK  ] Started Apply Kernel Variables.'],
      [C.green, '[  OK  ] Started zsh.'],
      [C.green, '[  OK  ] Reached target mface.net.'],
      [C.dim,   ''],
      [C.fg,    'mface login: shawn'],
      [C.fg,    'Password: ' + '•'.repeat(8)],
      [C.dim,   ''],
      [C.fg,    'Welcome to mfaceOS 26.04 LTS (GNU/Linux 6.8.0 x86_64)'],
      [C.dim,   ''],
      [C.orange, ' * The paved road is shorter than the scenic route, but also boring.'],
      [C.orange, ' * Type `help` for the list of commands. Type `motd` for the day\'s wisdom.'],
      [C.dim,   ''],
      [C.dim,   'Last login: Mon Apr 20 09:14:02 2026 from 10.0.0.42'],
    ];
    let i = 0;
    const t = setInterval(() => {
      if (i >= steps.length) { clearInterval(t); setBooted(true); return; }
      const [color, text] = steps[i++];
      setBootLines((ls) => [...ls, { color, text }]);
    }, 75);
    return () => clearInterval(t);
  }, [booted]);

  // skip boot on any key
  React.useEffect(() => {
    if (booted) return;
    const k = () => setBooted(true);
    window.addEventListener('keydown', k);
    window.addEventListener('click', k);
    return () => { window.removeEventListener('keydown', k); window.removeEventListener('click', k); };
  }, [booted]);

  // konami
  React.useEffect(() => {
    const seq = ['ArrowUp','ArrowUp','ArrowDown','ArrowDown','ArrowLeft','ArrowRight','ArrowLeft','ArrowRight','b','a'];
    let i = 0;
    const k = (e) => {
      if (e.key === seq[i] || e.key.toLowerCase() === seq[i]) { i++; if (i === seq.length) { i = 0; setKonami((n) => n + 1); } }
      else i = 0;
    };
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, []);

  const sendTo = (paneId, cmd) => {
    setPaneReqs((p) => ({ ...p, [paneId]: { cmd, n: (p[paneId]?.n || 0) + 1 } }));
  };

  const navItems = [
    ['about', 'about'],
    ['projects', 'projects'],
    ['now', 'now'],
    ['uses', 'uses'],
    ['contact', 'contact'],
    ['help', 'help'],
    ['motd', 'motd'],
    ['fortune', 'fortune'],
  ];

  return (
    <div style={{
      position: 'relative', width: '100%', height: '100%',
      background: C.bg, color: C.fg, fontFamily: window.TERM_FONT,
      fontSize: 13, lineHeight: 1.5, overflow: 'hidden', boxSizing: 'border-box',
      display: 'flex', flexDirection: 'column',
    }}>
      <style>{`
        .mf-tabbtn { cursor:pointer; padding:2px 10px; color:${C.dim}; border:none; background:transparent; font: inherit }
        .mf-tabbtn[data-active="true"] { color:${C.fg}; background:${C.bgAlt} }
        .mf-navitem { cursor:pointer; padding:3px 10px; display:flex; gap:8px; border-left:2px solid transparent; color:${C.fg} }
        .mf-navitem:hover { background:rgba(255,255,255,.04) }
        .mf-btn { background:${C.bgAlt}; color:${C.fg}; border:1px solid ${C.border}; padding:2px 8px; cursor:pointer; font: inherit; font-size:11px }
        .mf-btn:hover { background:${C.panel}; border-color:${C.orange} }
      `}</style>

      {/* Window chrome */}
      <div style={{ height: 28, background: '#111', borderBottom: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', padding: '0 10px', gap: 8, flexShrink: 0 }}>
        <div style={{ display: 'flex', gap: 6 }}>
          <div style={{ width: 11, height: 11, borderRadius: 6, background: '#e06c6c' }} />
          <div style={{ width: 11, height: 11, borderRadius: 6, background: '#e0b54c' }} />
          <div style={{ width: 11, height: 11, borderRadius: 6, background: '#79c06a' }} />
        </div>
        <div style={{ flex: 1, textAlign: 'center', color: '#bbb', fontSize: 12 }}>shawn@mface: ~ — tmux</div>
        <div style={{ color: C.dim, fontSize: 12 }}>100×32 · utf-8</div>
      </div>

      {/* Body: nav sidebar + panes */}
      <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>

        {/* Nav sidebar */}
        <div style={{ width: 200, background: C.panel, borderRight: `1px solid ${C.border}`, padding: '10px 0', overflow: 'auto', flexShrink: 0 }}>
          <div style={{ color: C.orange, padding: '0 12px 6px', fontSize: 11, letterSpacing: 1 }}>── MENU ──</div>
          {navItems.map(([k, label]) => (
            <div key={k} className="mf-navitem" onClick={() => sendTo(focusedPane, k)}>
              <span style={{ color: C.dim }}>›</span>
              <span>{label}</span>
            </div>
          ))}
          <div style={{ color: C.orange, padding: '14px 12px 6px', fontSize: 11, letterSpacing: 1 }}>── PANES ──</div>
          <div style={{ padding: '0 12px', display: 'flex', flexDirection: 'column', gap: 5 }}>
            <button className="mf-btn" onClick={() => setSplitRight((x) => !x)}>{splitRight ? '× close right' : '+ split right'}</button>
            <button className="mf-btn" onClick={() => setSplitBottom((x) => !x)}>{splitBottom ? '× close bottom' : '+ split bottom'}</button>
          </div>
          <div style={{ color: C.orange, padding: '14px 12px 6px', fontSize: 11, letterSpacing: 1 }}>── KEYS ──</div>
          <div style={{ padding: '0 12px', fontSize: 11, color: C.dim, lineHeight: 1.75 }}>
            <div><span style={{ color: C.yellow }}>↑/↓</span> history</div>
            <div><span style={{ color: C.yellow }}>Tab</span> complete</div>
            <div><span style={{ color: C.yellow }}>^L</span> clear</div>
            <div><span style={{ color: C.yellow }}>^C</span> cancel</div>
          </div>
          {konami > 0 && (
            <div style={{ margin: '16px 12px 0', padding: 8, background: C.bgAlt, border: `1px solid ${C.orange}`, fontSize: 11, color: C.yellow }}>
              ⇧ ★ KONAMI ★ ⇧<br/>
              <span style={{ color: C.dim }}>cheat mode engaged ({konami})</span>
            </div>
          )}
        </div>

        {/* Panes grid */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
            <div style={{ flex: 1, minWidth: 0, borderRight: splitRight ? `1px solid ${C.border}` : 'none' }}>
              {booted ? (
                <TermPaneHost paneId="main" isFocused={focusedPane === 'main'} onFocus={setFocusedPane}
                  request={paneReqs.main} initialBanner />
              ) : (
                <BootScreen lines={bootLines} C={C} />
              )}
            </div>
            {splitRight && booted && (
              <div style={{ flex: 1, minWidth: 0 }}>
                <TermPaneHost paneId="right" isFocused={focusedPane === 'right'} onFocus={setFocusedPane}
                  request={paneReqs.right} />
              </div>
            )}
          </div>
          {splitBottom && booted && (
            <div style={{ height: '40%', borderTop: `1px solid ${C.border}`, minHeight: 0 }}>
              <TermPaneHost paneId="bottom" isFocused={focusedPane === 'bottom'} onFocus={setFocusedPane}
                request={paneReqs.bottom} />
            </div>
          )}
        </div>
      </div>

      {/* tmux status bar */}
      <div style={{
        height: 22, background: '#111', borderTop: `1px solid ${C.border}`,
        display: 'flex', alignItems: 'center', fontSize: 11, flexShrink: 0, color: '#ddd',
      }}>
        <div style={{ background: C.orange, color: '#fff', height: '100%', padding: '0 10px', display: 'flex', alignItems: 'center', fontWeight: 600 }}>
          [mface]
        </div>
        <div style={{ padding: '0 10px', background: C.bgAlt, height: '100%', display: 'flex', alignItems: 'center', color: C.fg }}>
          0:zsh*
        </div>
        {splitRight && <div style={{ padding: '0 10px', height: '100%', display: 'flex', alignItems: 'center', color: C.dim }}>1:zsh</div>}
        {splitBottom && <div style={{ padding: '0 10px', height: '100%', display: 'flex', alignItems: 'center', color: C.dim }}>2:zsh</div>}
        <div style={{ flex: 1 }} />
        <div style={{ padding: '0 12px', color: C.dim }}>load 0.42 · 0.38 · 0.41</div>
        <div style={{ padding: '0 12px', color: C.dim }}>shawn@mface</div>
        <div style={{ padding: '0 12px', color: C.fg }}>{clock.toLocaleString('en-US', { weekday: 'short', hour: 'numeric', minute: '2-digit' })}</div>
      </div>
    </div>
  );
}

function BootScreen({ lines, C }) {
  return (
    <div style={{ height: '100%', overflow: 'auto', padding: '12px 16px', background: C.bg, fontFamily: window.TERM_FONT, fontSize: 12.5, lineHeight: 1.45, boxSizing: 'border-box' }}>
      {lines.map((l, i) => <div key={i} style={{ color: l.color, whiteSpace: 'pre-wrap' }}>{l.text || '\u00a0'}</div>)}
      <div style={{ color: C.dim, marginTop: 8, fontStyle: 'italic' }}>(press any key to skip)</div>
    </div>
  );
}

// Host wraps TermPane so we can forward a command injection request (from
// the sidebar) via a small effect without lifting all of pane state up.
function TermPaneHost({ paneId, isFocused, onFocus, request, initialBanner }) {
  const C = window.TERM_PALETTE;
  const T = window.TERM_CONTENT;
  const ref = React.useRef(null);
  const [bootstrapped, setBootstrapped] = React.useState(false);

  // We render TermPane with an initial buffer the first time; then commands
  // dispatched via `request` are delivered through a ref.
  const initial = React.useMemo(() => {
    if (!initialBanner) return [];
    return [
      ...T.banner,
      { type: 'line', parts: [{ type: 'span', color: C.dim, text: 'Welcome to mfaceOS — type ' }, { type: 'span', color: C.yellow, text: 'help' }, { type: 'span', color: C.dim, text: ' to get started.' }] },
      { type: 'line', parts: [] },
    ];
  }, []);

  return (
    <TermPaneBridge paneId={paneId} isFocused={isFocused} onFocus={onFocus} initial={initial} request={request} />
  );
}

// Bridge: re-exposes TermPane but forwards external requests by appending
// them to a queue the pane consumes in an effect. Implemented by
// remounting? No — we re-use TermPane with a small prop extension:
// `externalReq` — when it changes, TermPane should run that command.
function TermPaneBridge(props) {
  // We inject into TermPane by letting it listen to window custom events,
  // which is simpler than threading state. Emits a unique event per pane.
  const { paneId, request } = props;
  React.useEffect(() => {
    if (!request || !request.cmd) return;
    window.dispatchEvent(new CustomEvent('mf-term-run', { detail: { paneId, cmd: request.cmd, n: request.n } }));
  }, [request && request.n]);
  return <TermPane {...props} />;
}

window.TerminalSite = TerminalSite;
