"use client";

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

const routes: Record<string, string> = {
  about: "/About",
  learning: "/Learning",
  selfhosted: "/SelfHosted",
  home: "/",
};

export default function CdNavigation() {
  const router = useRouter();
  const bufferRef = useRef("");
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      const tag = (e.target as HTMLElement).tagName;
      if (tag === "INPUT" || tag === "TEXTAREA") return;

      bufferRef.current += e.key;

      if (timerRef.current) clearTimeout(timerRef.current);
      timerRef.current = setTimeout(() => {
        bufferRef.current = "";
      }, 1500);

      const match = bufferRef.current.match(/cd\s+(\S+)$/i);
      if (match) {
        const dest = routes[match[1].toLowerCase()];
        if (dest) {
          bufferRef.current = "";
          router.push(dest);
        }
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [router]);

  return null;
}
