/* ============================================================
   COMMAND PALETTE — persistent top input for /navigation
   ============================================================ */

const COMMANDS = [
  { cmd: "/help",        desc: "show this list" },
  { cmd: "/hero",        desc: "jump to intro", target: "hero" },
  { cmd: "/experience",  desc: "work history", target: "experience" },
  { cmd: "/projects",    desc: "selected projects", target: "projects" },
  { cmd: "/tech",        desc: "stack & tooling", target: "tech" },
  { cmd: "/languages",   desc: "spoken languages", target: "languages" },
  { cmd: "/education",   desc: "degrees", target: "education" },
  { cmd: "/contact",     desc: "how to reach me", target: "contact" },
  { cmd: "/theme",       desc: "toggle dark / light" },
  { cmd: "/clear",       desc: "clear output" },
];

function scrollToLabel(label) {
  const el = document.querySelector(`[data-screen-label="${label}"]`);
  if (el) {
    const y = el.getBoundingClientRect().top + window.scrollY - 80;
    window.scrollTo({ top: y, behavior: "smooth" });
    return true;
  }
  return false;
}

function Cmdline() {
  const [value, setValue] = useState("");
  const [focus, setFocus] = useState(false);
  const [output, setOutput] = useState(null); // {kind, content}
  const inputRef = useRef(null);

  // global shortcut: "/" focuses the input
  useEffect(() => {
    const h = (e) => {
      if (e.key === "/" && document.activeElement?.tagName !== "INPUT") {
        e.preventDefault();
        inputRef.current?.focus();
      }
      if (e.key === "Escape") {
        inputRef.current?.blur();
        setOutput(null);
      }
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);

  // suggestions (filtered commands)
  const suggestions = useMemo(() => {
    if (!value) return [];
    const q = value.toLowerCase();
    return COMMANDS.filter(c => c.cmd.startsWith(q)).slice(0, 6);
  }, [value]);

  const run = (raw) => {
    const input = raw.trim().toLowerCase();
    if (!input) return;
    if (input === "/help") {
      setOutput({ kind: "help", content: COMMANDS });
      return;
    }
    if (input === "/theme") {
      const body = document.body;
      const next = body.classList.contains("theme-dark") ? "light" : "dark";
      body.classList.remove("theme-dark", "theme-light");
      body.classList.add(`theme-${next}`);
      window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { theme: next } }, "*");
      setOutput({ kind: "ok", content: `theme → ${next}` });
      return;
    }
    if (input === "/clear") { setOutput(null); return; }
    // scroll to section
    const cmd = COMMANDS.find(c => c.cmd === input);
    if (cmd && cmd.target) {
      if (scrollToLabel(cmd.target)) {
        setOutput({ kind: "ok", content: `→ scrolled to ${cmd.target}` });
        // auto-clear the success line
        setTimeout(() => setOutput(o => (o && o.content?.toString().startsWith("→") ? null : o)), 1600);
        return;
      }
    }
    // fallback: try raw label
    const bare = input.replace(/^\//, "");
    if (scrollToLabel(bare)) {
      setOutput({ kind: "ok", content: `→ scrolled to ${bare}` });
      setTimeout(() => setOutput(o => (o && o.content?.toString().startsWith("→") ? null : o)), 1600);
      return;
    }
    setOutput({ kind: "err", content: `command not found: ${input}. try /help` });
  };

  const onSubmit = (e) => {
    e.preventDefault();
    run(value);
    setValue("");
  };

  const pickSuggestion = (s) => {
    setValue("");
    run(s.cmd);
    inputRef.current?.focus();
  };

  // rotating placeholder — cycles through commands when idle
  const rotatingOptions = useMemo(
    () => COMMANDS.filter(c => c.cmd !== "/clear").map(c => c.cmd),
    []
  );
  const [rotIdx, setRotIdx] = useState(0);
  const [placeholder, setPlaceholder] = useState("");
  useEffect(() => {
    // don't animate when user is typing or focused
    if (focus || value) { setPlaceholder(""); return; }
    let cancelled = false;
    const target = "type " + rotatingOptions[rotIdx] + " and press enter";
    let i = 0;
    setPlaceholder("");
    const typeNext = () => {
      if (cancelled) return;
      if (i <= target.length) {
        setPlaceholder(target.slice(0, i));
        i++;
        setTimeout(typeNext, 40);
      } else {
        // hold, then rotate
        setTimeout(() => {
          if (!cancelled) setRotIdx((n) => (n + 1) % rotatingOptions.length);
        }, 1800);
      }
    };
    typeNext();
    return () => { cancelled = true; };
  }, [rotIdx, focus, value, rotatingOptions]);

  return (
    <div className="cmdline-wrap">
      <form className={"cmdline " + (focus ? "focus" : "")} onSubmit={onSubmit}>
        <span className="cmd-prompt"><span className="cu">yzenned</span><span className="sy">@</span><span className="ho">portfolio</span><span className="sy">:~$</span></span>
        <span className="cmd-input-wrap">
          {!value && !focus && placeholder && (
            <span className="cmd-ghost" aria-hidden="true">{placeholder}<span className="cmd-ghost-caret">▋</span></span>
          )}
          <input
            ref={inputRef}
            className="cmd-input"
            type="text"
            spellCheck="false"
            autoComplete="off"
            autoCorrect="off"
            autoCapitalize="off"
            value={value}
            onChange={(e) => setValue(e.target.value)}
            onFocus={() => setFocus(true)}
            onBlur={() => setTimeout(() => setFocus(false), 140)}
            onKeyDown={(e) => {
              if (e.key === "Tab" && suggestions[0]) {
                e.preventDefault();
                setValue(suggestions[0].cmd);
              }
            }}
          />
        </span>
        <span className="cmd-hint">{focus ? "enter ↵" : "/"}</span>
      </form>

      {focus && suggestions.length > 0 && (
        <div className="cmd-sugg">
          {suggestions.map((s, i) => (
            <div
              key={s.cmd}
              className="cmd-sugg-row"
              onMouseDown={() => pickSuggestion(s)}
            >
              <span className="c">{s.cmd}</span>
              <span className="d">{s.desc}</span>
            </div>
          ))}
        </div>
      )}

      {output && (
        <div className={"cmd-output " + output.kind}>
          {output.kind === "help" ? (
            <>
              <div className="out-head">// available commands</div>
              <div className="out-grid">
                {output.content.map(c => (
                  <div key={c.cmd} className="out-row" onClick={() => run(c.cmd)}>
                    <span className="c">{c.cmd}</span>
                    <span className="d">{c.desc}</span>
                  </div>
                ))}
              </div>
              <div className="out-foot">tip: press <kbd>/</kbd> anywhere to focus · <kbd>tab</kbd> to autocomplete · <kbd>esc</kbd> to close</div>
            </>
          ) : (
            <span>{output.content}</span>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Cmdline, scrollToLabel });
