/* ============================================================
   terminal.jsx — interactive shell playground
   ============================================================ */
const { useState: useStateT, useRef: useRefT, useEffect: useEffectT } = React;

function Terminal() {
  const D = window.PORTFOLIO;
  const prompt = `${D.identity.handle}@${D.identity.host}`;
  const banner = [
    { type: "out", html: `<span class="a">${prompt}</span>:~$ welcome. type <span class="w">help</span> to list commands, or try <span class="a">neofetch</span>, <span class="a">cat vault</span>, <span class="a">whoami</span>.` },
  ];
  const [lines, setLines] = useStateT(banner);
  const [val, setVal] = useStateT("");
  const [history, setHistory] = useStateT([]);
  const [hIdx, setHIdx] = useStateT(-1);
  const bodyRef = useRefT(null);
  const inputRef = useRefT(null);

  const scroll = () => { requestAnimationFrame(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }); };
  useEffectT(() => { scroll(); }, [lines]);

  const push = (arr) => setLines((l) => [...l, ...arr]);

  const COMMANDS = {
    help: () => [
      { type: "out", html: `<span class="w">available commands</span>` },
      { type: "out", html: `  <span class="a">whoami</span>      one-line bio          <span class="a">cat vault</span>    Vault case study` },
      { type: "out", html: `  <span class="a">about</span>       full summary          <span class="a">cat skills</span>   the stack` },
      { type: "out", html: `  <span class="a">ls</span>          list sections         <span class="a">style</span>       operating style` },
      { type: "out", html: `  <span class="a">experience</span>  career git log       <span class="a">projects</span>    engineering lab` },
      { type: "out", html: `  <span class="a">projects</span>    from-scratch builds   <span class="a">contact</span>     reach me` },
      { type: "out", html: `  <span class="a">neofetch</span>    system summary        <span class="a">resume</span>      open résumé` },
      { type: "out", html: `  <span class="a">goto &lt;sec&gt;</span>  scroll to a section   <span class="a">clear</span>       clear screen` },
      { type: "out", html: `  also: <span class="am">sudo</span>, <span class="am">date</span>, <span class="am">echo</span>, <span class="am">uptime</span>, <span class="am">pwd</span>` },
    ],
    whoami: () => [{ type: "out", html: `<span class="w">${D.identity.name}</span> — ${D.identity.role}. Backend & systems. Makes things <span class="a">11× faster</span> for a living.` }],
    about: () => [{ type: "out", html: D.identity.summary }],
    ls: () => [{ type: "out", html: `<span class="a">work/   projects/   operating-style/   experience/   terminal/   skills/   contact/</span>   <span class="w">resume.pdf</span>` }],
    pwd: () => [{ type: "out", html: `/home/${D.identity.handle}/portfolio` }],
    neofetch: () => {
      const i = D.identity;
      return [{ type: "out", html:
`<span class="a">      ___       </span>  <span class="a">${i.handle}</span>@<span class="a">${i.host}</span>
<span class="a">     /  /\\      </span>  ----------------
<span class="a">    /  /::\\     </span>  <span class="a">Role</span>   : ${i.role}
<span class="a">   /  /:/\\:\\    </span>  <span class="a">Focus</span>  : Backend · Systems · Search
<span class="a">  /  /:/  \\:\\   </span>  <span class="a">Uptime</span> : ${i.years} years
<span class="a">  \\  \\:\\  /:/   </span>  <span class="a">Langs</span>  : Go · Python · C · SQL
<span class="a">   \\  \\:\\/:/    </span>  <span class="a">Cloud</span>  : AWS · GCP · Terraform
<span class="a">    \\  \\::/     </span>  <span class="a">Kernel</span> : Solr · Kafka · Airflow
<span class="a">     \\  \\\\      </span>  <span class="a">Status</span> : <span class="w">available for work</span>
<span class="a">      \\__\\\\     </span>  <span class="a">Locale</span> : ${i.location}` }];
    },
    "cat vault": () => {
      const c = D.cases[0];
      return [
        { type: "out", html: `<span class="w"># Vault — ${c.co}</span>  <span class="am">(${c.dates})</span>` },
        { type: "out", html: c.blurb },
        ...c.bigstats.map((b) => ({ type: "out", html: `  <span class="a">${b.n.padEnd(7)}</span> ${b.l}` })),
      ];
    },
    "cat skills": () => D.skills.map((s) => ({ type: "out", html: `<span class="a">${("[" + s.key + "]").padEnd(22)}</span> ${s.vals.join(", ")}` })),
    skills: () => COMMANDS["cat skills"](),
    vault: () => COMMANDS["cat vault"](),
    projects: () => D.projects.map((p) => ({ type: "out", html: `<span class="a">→ ${p.name}</span> <span class="am">[${p.lang}]</span> — ${p.desc}` })),
    style: () => D.principles.map((p) => ({ type: "out", html: `<span class="a">${("[" + p.k + "]").padEnd(24)}</span> ${p.v}` })),
    experience: () => D.experience.map((e) => ({ type: "out", html: `<span class="am">${e.hash}</span> <span class="w">${e.msg}</span>  <span class="a">(${e.author})</span>` })),
    contact: () => [
      { type: "out", html: `<span class="a">email   </span> ${D.contact.email}` },
      { type: "out", html: `<span class="a">github  </span> ${D.contact.github}` },
      { type: "out", html: `<span class="a">linkedin</span> ${D.contact.linkedin}` },
      { type: "out", html: `<span class="a">phone   </span> ${D.contact.phone}` },
    ],
    resume: () => { window.open("uploads/Pulkit_Nijhawan_Resume.pdf", "_blank"); return [{ type: "out", html: `opening <span class="a">resume.pdf</span> …` }]; },
    sudo: () => [{ type: "out", html: `<span class="err">[sudo]</span> nice try. you already have root — just <span class="a">hire</span> him.` }],
    date: () => [{ type: "out", html: new Date().toString() }],
    uptime: () => [{ type: "out", html: `up <span class="a">${D.identity.years} years</span>,  load average: <span class="a">shipping, shipping, shipping</span>` }],
    clear: () => "CLEAR",
    help_alias: () => COMMANDS.help(),
  };

  const SECTIONS = { impact: "work", work: "work", experience: "experience", log: "experience", projects: "projects", lab: "projects", style: "operating-style", skills: "skills", shell: "terminal", terminal: "terminal", contact: "contact", top: "top" };

  const run = (raw) => {
    const cmd = raw.trim();
    const echo = { type: "cmd", html: `<span class="u">${prompt}</span><span class="p">:~$</span> ${cmd.replace(/</g, "&lt;")}` };
    if (!cmd) { push([echo]); return; }
    setHistory((h) => [cmd, ...h]); setHIdx(-1);

    const lower = cmd.toLowerCase();
    if (lower === "clear") { setLines([]); return; }
    if (lower.startsWith("echo ")) { push([echo, { type: "out", html: cmd.slice(5).replace(/</g, "&lt;") }]); return; }
    if (lower.startsWith("goto ")) {
      const t = lower.slice(5).trim(); const id = SECTIONS[t];
      if (id) { document.getElementById(id)?.scrollIntoView({ behavior: "smooth" }); push([echo, { type: "out", html: `scrolling to <span class="a">${t}</span> …` }]); }
      else push([echo, { type: "out", html: `<span class="err">goto: no such section: ${t}</span>` }]);
      return;
    }
    if (lower.startsWith("cd ")) { push([echo, { type: "out", html: `try <span class="a">goto ${lower.slice(3).trim()}</span> to navigate.` }]); return; }
    const fn = COMMANDS[lower];
    if (fn) { const r = fn(); push([echo, ...(Array.isArray(r) ? r : [])]); }
    else push([echo, { type: "out", html: `<span class="err">command not found: ${cmd.replace(/</g, "&lt;")}</span> — type <span class="a">help</span>` }]);
  };

  const onKey = (e) => {
    if (e.key === "Enter") { run(val); setVal(""); }
    else if (e.key === "ArrowUp") { e.preventDefault(); if (history.length) { const ni = Math.min(hIdx + 1, history.length - 1); setHIdx(ni); setVal(history[ni]); } }
    else if (e.key === "ArrowDown") { e.preventDefault(); const ni = Math.max(hIdx - 1, -1); setHIdx(ni); setVal(ni === -1 ? "" : history[ni]); }
    else if (e.key === "Tab") {
      e.preventDefault();
      const opts = ["help", "whoami", "about", "ls", "neofetch", "projects", "skills", "experience", "contact", "resume", "cat vault", "cat skills", "clear"];
      const m = opts.find((o) => o.startsWith(val.toLowerCase()));
      if (m) setVal(m);
    } else if (e.key === "l" && e.ctrlKey) { e.preventDefault(); setLines([]); }
  };

  return (
    <section className="section" id="terminal">
      <div className="wrap section-pad">
        <Reveal className="section-head">
          <div>
            <div className="kicker"><span className="idx">~</span> / LIVE SHELL</div>
            <h2 className="section-title" style={{ marginTop: 14 }}>Explore the <span className="accent">portfolio</span>.</h2>
          </div>
          <div className="mlabel">a real shell · type help</div>
        </Reveal>
        <Reveal className="terminal-wrap" onClick={() => inputRef.current?.focus()}>
          <div className="term-bar">
            <span className="tl"><i></i><i></i><i></i></span>
            <span className="tt">{prompt}: ~/portfolio — zsh</span>
            <span className="hint">↑↓ history · tab complete</span>
          </div>
          <div className="term-body" ref={bodyRef} onClick={() => inputRef.current?.focus()}>
            {lines.map((l, k) => (
              <div className={l.type === "cmd" ? "term-line cmd" : "term-out"} key={k} dangerouslySetInnerHTML={{ __html: l.html }}></div>
            ))}
            <div className="term-input-row">
              <span className="u" style={{ color: "var(--cyan)" }}>{prompt}</span><span className="p" style={{ color: "var(--accent)" }}>:~$</span>
              <input
                ref={inputRef}
                className="term-input"
                value={val}
                spellCheck={false}
                autoCapitalize="off"
                autoComplete="off"
                onChange={(e) => setVal(e.target.value)}
                onKeyDown={onKey}
                aria-label="terminal input"
              />
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

window.Terminal = Terminal;
