/* ============================================================
   <KeyboardEggs /> — five keyboard-combo Easter eggs.

   1.  Type "INNOVEEV"  → brand burst + confetti
   2.  ?                → keyboard shortcut cheat sheet
   3.  /                → spotlight search overlay
   4.  G then X         → Vim-style page jump (b/a/p/c/h/r/f)
   5.  T three times    → cycle theme (light ↔ dark)

   Skips firing when the focused element is a text input.
   ============================================================ */

const PAGES = [
  { key: "h", label: "Home",       href: "index.html",   hint: "Studio overview" },
  { key: "a", label: "Apps",       href: "apps.html",    hint: "Product showcase" },
  { key: "b", label: "Blog",       href: "blog.html",    hint: "Field notes" },
  { key: "p", label: "Pricing",    href: "pricing.html", hint: "Tiers + estimator" },
  { key: "c", label: "Contact",    href: "contact.html", hint: "Talk to the studio" },
  { key: "o", label: "About",      href: "about.html",   hint: "Team + values" },
  { key: "r", label: "Process",    href: "process.html", hint: "How we work" },
  { key: "f", label: "FAQ",        href: "faq.html",     hint: "Answers" },
  { key: "k", label: "Careers",    href: "careers.html", hint: "Open roles" },
];

const SHORTCUTS = [
  { keys: ["?"],                       label: "Open this cheat sheet" },
  { keys: ["/"],                       label: "Spotlight — jump anywhere" },
  { keys: ["G", "→"],                  label: "Vim-style nav (G A = apps, G B = blog, G C = contact…)" },
  { keys: ["T", "T", "T"],             label: "Cycle theme (light ↔ dark)" },
  { keys: ["I","N","N","O","V","E","E","V"], label: "(Try it.)" },
  { keys: ["↑","↑","↓","↓","←","→","←","→","B","A"], label: "(Try it too.)" },
  { keys: ["Esc"],                     label: "Close this / cancel" },
];

