// Terminal component — interactive shell with real commands
const { useState, useEffect, useRef, useCallback } = React;

function TerminalLine({ line }) {
  if (line.html) {
    return <div className={"line " + (line.type || '')} dangerouslySetInnerHTML={{__html: line.html}} />;
  }
  if (line.prompt) {
    return (
      <div className="prompt-line">
        <span className="user">visitor</span>
        <span className="at">@</span>
        <span className="host">varad.sh</span>
        <span className="sym">:</span>
        <span className="path">~</span>
        <span className="sym">$</span>
        <span className="cmd-static">{line.text}</span>
      </div>
    );
  }
  return <div className={"line " + (line.type || '')}>{line.text}</div>;
}

function Terminal() {
  const [history, setHistory] = useState([]);
  const [cmd, setCmd] = useState('');
  const [cmdHist, setCmdHist] = useState([]);
  const [histIdx, setHistIdx] = useState(-1);
  const [booted, setBooted] = useState(false);
  const bodyRef = useRef(null);
  const inputRef = useRef(null);

  const push = useCallback((items) => {
    setHistory(h => [...h, ...(Array.isArray(items) ? items : [items])]);
  }, []);

  // Boot sequence
  useEffect(() => {
    const boot = async () => {
      const steps = [
        { text: 'varad.sh v4.0.7 — init...', type: 'sys', d: 120 },
        { text: '[ ok ] loading identity matrix', type: 'ok', d: 80 },
        { text: '[ ok ] establishing secure channel', type: 'ok', d: 80 },
        { text: '[ ok ] mounting /projects /skills /writing', type: 'ok', d: 80 },
        { text: '[ ok ] warming up AI subprocesses', type: 'ok', d: 80 },
        { text: 'ready.', type: 'info', d: 120 },
        { text: '', d: 50 },
        { text: 'type `help` to see what i can show you.', type: 'sys', d: 0 },
        { text: 'try: about · projects · skills · contact · matrix · sudo', type: 'sys', d: 0 },
        { text: '', d: 0 },
      ];
      for (const s of steps) {
        await new Promise(r => setTimeout(r, s.d));
        push({ text: s.text, type: s.type });
      }
      setBooted(true);
      setTimeout(() => inputRef.current && inputRef.current.focus(), 50);
    };
    boot();
  }, [push]);

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [history]);

  const run = useCallback((raw) => {
    const input = raw.trim();
    push({ prompt: true, text: input });
    if (!input) { return; }
    setCmdHist(h => [...h, input].slice(-50));
    setHistIdx(-1);

    const [c, ...args] = input.split(/\s+/);
    const cmd = c.toLowerCase();
    const D = window.DATA;

    const out = [];

    switch (cmd) {
      case 'help':
      case '?':
        out.push({ type: 'info', text: 'AVAILABLE COMMANDS' });
        out.push({ type: 'sys', text: '  about          — who is varad' });
        out.push({ type: 'sys', text: '  projects       — list shipped work' });
        out.push({ type: 'sys', text: '  skills         — the stack' });
        out.push({ type: 'sys', text: '  experience     — timeline' });
        out.push({ type: 'sys', text: '  contact        — how to reach me' });
        out.push({ type: 'sys', text: '  whoami         — identity dump' });
        out.push({ type: 'sys', text: '  ls             — filesystem' });
        out.push({ type: 'sys', text: '  cat readme     — read the readme' });
        out.push({ type: 'sys', text: '  neofetch       — system info' });
        out.push({ type: 'sys', text: '  matrix         — toggle matrix rain' });
        out.push({ type: 'sys', text: '  theme <color>  — green|cyan|magenta|yellow|violet' });
        out.push({ type: 'sys', text: '  clear          — clear screen' });
        out.push({ type: 'sys', text: '  sudo           — elevate (?)' });
        out.push({ type: 'sys', text: '  exit           — good luck with that' });
        break;

      case 'about':
      case 'whoami':
        out.push({ type: 'info', text: `> ${D.name}` });
        out.push({ type: 'sys', text: `  role : ${D.title}` });
        out.push({ type: 'sys', text: `  loc  : ${D.location}` });
        out.push({ type: 'sys', text: `  stat : ${D.status}` });
        out.push({ text: '' });
        D.about.forEach(l => out.push({ text: l }));
        break;

      case 'projects':
      case 'ls':
        if (cmd === 'ls' && args[0]) {
          out.push({ type: 'err', text: `ls: ${args[0]}: No such file or directory (nice try)` });
          break;
        }
        if (cmd === 'ls') {
          out.push({ type: 'info', text: `total ${D.projects.length}` });
          D.projects.forEach((p,i)=>{
            out.push({ html: `<span class="ok">drwxr-xr-x</span> varad varad  42  ${p.name.toLowerCase().replace(/\s+/g,'-')}/` });
          });
        } else {
          D.projects.forEach((p, i) => {
            out.push({ type: 'info', text: `[${i+1}] ${p.name}` });
            out.push({ type: 'sys', text: `    ${p.desc}` });
            out.push({ html: `    live: <span class="ok">${p.url}</span>` });
            if (p.repo && p.repo !== p.url) out.push({ html: `    repo: <span class="info">${p.repo}</span>` });
            out.push({ text: '' });
          });
        }
        break;

      case 'skills':
        D.skills.forEach(s => {
          out.push({ html: `<span class="ok">${s.label.padEnd(12)}</span> :: <span class="info">${s.items.join('  ')}</span>` });
        });
        break;

      case 'experience':
      case 'history':
        if (!D.timeline) { out.push({ type:'sys', text:'no timeline data. ask instead: `ask about your experience`' }); break; }
        D.timeline.forEach(t => {
          out.push({ html: `<span class="warn">${t.date.padEnd(14)}</span> <span class="ok">${t.title}</span>` });
          out.push({ type: 'sys', text: `               ${t.desc}` });
        });
        break;

      case 'contact':
        out.push({ type: 'info', text: 'CONTACT' });
        out.push({ html: `  email    : <a href="mailto:${D.email}" class="ok" style="color:var(--accent);text-decoration:underline">${D.email}</a>` });
        out.push({ html: `  github   : <a href="${D.github}" target="_blank" style="color:var(--accent-3);text-decoration:underline">${D.github}</a>` });
        out.push({ html: `  linkedin : <a href="${D.linkedin}" target="_blank" style="color:var(--accent-3);text-decoration:underline">${D.linkedin}</a>` });
        break;

      case 'neofetch': {
        out.push({ html: `
<pre class="line ok" style="color:var(--accent);line-height:1.2;font-size:12px;">
       _            _               
__   _(_) __ _  ___| | ___  ___     
\\ \\ / / |/ _\` |/ _ \\ |/ _ \\/ __|    
 \\ V /| | (_| |  __/ |  __/\\__ \\    
  \\_/ |_|\\__,_|\\___|_|\\___||___/    
</pre>
` });
        out.push({ html: `<span class="ok">OS       </span> : varad.sh 4.0.7` });
        out.push({ html: `<span class="ok">Kernel   </span> : caffeine-6.9.1` });
        out.push({ html: `<span class="ok">Shell    </span> : /bin/curiosity` });
        out.push({ html: `<span class="ok">Uptime   </span> : since birth` });
        out.push({ html: `<span class="ok">Packages </span> : 50+ repos, 2.4k commits/yr` });
        out.push({ html: `<span class="ok">Editor   </span> : vim + tmux, always` });
        break;
      }

      case 'cat': {
        const target = args.join(' ').toLowerCase();
        if (!target) { out.push({ type: 'err', text: 'cat: missing operand. try `cat readme`' }); break; }
        if (target.includes('readme')) {
          out.push({ type: 'info', text: '=== README.md ===' });
          out.push({ text: '# hi.' });
          out.push({ text: '' });
          out.push({ text: 'i build things. mostly backend, sometimes full stack.' });
          out.push({ text: 'always shipping.' });
          out.push({ text: '' });
          out.push({ text: 'collab: agrawalvaradraj2007@gmail.com' });
        } else {
          out.push({ type: 'err', text: `cat: ${target}: No such file` });
        }
        break;
      }

      case 'matrix':
      case 'bg': {
        const modes = ['matrix','particles','grid','off'];
        const cur = window.getBgMode();
        const next = args[0] && modes.includes(args[0]) ? args[0] : modes[(modes.indexOf(cur)+1)%modes.length];
        window.setBgMode(next);
        out.push({ type: 'ok', text: `bg: ${cur} → ${next}` });
        break;
      }

      case 'theme': {
        const map = { green:'#00ff9c', cyan:'#00e5ff', magenta:'#ff3cac', yellow:'#ffee00', violet:'#b388ff', orange:'#ff7e36' };
        const t = args[0];
        if (!t || !map[t]) {
          out.push({ type: 'err', text: `theme: usage: theme [${Object.keys(map).join('|')}]` });
          break;
        }
        window.setAccentColor(map[t]);
        out.push({ type: 'ok', text: `theme → ${t}` });
        break;
      }

      case 'clear':
      case 'cls':
        setHistory([]);
        return;

      case 'sudo':
        out.push({ type: 'err', text: `[sudo] password for visitor: ` });
        out.push({ type: 'sys', text: `                  ✗✗✗✗✗✗✗` });
        out.push({ type: 'err', text: `sudo: 3 incorrect password attempts` });
        out.push({ type: 'warn', text: `this incident will be reported to /dev/null` });
        break;

      case 'rm':
        if (args.includes('-rf') && args.includes('/')) {
          out.push({ type: 'err', text: 'rm: refusing to. try it on your own machine, hero.' });
        } else {
          out.push({ type: 'err', text: `rm: cannot remove '${args.join(' ')}': Read-only filesystem` });
        }
        break;

      case 'exit':
      case 'quit':
      case 'logout':
        out.push({ type: 'err', text: 'nope. you live here now.' });
        break;

      case 'date':
        out.push({ type: 'sys', text: new Date().toString() });
        break;

      case 'echo':
        out.push({ text: args.join(' ') });
        break;

      case 'hack':
      case 'hack --nasa':
        simulateHack(push);
        return;

      case 'coffee':
      case 'chai':
        out.push({ type: 'warn', text: `brewing... ☕` });
        out.push({ type: 'ok', text: 'done. +1 productivity. +1 anxiety.' });
        break;

      case 'ask': {
        const q = args.join(' ');
        if (!q) { out.push({ type:'err', text:'usage: ask <question>  — talks to an AI about me' }); break; }
        push({ type: 'sys', text: `querying AI about varad...` });
        askAI(q, push);
        return;
      }

      default:
        out.push({ type: 'err', text: `command not found: ${cmd}` });
        out.push({ type: 'sys', text: `try: help` });
    }

    push(out);
  }, [push]);

  async function askAI(q, push) {
    try {
      const sys = `You are varad.sh, an AI assistant embedded in Varad Raj Agrawal's portfolio terminal. Answer questions about Varad in a short, dry, technical, matter-of-fact tone. Max 3 short sentences. Facts: full-stack dev, backend-heavy, open-source contributor, AI/ML tinkerer, startup builder. Based in India. Built vermix.in and focus-11f3c.web.app. Email: agrawalvaradraj2007@gmail.com. If asked something you don't know, say so briefly. No emoji.`;
      const res = await window.claude.complete({
        messages: [{ role: 'user', content: `${sys}\n\nQuestion: ${q}` }]
      });
      push({ type: 'info', text: res.trim() });
    } catch (e) {
      push({ type: 'err', text: `ai subprocess failed: ${e && e.message || e}` });
    }
  }

  async function simulateHack(push) {
    const lines = [
      { t: 'sys', s: 'INITIATING INTRUSION SEQUENCE...' },
      { t: 'warn', s: '> bypassing firewall' },
      { t: 'ok', s: '[==========>........] 52%' },
      { t: 'ok', s: '[================>..] 89%' },
      { t: 'ok', s: '[==================] 100%' },
      { t: 'err', s: 'ACCESS GRANTED' },
      { t: 'info', s: 'just kidding. please don\'t actually do this.' },
    ];
    for (const l of lines) {
      await new Promise(r => setTimeout(r, 180));
      push({ type: l.t, text: l.s });
    }
  }

  const onKey = (e) => {
    if (e.key === 'Enter') {
      run(cmd);
      setCmd('');
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      if (cmdHist.length) {
        const ni = histIdx < 0 ? cmdHist.length - 1 : Math.max(0, histIdx - 1);
        setHistIdx(ni);
        setCmd(cmdHist[ni]);
      }
    } else if (e.key === 'ArrowDown') {
      e.preventDefault();
      if (histIdx >= 0) {
        const ni = histIdx + 1;
        if (ni >= cmdHist.length) { setHistIdx(-1); setCmd(''); }
        else { setHistIdx(ni); setCmd(cmdHist[ni]); }
      }
    } else if (e.key === 'l' && (e.ctrlKey || e.metaKey)) {
      e.preventDefault();
      setHistory([]);
    }
  };

  return (
    <div className="terminal" onClick={() => inputRef.current && inputRef.current.focus()}>
      <div className="terminal-chrome">
        <span className="tdot r"></span>
        <span className="tdot y"></span>
        <span className="tdot g"></span>
        <span>varad@terminal — bash — 120×32</span>
        <span className="path">~/portfolio</span>
      </div>
      <div className="terminal-body" ref={bodyRef}>
        {history.map((l, i) => <TerminalLine key={i} line={l} />)}
        {booted && (
          <div className="prompt-line">
            <span className="user">visitor</span>
            <span className="at">@</span>
            <span className="host">varad.sh</span>
            <span className="sym">:</span>
            <span className="path">~</span>
            <span className="sym">$</span>
            <input
              ref={inputRef}
              className="cmd"
              value={cmd}
              onChange={(e) => setCmd(e.target.value)}
              onKeyDown={onKey}
              autoFocus
              spellCheck={false}
              autoComplete="off"
            />
          </div>
        )}
      </div>
    </div>
  );
}

window.Terminal = Terminal;
