/* global React */
const { useState: useState_T, useRef: useRef_T, useEffect: useEffect_T } = React;

const FORTUNES = [
  "ship it. fix it on a branch nobody reads.",
  "the bug is in the place you swore you already checked.",
  "you have unread changelogs (412).",
  "tabs are a serving suggestion. spaces are a religion.",
  "today's git commit message: 'final final v2 (real)'",
  "your future self says: please add a README.",
  "rm -rf node_modules && npm i is a mood, not a fix.",
  "comments are love letters to your future, tireder self.",
];

const PROMPTS = {
  help: () => [
    "available commands:",
    "  whoami   \u2192 who is this person",
    "  skills   \u2192 what I can do",
    "  coffee   \u2192 brew a virtual cup",
    "  joke     \u2192 a dev joke (apologies in advance)",
    "  fortune  \u2192 a tiny prophecy",
    "  contact  \u2192 how to reach me",
    "  clear    \u2192 wipe the screen",
    "  sudo     \u2192 you wish",
  ],
  whoami: () => [
    "rahul \u00b7 chennai, IN \u00b7 full-stack + AI dev",
    "lvl 23 \u00b7 mostly harmless \u00b7 ships things on purpose",
  ],
  skills: () => [
    "frontend  : react, ts, tailwind, motion",
    "backend   : node, python, redis, mongo",
    "ml/native : pytorch, langchain, swift, docker",
    "vibes     : tabs(?), trailing commas(yes), oxford comma(yes)",
  ],
  coffee: () => [
    "          (  )   (   )  ) ",
    "           ) (   )  (  (",
    "           ( )  (    ) )",
    "         _____________",
    "        <_____________> ___",
    "        |             |/ _ \\",
    "        |               | | |",
    "        |               |_| |",
    "     ___|             |\\___/",
    "    /    \\___________/    \\",
    "    \\_____________________/",
    "",
    "+1 caffeine. -1 anxiety (temporarily).",
  ],
  joke: () => {
    const jokes = [
      "why do programmers prefer dark mode? because light attracts bugs.",
      "i told a UDP joke. you might not get it.",
      "there are 10 kinds of people: those who get binary and those who don't.",
      "i would tell you a concurrency joke but the punchline ar       rives first.",
      "css is great. it's just a typo away from chaos.",
    ];
    return [jokes[Math.floor(Math.random() * jokes.length)]];
  },
  fortune: () => [FORTUNES[Math.floor(Math.random() * FORTUNES.length)]],
  contact: () => [
    "email    \u2192 rahulnilvan43@gmail.com",
    "github   \u2192 github.com/therahul-yo",
    "linkedin \u2192 linkedin.com/in/rahul-t-rn56",
    "reply SLA: vibes (usually < 24h)",
  ],
  sudo: () => ["nope. you're not in the sudoers file. this incident will be reported."],
  ls: () => ["projects/  skills.txt  resume.pdf  .secrets/  todo.md"],
  cat: () => ["    /\\_/\\", "   ( o.o )", "    > ^ <"],
};

window.TerminalSection = function TerminalSection() {
  const [lines, setLines] = useState_T([
    { kind: 'sys', text: "rahul-os v4.0.4 \u00b7 type 'help' for commands" },
    { kind: 'sys', text: "" },
  ]);
  const [input, setInput] = useState_T("");
  const inputRef = useRef_T(null);
  const scrollRef = useRef_T(null);

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

  const run = (cmd) => {
    const c = cmd.trim().toLowerCase();
    const next = [...lines, { kind: 'in', text: c }];
    if (c === '') { setLines(next); return; }
    if (c === 'clear') { setLines([{ kind: 'sys', text: "screen wiped \u00b7 type 'help' to start over" }]); return; }
    const fn = PROMPTS[c.split(' ')[0]];
    if (fn) {
      fn().forEach(l => next.push({ kind: 'out', text: l }));
    } else {
      next.push({ kind: 'err', text: `command not found: ${c} \u2014 try 'help'` });
    }
    setLines(next);
  };

  const onKey = (e) => {
    if (e.key === 'Enter') { run(input); setInput(""); }
  };

  return (
    <section className="terminal-section">
      <div className="section-head">
        <div className="num">// 04</div>
        <h2>$ Play<br />the prompt<span className="swirl">type something. anything. seriously.</span></h2>
        <div className="meta">interactive \u00b7 keyboard-only</div>
      </div>

      <div className="terminal" onClick={() => inputRef.current?.focus()}>
        <div className="term-bar">
          <span className="dot r" /><span className="dot y" /><span className="dot g" />
          <span className="term-title">rahul@portfolio:~ \u2014 zsh</span>
          <span className="term-meta">80\u00d724</span>
        </div>
        <div className="term-body" ref={scrollRef}>
          {lines.map((l, i) => (
            <div key={i} className={`term-line term-${l.kind}`}>
              {l.kind === 'in' && <span className="term-prompt">$</span>}
              <pre>{l.text}</pre>
            </div>
          ))}
          <div className="term-line term-input-row">
            <span className="term-prompt">$</span>
            <span className="term-input-wrap">
              <span className="term-typed">
                {input || <span className="term-placeholder">try: help</span>}
              </span>
              <span className="cursor" />
              <input
                ref={inputRef}
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={onKey}
                spellCheck={false}
              />
            </span>
          </div>
        </div>
      </div>

      <div className="term-hint">
        try: <kbd>help</kbd> <kbd>whoami</kbd> <kbd>coffee</kbd> <kbd>joke</kbd> <kbd>fortune</kbd> <kbd>cat</kbd> <kbd>sudo</kbd>
      </div>
    </section>
  );
};

/* =========================================================
   KONAMI CODE EASTER EGG
========================================================= */
window.KonamiEgg = function KonamiEgg() {
  useEffect_T(() => {
    const seq = ['ArrowUp','ArrowUp','ArrowDown','ArrowDown','ArrowLeft','ArrowRight','ArrowLeft','ArrowRight','b','a'];
    let i = 0;
    const onKey = (e) => {
      const k = e.key.length === 1 ? e.key.toLowerCase() : e.key;
      if (k === seq[i]) {
        i++;
        if (i === seq.length) {
          document.body.classList.add('konami');
          // confetti shower
          for (let n = 0; n < 60; n++) {
            const c = document.createElement('div');
            c.className = 'confetti';
            c.style.left = Math.random() * 100 + 'vw';
            c.style.background = ['#d8ff3a','#ff5a3c','#5ec6ff','#ffd34a','#ff8fb0'][n % 5];
            c.style.animationDelay = (Math.random() * 0.8) + 's';
            c.style.transform = `rotate(${Math.random() * 360}deg)`;
            document.body.appendChild(c);
            setTimeout(() => c.remove(), 4500);
          }
          i = 0;
        }
      } else {
        i = 0;
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  return null;
};