function KeyboardEggs() {
  const [cheatOpen,    setCheatOpen]    = React.useState(false);
  const [spotOpen,     setSpotOpen]     = React.useState(false);
  const [innoveevHit,  setInnoveevHit]  = React.useState(false);

  const gPendingRef = React.useRef(false);
  const gTimerRef   = React.useRef(null);
  const tBufferRef  = React.useRef([]);
  const innoBufRef  = React.useRef("");

  // ----- Spotlight state -----
  const [spotQuery, setSpotQuery] = React.useState("");
  const [spotIdx,   setSpotIdx]   = React.useState(0);
  const spotInputRef = React.useRef(null);

  const ITEMS = PAGES;
  const filteredItems = React.useMemo(() => {
    const q = spotQuery.trim().toLowerCase();
    if (!q) return ITEMS;
    return ITEMS.filter((it) =>
      it.label.toLowerCase().includes(q) ||
      it.hint.toLowerCase().includes(q) ||
      it.href.toLowerCase().includes(q)
    );
  }, [spotQuery]);

  React.useEffect(() => {
    if (!spotOpen) { setSpotQuery(""); setSpotIdx(0); return; }
    setTimeout(() => spotInputRef.current?.focus(), 60);
  }, [spotOpen]);

  React.useEffect(() => { setSpotIdx(0); }, [spotQuery]);

  React.useEffect(() => {
    const onKey = (e) => {
      const tag = e.target?.tagName;
      const inField =
        tag === "INPUT" || tag === "TEXTAREA" || e.target?.isContentEditable;

      // Esc closes any overlay (always wins)
      if (e.key === "Escape") {
        if (cheatOpen) { setCheatOpen(false); e.preventDefault(); return; }
        if (spotOpen)  { setSpotOpen(false);  e.preventDefault(); return; }
      }

      // Don't fire combos while typing in a field — EXCEPT inside the
      // spotlight input, where we still need arrow keys + enter.
      if (inField && !spotOpen) return;

      // Spotlight nav keys
      if (spotOpen) {
        if (e.key === "ArrowDown") {
          e.preventDefault();
          setSpotIdx((i) => Math.min(filteredItems.length - 1, i + 1));
        } else if (e.key === "ArrowUp") {
          e.preventDefault();
          setSpotIdx((i) => Math.max(0, i - 1));
        } else if (e.key === "Enter") {
          e.preventDefault();
          const target = filteredItems[spotIdx];
          if (target) window.location.href = target.href;
        }
        return;
      }

      // 1. "?" — cheat sheet
      if (e.key === "?") {
        setCheatOpen((o) => !o);
        return;
      }

      // 2. "/" — spotlight
      if (e.key === "/") {
        e.preventDefault();
        setSpotOpen(true);
        return;
      }

      const k = e.key.length === 1 ? e.key.toLowerCase() : e.key;

      // 3. Vim G + X
      if (gPendingRef.current && k.length === 1) {
        const dest = PAGES.find((p) => p.key === k);
        gPendingRef.current = false;
        clearTimeout(gTimerRef.current);
        if (dest) {
          e.preventDefault();
          window.location.href = dest.href;
          return;
        }
      }
      if (k === "g" && !gPendingRef.current) {
        gPendingRef.current = true;
        clearTimeout(gTimerRef.current);
        gTimerRef.current = setTimeout(() => { gPendingRef.current = false; }, 900);
      }

      // 4. T three times within 800ms — theme cycle
      if (k === "t") {
        const now = performance.now();
        tBufferRef.current = [...tBufferRef.current, now].filter((ts) => now - ts < 800);
        if (tBufferRef.current.length >= 3) {
          tBufferRef.current = [];
          const cur = document.documentElement.getAttribute("data-theme") || "light";
          const next = cur === "dark" ? "light" : "dark";
          document.documentElement.setAttribute("data-theme", next);
          // Persist if the Tweaks system is around
          try {
            window.parent?.postMessage?.(
              { type: "__edit_mode_set_keys", edits: { theme: next } },
              "*"
            );
          } catch {}
          showToast(`Theme · ${next}`);
        }
      }

      // 5. Type "INNOVEEV"
      if (/^[a-z]$/.test(k)) {
        innoBufRef.current = (innoBufRef.current + k).slice(-9);
        if (innoBufRef.current.endsWith("innoveev")) {
          innoBufRef.current = "";
          setInnoveevHit(true);
          setTimeout(() => setInnoveevHit(false), 3200);
        }
      }
    };

    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [cheatOpen, spotOpen, filteredItems, spotIdx]);

  return (
    <>
      {/* Cheat sheet */}
      {cheatOpen && (
        <div className="kbd-modal" role="dialog" aria-modal="true" aria-label="Keyboard shortcuts">
          <div className="kbd-modal__backdrop" onClick={() => setCheatOpen(false)}></div>
          <div className="kbd-modal__card">
            <button
              type="button"
              className="kbd-modal__close"
              onClick={() => setCheatOpen(false)}
              aria-label="Close"
            >
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
              </svg>
            </button>
            <span className="kbd-modal__eyebrow">Keyboard · Cheat sheet</span>
            <h2 className="kbd-modal__title">Shortcuts</h2>
            <p className="kbd-modal__lede">Things the engineers in the studio use. A few are easter eggs — find them.</p>
            <ul className="kbd-list">
              {SHORTCUTS.map((s, i) => (
                <li key={i} className="kbd-list__row">
                  <span className="kbd-list__keys">
                    {s.keys.map((k, j) => (
                      <React.Fragment key={j}>
                        <kbd className="kbd-key">{k}</kbd>
                        {j < s.keys.length - 1 ? <span className="kbd-then">then</span> : null}
                      </React.Fragment>
                    ))}
                  </span>
                  <span className="kbd-list__label">{s.label}</span>
                </li>
              ))}
            </ul>
            <div className="spotlight__foot kbd-modal__foot--row">
              <span><kbd className="kbd-key kbd-key--mini">↑</kbd><kbd className="kbd-key kbd-key--mini">↓</kbd> Navigate</span>
              <span><kbd className="kbd-key kbd-key--mini">↵</kbd> Open</span>
              <span><kbd className="kbd-key kbd-key--mini">Esc</kbd> Close</span>
            </div>
          </div>
        </div>
      )}

      {/* Spotlight */}
      {spotOpen && (
        <div className="spotlight" role="dialog" aria-modal="true" aria-label="Spotlight search">
          <div className="spotlight__backdrop" onClick={() => setSpotOpen(false)}></div>
          <div className="spotlight__card">
            <div className="spotlight__input-wrap">
              <svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true">
                <circle cx="9" cy="9" r="6" stroke="currentColor" strokeWidth="1.6"/>
                <path d="m17 17-3.5-3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
              </svg>
              <input
                ref={spotInputRef}
                type="text"
                className="spotlight__input"
                placeholder="Jump anywhere — pages, sections…"
                value={spotQuery}
                onChange={(e) => setSpotQuery(e.target.value)}
              />
              <kbd className="kbd-key kbd-key--mini">Esc</kbd>
            </div>
            {filteredItems.length === 0 ? (
              <div className="spotlight__empty">No matches.</div>
            ) : (
              <ul className="spotlight__list">
                {filteredItems.map((it, i) => (
                  <li key={it.key}>
                    <a
                      href={it.href}
                      className={`spotlight__row ${i === spotIdx ? "is-active" : ""}`}
                      onMouseEnter={() => setSpotIdx(i)}
                    >
                      <span className="spotlight__row-key">G·{it.key.toUpperCase()}</span>
                      <span className="spotlight__row-label">{it.label}</span>
                      <span className="spotlight__row-hint">{it.hint}</span>
                      <span className="spotlight__row-chev" aria-hidden="true">↵</span>
                    </a>
                  </li>
                ))}
              </ul>
            )}
            <div className="spotlight__foot">
              <span><kbd className="kbd-key kbd-key--mini">↑</kbd><kbd className="kbd-key kbd-key--mini">↓</kbd> Navigate</span>
              <span><kbd className="kbd-key kbd-key--mini">↵</kbd> Open</span>
              <span><kbd className="kbd-key kbd-key--mini">?</kbd> Shortcuts</span>
            </div>
          </div>
        </div>
      )}

      {/* INNOVEEV brand burst */}
      {innoveevHit && (
        <div className="inno-burst" aria-hidden="true">
          <div className="inno-burst__brand">
            <span className="brand-mark"></span>
            <span className="inno-burst__word">INNOVEEV</span>
          </div>
          <div className="inno-burst__confetti">
            {Array.from({ length: 32 }).map((_, i) => (
              <span
                key={i}
                className="inno-burst__bit"
                style={{
                  "--x": `${(Math.random() * 100).toFixed(1)}%`,
                  "--dur": `${(1.4 + Math.random() * 1.4).toFixed(2)}s`,
                  "--delay": `${(Math.random() * 0.5).toFixed(2)}s`,
                  "--rot": `${Math.floor(Math.random() * 720)}deg`,
                  "--hue": Math.floor(Math.random() * 360),
                }}
              ></span>
            ))}
          </div>
        </div>
      )}
    </>
  );
}

// ----- Lightweight toast (theme cycle, etc.) -----
function showToast(text) {
  const el = document.createElement("div");
  el.className = "kbd-toast";
  el.textContent = text;
  document.body.appendChild(el);
  setTimeout(() => el.remove(), 1700);
}

window.KeyboardEggs = KeyboardEggs;
