"use client";

import type { ReactNode } from "react";
import { useEffect, useState } from "react";

import { TooltipProvider } from "@/components/ui/tooltip";
import { RightPanel } from "@/components/panels/right-panel";
import { Sidebar } from "@/components/sidebar/sidebar";
import { CommandPalette } from "@/components/ai/command-palette";
import { SearchDialog } from "@/components/search";

export function AppShell({ children }: { children: ReactNode }) {
  const [searchOpen, setSearchOpen] = useState(false);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      const isSlash = e.key === "/" || e.code === "Slash";
      if (!isSlash || !(e.metaKey || e.ctrlKey)) return;
      const t = e.target as HTMLElement | null;
      if (t?.closest?.("[data-search-dialog-ignore-shortcut]")) return;
      e.preventDefault();
      setSearchOpen(true);
    };
    document.addEventListener("keydown", onKey, true);
    return () => document.removeEventListener("keydown", onKey, true);
  }, []);

  return (
    <TooltipProvider delayDuration={300}>
      <div className="flex h-[100dvh] w-full overflow-hidden bg-background">
        <Sidebar onOpenSearch={() => setSearchOpen(true)} />
        <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
          <main className="flex-1 overflow-auto">{children}</main>
        </div>
        <RightPanel />
      </div>
      <CommandPalette />
      <SearchDialog open={searchOpen} onOpenChange={setSearchOpen} />
    </TooltipProvider>
  );
}
