/* Boot sequence — typed terminal intro */
const BOOT_LINES = [
  { t: 120, html: `<span class="prompt">root@matrix</span>:<span class="dim">~</span>$ ./initialize --user "omar_bandial"` },
  { t: 180, html: `<span class="dim">[ ok ]</span> Connecting to mainframe...` },
  { t: 140, html: `<span class="dim">[ ok ]</span> Decrypting identity :: <span class="ok">ACCESS GRANTED</span>` },
  { t: 160, html: `<span class="dim">[ ok ]</span> Loading profile // <span class="ok">muhammad.omar.farooq.bandial</span>` },
  { t: 200, html: `<span class="dim">[ ok ]</span> Frontend runtime online — <span class="ok">React · TypeScript · Vite</span>` },
  { t: 200, html: `<span class="dim">[ ok ]</span> AI/ML stack online — <span class="ok">PyTorch · Transformers · Whisper</span>` },
  { t: 220, html: `<span class="prompt">root@matrix</span>:<span class="dim">~</span>$ cat /about/greeting.txt` },
];

function BootTerminal({ onComplete }) {
  const [lines, setLines] = React.useState([]);
  const [typing, setTyping] = React.useState('');
  const [done, setDone] = React.useState(false);
  const idxRef = React.useRef(0);

  React.useEffect(() => {
    let cancelled = false;
    async function run(){
      for (const L of BOOT_LINES) {
        if (cancelled) return;
        // type out one line char-by-char (HTML-safe: type the text, then commit HTML)
        const text = L.html.replace(/<[^>]+>/g, '');
        for (let i = 0; i <= text.length; i++) {
          if (cancelled) return;
          setTyping(text.slice(0, i));
          await new Promise(r => setTimeout(r, 8));
        }
        if (cancelled) return;
        setLines(prev => [...prev, L.html]);
        setTyping('');
        await new Promise(r => setTimeout(r, L.t));
      }
      setDone(true);
      if (onComplete) onComplete();
    }
    run();
    return () => { cancelled = true; };
  }, []);

  return (
    <div className="boot-terminal">
      {lines.map((l, i) => (
        <div className="line" key={i} dangerouslySetInnerHTML={{__html: l}} />
      ))}
      {!done && (
        <div className="line"><span dangerouslySetInnerHTML={{__html: typing}} /><span className="caret"></span></div>
      )}
      {done && <div className="line"><span className="caret"></span></div>}
    </div>
  );
}

window.BootTerminal = BootTerminal;
