"use client";

import { useEffect, useRef, useState, useCallback } from "react";
import { useRouter } from "next/navigation";

// R14 A.3: chord-style navigation shortcuts (g h, g m, g n, g d, g s).
// Press g, then within 1 second press h/m/n/d/s to navigate. Single-key
// shortcuts (/, Esc, ?) keep their existing behavior.
const CHORD_TARGETS: Record<string, string> = {
  h: "/",
  m: "/messages",
  n: "/notifications",
  d: "/dashboard",
  s: "/search",
};

const CHORD_LABELS: { combo: string; desc: string }[] = [
  { combo: "g h", desc: "Go to home" },
  { combo: "g m", desc: "Go to messages" },
  { combo: "g n", desc: "Go to notifications" },
  { combo: "g d", desc: "Go to dashboard" },
  { combo: "g s", desc: "Go to search" },
];

export default function KeyboardShortcuts() {
  const [showHelp, setShowHelp] = useState(false);
  const router = useRouter();
  // Tracks whether the user pressed `g` within the last 1 second; the next
  // letter pressed completes the chord. Reset on timeout, key Escape, or
  // any unrelated key.
  const gPressedRef = useRef(false);
  const gTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const clearChord = useCallback(() => {
    gPressedRef.current = false;
    if (gTimerRef.current) {
      clearTimeout(gTimerRef.current);
      gTimerRef.current = null;
    }
  }, []);

  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      // Ignore if user is typing in an input
      const tag = (e.target as HTMLElement)?.tagName;
      if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
        if (e.key === "Escape") {
          (e.target as HTMLElement).blur();
        }
        return;
      }

      // Chord completion: if we're waiting for the second key after `g`, see
      // if this is a known target letter.
      if (gPressedRef.current) {
        const target = CHORD_TARGETS[e.key.toLowerCase()];
        clearChord();
        if (target) {
          e.preventDefault();
          router.push(target);
          return;
        }
        // Unknown second key — fall through so single-key shortcuts still work.
      }

      // First leg of the chord — only arm if no modifiers are held.
      if (e.key === "g" && !e.metaKey && !e.ctrlKey && !e.altKey) {
        gPressedRef.current = true;
        gTimerRef.current = setTimeout(clearChord, 1000);
        return;
      }

      if (e.key === "/") {
        e.preventDefault();
        // Focus the sticky search input, or the hero search, or the nav search
        const searchInput =
          document.getElementById("sticky-search-input") ||
          document.querySelector<HTMLInputElement>('input[type="search"]') ||
          document.querySelector<HTMLInputElement>('input[placeholder*="Search"]') ||
          document.querySelector<HTMLInputElement>('input[placeholder*="search"]');
        if (searchInput) {
          searchInput.focus();
          if ('select' in searchInput) (searchInput as HTMLInputElement).select();
        }
      }

      if (e.key === "Escape") {
        clearChord();
        // Close any open modal/dialog
        const closeBtn = document.querySelector<HTMLButtonElement>(
          '[data-dialog-close], [aria-label="Close"], dialog[open] button'
        );
        if (closeBtn) {
          closeBtn.click();
        }
        setShowHelp(false);
      }

      if (e.key === "?") {
        e.preventDefault();
        setShowHelp((prev) => !prev);
      }
    },
    [router, clearChord]
  );

  useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
      if (gTimerRef.current) clearTimeout(gTimerRef.current);
    };
  }, [handleKeyDown]);

  return (
    <>
      {/* Help modal */}
      {showHelp && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm">
          <div className="bg-surface border border-surface-light rounded-xl shadow-elevated p-6 max-w-sm w-full mx-4">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-white">Keyboard Shortcuts</h3>
              <button
                onClick={() => setShowHelp(false)}
                className="text-text-muted hover:text-white transition-colors"
                data-dialog-close
                aria-label="Close shortcuts"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div className="space-y-3">
              {[
                { key: "/", desc: "Focus search bar" },
                { key: "Esc", desc: "Close modal / unfocus" },
                { key: "?", desc: "Toggle this help" },
                ...CHORD_LABELS.map((c) => ({ key: c.combo, desc: c.desc })),
              ].map((shortcut) => (
                <div key={shortcut.key} className="flex items-center justify-between">
                  <span className="text-sm text-text-muted">{shortcut.desc}</span>
                  <kbd className="bg-surface-light text-white px-2 py-0.5 rounded text-xs font-mono border border-white/10">
                    {shortcut.key}
                  </kbd>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </>
  );
}
