/* ============================================================
   TERMINAL 88 // interações
   ============================================================ */
(function () {
  "use strict";

  const prefersReduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

  /* ============================================================
     Boot sequence — type lines, then reveal the site
     ============================================================ */
  const boot = document.getElementById("boot");
  const bootLog = document.getElementById("bootLog");

  const BOOT_LINES = [
    "TERMINAL 88 BIOS v8.8 ......... OK",
    "initialising broth reactors ... OK",
    "mounting /menu ............... OK",
    "warming noodle cache ......... OK",
    "neon subsystems .............. ONLINE",
    "",
    "welcome, guest. tens fome? [Y/n] Y",
    "loading kitchen ..."
  ];

  async function runBoot() {
    if (prefersReduced || !boot || !bootLog) { finishBoot(); return; }
    for (const line of BOOT_LINES) {
      for (let i = 0; i <= line.length; i++) {
        bootLog.textContent = bootLog.textContent.replace(/█$/, "") + (i === 0 ? "" : line[i - 1]);
        bootLog.textContent += "█";
        await sleep(10);
        bootLog.textContent = bootLog.textContent.replace(/█$/, "");
      }
      bootLog.textContent += "\n";
      await sleep(90);
    }
    await sleep(450);
    finishBoot();
  }

  function finishBoot() {
    if (boot) boot.classList.add("is-done");
    document.body.classList.remove("is-loading");
    setTimeout(() => boot && boot.remove(), 600);
    typeHero();
  }

  window.addEventListener("load", runBoot);

  /* ---------- Hero command typewriter ---------- */
  async function typeHero() {
    const el = document.getElementById("heroCmd");
    if (!el) return;
    const text = "menu --all --hungry";
    if (prefersReduced) { el.textContent = text; return; }
    for (let i = 0; i < text.length; i++) {
      el.textContent += text[i];
      await sleep(55);
    }
  }

  /* ---------- Header state ---------- */
  const head = document.getElementById("head");
  const onScroll = () => head.classList.toggle("is-scrolled", window.scrollY > 30);
  onScroll();
  window.addEventListener("scroll", onScroll, { passive: true });

  /* ---------- Reveal windows ---------- */
  if ("IntersectionObserver" in window && !prefersReduced) {
    const io = new IntersectionObserver((entries, obs) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { e.target.classList.add("is-visible"); obs.unobserve(e.target); }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -6% 0px" });
    document.querySelectorAll(".win, .console").forEach((el) => io.observe(el));
  } else {
    document.querySelectorAll(".win, .console").forEach((el) => el.classList.add("is-visible"));
  }

  /* ============================================================
     Interactive console — a few playful commands
     ============================================================ */
  const cmd = document.getElementById("cmd");
  const out = document.getElementById("out");

  const RESPONSES = {
    help: "comandos: help · menu · especial · whoami · sobre · clear",
    menu: "ramen · sides · drinks — desliza para cima para ler o menu completo.",
    especial: "[PRATO SECRETO] mazesoba de trufa negra — só à meia-noite. pede ao balcão. 🍜",
    whoami: "guest · fome:MÁXIMA · mesa:88 · acesso:concedido",
    sobre: "Terminal 88 // cyber noodle bar. caldos a ferver desde 2088. aberto 18:00—03:00.",
    ls: "ramen.txt  sides.txt  drinks.txt  segredos/",
    "sudo": "nice try. o único root aqui é o gengibre. 🫚",
    coffee: "café? isto é um bar de ramen. mas tens matcha_cola no menu.",
  };

  if (cmd && out) {
    cmd.addEventListener("keydown", (e) => {
      if (e.key !== "Enter") return;
      const raw = cmd.value.trim();
      const key = raw.toLowerCase();
      cmd.value = "";
      if (!raw) return;

      if (key === "clear") { out.textContent = ""; return; }

      let reply = RESPONSES[key];
      if (!reply) reply = "comando desconhecido: '" + raw + "'  (tenta: help)";

      out.textContent += "guest@terminal88:~$ " + raw + "\n" + reply + "\n\n";
      out.scrollTop = out.scrollHeight;
    });
  }
})();
