// terminal.jsx — interactive terminal with command parser, history, suggestions

const { useState: useTState, useEffect: useETerm, useRef: useRTerm, useCallback: useCTerm } = React;

function Terminal({ state, setState, onEvents, suggestion, onCommand }) {
  const [input, setInput] = useTState("");
  const [history, setHistory] = useTState([
    { kind: "system", text: "git playground v1.0 — type 'help' for commands" },
  ]);
  const [pastCommands, setPast] = useTState([]);
  const [pastIdx, setPastIdx] = useTState(-1);
  const inputRef = useRTerm(null);
  const scrollRef = useRTerm(null);

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

  const focus = () => inputRef.current?.focus();

  const submit = (cmd) => {
    const text = (cmd ?? input).trim();
    if (!text) return;
    setHistory(h => [...h, { kind: "cmd", text }]);
    setPast(p => [...p, text]);
    setPastIdx(-1);
    setInput("");

    const { state: newState, events } = runAny(state, text);
    setState(newState);

    const newLines = [];
    let clearReq = false;
    for (const e of events) {
      if (e.type === "clear") { clearReq = true; continue; }
      if (e.type === "log") newLines.push({ kind: "log", text: e.text });
      if (e.type === "ok") newLines.push({ kind: "ok", text: e.text });
      if (e.type === "err") newLines.push({ kind: "err", text: e.text });
    }
    if (clearReq) {
      setHistory([{ kind: "system", text: "(cleared)" }]);
    } else {
      setHistory(h => [...h, ...newLines]);
    }
    if (onEvents) onEvents(events, text);
    if (onCommand) onCommand(text);
  };

  const onKey = (e) => {
    if (e.key === "Enter") {
      e.preventDefault();
      submit();
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      if (pastCommands.length === 0) return;
      const newIdx = pastIdx === -1 ? pastCommands.length - 1 : Math.max(0, pastIdx - 1);
      setPastIdx(newIdx);
      setInput(pastCommands[newIdx] || "");
    } else if (e.key === "ArrowDown") {
      e.preventDefault();
      if (pastIdx === -1) return;
      const newIdx = pastIdx + 1;
      if (newIdx >= pastCommands.length) {
        setPastIdx(-1);
        setInput("");
      } else {
        setPastIdx(newIdx);
        setInput(pastCommands[newIdx]);
      }
    } else if (e.key === "Tab") {
      e.preventDefault();
      if (suggestion) setInput(suggestion);
    }
  };

  const lineColor = (kind) => ({
    cmd: "#FFD93D",
    ok: "#7FE07F",
    err: "#FF7676",
    log: "#E0E0E0",
    system: "#9090A0",
  }[kind] || "#E0E0E0");

  return (
    <div onClick={focus} className="panel panel-lg" style={{
      background: "#1A1410",
      color: "#E0E0E0",
      border: "3px solid var(--ink)",
      borderRadius: 14,
      display: "flex",
      flexDirection: "column",
      overflow: "hidden",
      cursor: "text",
      minHeight: 0,
      width: "100%",
      height: "100%",
      flex: 1,
    }}>
      {/* terminal title bar */}
      <div style={{
        background: "#2A2018",
        padding: "8px 14px",
        borderBottom: "2px solid var(--ink)",
        display: "flex", alignItems: "center", gap: 10,
        flexShrink: 0,
      }}>
        <div style={{ display: "flex", gap: 6 }}>
          <div style={{ width: 11, height: 11, borderRadius: "50%", background: "#FF6B6B", border: "1px solid #4a2a2a" }} />
          <div style={{ width: 11, height: 11, borderRadius: "50%", background: "#FFD93D", border: "1px solid #4a4520" }} />
          <div style={{ width: 11, height: 11, borderRadius: "50%", background: "#7FE07F", border: "1px solid #2a4a2a" }} />
        </div>
        <div className="mono" style={{ fontSize: 11, color: "#999", flex: 1, textAlign: "center" }}>
          ~/{state.initialized ? "git-project" : "your-folder"}{state.initialized ? ` (${state.HEAD})` : ""}
        </div>
        <div className="mono" style={{ fontSize: 10, color: "#666" }}>terminal</div>
      </div>

      {/* scrollback */}
      <div ref={scrollRef} className="mono" style={{
        flex: 1,
        padding: "10px 14px",
        overflowY: "auto",
        fontSize: 13,
        lineHeight: 1.5,
        minHeight: 0,
      }}>
        {history.map((line, i) => (
          <div key={i} style={{ color: lineColor(line.kind), whiteSpace: "pre-wrap" }}>
            {line.kind === "cmd" ? <span style={{ color: "#7FE07F" }}>$ </span> : null}
            {line.text}
          </div>
        ))}
      </div>

      {/* input */}
      <div style={{
        padding: "10px 14px",
        borderTop: "1px solid #3a302a",
        display: "flex",
        alignItems: "center",
        gap: 8,
        flexShrink: 0,
      }}>
        <span className="mono" style={{ color: "#7FE07F", fontSize: 14, fontWeight: 700 }}>$</span>
        <input
          ref={inputRef}
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={onKey}
          autoFocus
          spellCheck={false}
          className="mono"
          style={{
            flex: 1,
            background: "transparent",
            border: "none",
            outline: "none",
            color: "#FFD93D",
            fontSize: 14,
            fontFamily: "JetBrains Mono, monospace",
            caretColor: "#FFD93D",
          }}
          placeholder={suggestion ? `try: ${suggestion}  (press Tab)` : "type a command and press Enter"}
        />
        {suggestion && (
          <button
            className="btn"
            onClick={(e) => { e.stopPropagation(); setInput(suggestion); inputRef.current?.focus(); }}
            style={{ fontSize: 11, padding: "4px 10px", background: "var(--joy)" }}
          >
            ⇥ hint
          </button>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Terminal });
