const { useState: useStateT, useEffect: useEffectT, useRef: useRefT } = React;

const BANNER = [
  "rohan@folio:~$ whoami",
  "",
  " ____       _                  __        __",
  "|  _ \\ ___ | |__   __ _ _ __   \\ \\      / /",
  "| |_) / _ \\| '_ \\ / _` | '_ \\   \\ \\ /\\ / / ",
  "|  _ < (_) | | | | (_| | | | |   \\ V  V /  ",
  "|_| \\_\\___/|_| |_|\\__,_|_| |_|    \\_/\\_/   ",
  "",
  "type 'help' for commands.  esc to close.",
];

function Terminal({ onClose, data }) {
  const [lines, setLines] = useStateT(BANNER.map((l) => ({ kind: "out", text: l })));
  const [input, setInput] = useStateT("");
  const [history, setHistory] = useStateT([]);
  const [hIdx, setHIdx] = useStateT(-1);
  const inputRef = useRefT(null);
  const bodyRef = useRefT(null);

  useEffectT(() => { inputRef.current && inputRef.current.focus(); }, []);
  useEffectT(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [lines]);
  useEffectT(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [onClose]);

  const run = (raw) => {
    const cmd = raw.trim();
    const out = [{ kind: "user", text: `rohan@folio:~$ ${cmd}` }];
    if (!cmd) { setLines((l) => [...l, { kind: "user", text: "rohan@folio:~$" }]); return; }

    const [name, ...args] = cmd.split(/\s+/);
    switch (name) {
      case "help":
        out.push(
          { kind: "out", text: "available commands:" },
          { kind: "out", text: "  whoami     — who is this" },
          { kind: "out", text: "  skills     — print skill groups" },
          { kind: "out", text: "  projects   — list projects" },
          { kind: "out", text: "  cat <id>   — show project details (id: layoff-tracker, tb-detection, mcp-server, qlora-pipeline)" },
          { kind: "out", text: "  contact    — print contact info" },
          { kind: "out", text: "  theme      — toggle light/dark" },
          { kind: "out", text: "  clear      — clear screen" },
          { kind: "out", text: "  sudo       — ..." },
          { kind: "out", text: "  exit       — close terminal" },
        );
        break;
      case "whoami":
        out.push(
          { kind: "accent", text: `${data.profile.name} — ${data.profile.role}` },
          { kind: "out", text: data.profile.summary },
        );
        break;
      case "skills":
        data.skills.forEach((s) => {
          out.push({ kind: "accent", text: `# ${s.group}` });
          out.push({ kind: "out", text: "  " + s.items.join(", ") });
        });
        break;
      case "projects":
        data.projects.forEach((p, i) => {
          out.push({ kind: "out", text: `${String(i + 1).padStart(2, "0")}  ${p.id.padEnd(18)} ${p.title}` });
        });
        out.push({ kind: "out", text: "" });
        out.push({ kind: "out", text: "use: cat <id>" });
        break;
      case "cat": {
        const p = data.projects.find((x) => x.id === args[0]);
        if (!p) { out.push({ kind: "out", text: `cat: ${args[0] || "(no arg)"}: no such project` }); break; }
        out.push({ kind: "accent", text: `## ${p.title} (${p.year})` });
        out.push({ kind: "out", text: p.blurb });
        out.push({ kind: "out", text: "" });
        out.push({ kind: "accent", text: "// problem" });
        out.push({ kind: "out", text: p.details.problem });
        out.push({ kind: "out", text: "" });
        out.push({ kind: "accent", text: "// approach" });
        p.details.approach.forEach((a) => out.push({ kind: "out", text: "  - " + a }));
        out.push({ kind: "out", text: "" });
        out.push({ kind: "accent", text: "// outcomes" });
        p.details.outcomes.forEach((o) => out.push({ kind: "out", text: "  - " + o }));
        break;
      }
      case "contact":
        out.push(
          { kind: "out", text: `email:    ${data.profile.email}` },
          { kind: "out", text: `phone:    ${data.profile.phone}` },
          { kind: "out", text: `linkedin: linkedin.com${data.profile.linkedin}` },
          { kind: "out", text: `github:   github.com${data.profile.github}` },
        );
        break;
      case "theme": {
        const cur = document.documentElement.getAttribute("data-theme");
        const next = cur === "dark" ? "light" : "dark";
        document.documentElement.setAttribute("data-theme", next);
        try { localStorage.setItem("rohan.theme", next); } catch (_) {}
        out.push({ kind: "accent", text: `theme -> ${next}` });
        break;
      }
      case "clear":
        setLines([]);
        setInput("");
        setHistory((h) => [raw, ...h].slice(0, 50));
        setHIdx(-1);
        return;
      case "sudo":
        out.push({ kind: "out", text: "rohan is not in the sudoers file.  This incident will be reported." });
        break;
      case "ls":
        out.push({ kind: "out", text: "about/  experience/  projects/  contact/  .secret" });
        break;
      case "cat.secret":
      case "cat":
        break;
      case "exit":
        onClose();
        return;
      default:
        out.push({ kind: "out", text: `command not found: ${name}. try 'help'.` });
    }

    setLines((l) => [...l, ...out]);
    setHistory((h) => [raw, ...h].slice(0, 50));
    setHIdx(-1);
    setInput("");
  };

  const onKeyDown = (e) => {
    if (e.key === "Enter") { run(input); }
    else if (e.key === "ArrowUp") {
      e.preventDefault();
      const n = Math.min(history.length - 1, hIdx + 1);
      if (n >= 0 && history[n] != null) { setHIdx(n); setInput(history[n]); }
    } else if (e.key === "ArrowDown") {
      e.preventDefault();
      const n = hIdx - 1;
      if (n < 0) { setHIdx(-1); setInput(""); }
      else { setHIdx(n); setInput(history[n]); }
    }
  };

  return (
    <div className="term" onClick={() => inputRef.current && inputRef.current.focus()}>
      <div className="term-bar">
        <div className="term-dots">
          <div className="term-dot" /><div className="term-dot" /><div className="term-dot" />
        </div>
        <div className="term-title">rohan@folio — zsh — 80×24</div>
        <button className="term-close" onClick={onClose}>✕</button>
      </div>
      <div className="term-body" ref={bodyRef}>
        {lines.map((l, i) => (
          <div className={`term-line ${l.kind}`} key={i}>{l.text || "\u00A0"}</div>
        ))}
        <div className="term-input-row">
          <span className="prompt-arrow">rohan@folio:~$</span>
          <input
            ref={inputRef}
            className="term-input"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={onKeyDown}
            autoComplete="off"
            spellCheck="false"
          />
        </div>
      </div>
      <div className="term-hint">hint: type <b>help</b> · ↑/↓ history · esc to close</div>
    </div>
  );
}

Object.assign(window, { Terminal });
