"use client";

import { useState, useEffect } from "react";
import { usePathname } from "next/navigation";
import { Authenticated } from "convex/react";
import { QuickSwitcher } from "./QuickSwitcher";
import { Id } from "@/convex/_generated/dataModel";

/**
 * Global QuickSwitcher wrapper that:
 * - Shows on all authenticated pages
 * - Handles Cmd+K / Ctrl+K keyboard shortcut globally
 * - Extracts current spaceId from URL when on a space page
 */
export function GlobalQuickSwitcher() {
  const [isOpen, setIsOpen] = useState(false);
  const pathname = usePathname();

  // Extract spaceId from URL if we're on a space page
  const currentSpaceId = pathname?.startsWith("/space/")
    ? (pathname.split("/")[2]?.split("?")[0] as Id<"spaces"> | undefined)
    : undefined;

  // Handle Cmd+K / Ctrl+K globally
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        setIsOpen(true);
      }
    };

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

  return (
    <Authenticated>
      <QuickSwitcher
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
        currentSpaceId={currentSpaceId}
      />
    </Authenticated>
  );
}
