"use client";

import { type ReactNode, useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { Menu } from "lucide-react";
import { Sidebar } from "@/components/layout/sidebar";
import { Topbar } from "@/components/layout/topbar";
import { MobileNav } from "@/components/layout/mobile-nav";
import { MobileSidebar } from "@/components/layout/mobile-sidebar";
import { CommandPalette } from "@/components/layout/command-palette";
import { FocusBar } from "@/components/focus/focus-bar";
import { FloatingTimer } from "@/components/timer/floating-timer";
import { triggerDueAutomations } from "@/lib/automations/run-due";
import { initSoundUnlock } from "@/lib/sounds";
import { triggerTaskCleanup } from "@/lib/tasks/cleanup";
import { useSmartNotifications } from "@/hooks/use-smart-notifications";
import { useUIStore } from "@/stores/ui-store";
import { useWorkspaceStore } from "@/stores/workspace-store";
import { useFocusStore } from "@/stores/focus-store";

interface AppShellProps {
  children: ReactNode;
  userName: string;
  userAvatar?: string | null;
  userUsername?: string | null;
  userEmail: string;
}

export function AppShell({
  children,
  userName,
  userAvatar,
  userUsername,
  userEmail,
}: AppShellProps) {
  const pathname = usePathname();
  const router = useRouter();
  const initWorkspace = useWorkspaceStore((state) => state.initWorkspace);
  const activeTeamId = useWorkspaceStore((state) => state.activeTeamId);
  const initialized = useWorkspaceStore((state) => state.initialized);
  const sidebarOpen = useUIStore((state) => state.sidebarOpen);
  const setSidebarOpen = useUIStore((state) => state.setSidebarOpen);
  const setCommandPaletteOpen = useUIStore((state) => state.setCommandPaletteOpen);
  const commandPaletteOpen = useUIStore((state) => state.commandPaletteOpen);
  const setFocusReturnPath = useFocusStore((state) => state.setFocusReturnPath);
  // A single note view gets the exact same distraction-free shell as
  // /focus — no sidebar/topbar chrome, just a floating nav toggle — so
  // writing a note actually feels like the only thing on screen. Matched by
  // UUID so it only catches a real note id, not /notes or /notes/marketplace.
  const isSingleNotePage = /^\/notes\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
    pathname
  );
  const isFocusPage = pathname.startsWith("/focus") || isSingleNotePage;

  useSmartNotifications();

  useEffect(() => {
    initWorkspace();
  }, [initWorkspace]);

  useEffect(() => {
    initSoundUnlock();
  }, []);

  useEffect(() => {
    if (!initialized) return;
    void triggerTaskCleanup(activeTeamId);
  }, [activeTeamId, initialized]);

  useEffect(() => {
    if (!initialized) return;

    void triggerDueAutomations(activeTeamId);
    const interval = window.setInterval(() => {
      void triggerDueAutomations(activeTeamId);
    }, 60 * 1000);

    return () => window.clearInterval(interval);
  }, [activeTeamId, initialized]);

  useEffect(() => {
    if (!isFocusPage) {
      setFocusReturnPath(pathname);
    }
  }, [isFocusPage, pathname, setFocusReturnPath]);

  // Auto-close the desktop overlay sidebar when leaving Focus (it's only
  // used there, see the isFocusPage branch below). Keyed on isFocusPage
  // alone — depending on sidebarOpen too would refire this on every
  // toggle, which fought the mobile "More" button since it shares the
  // same sidebarOpen state to open MobileSidebar on normal pages.
  useEffect(() => {
    if (!isFocusPage) {
      setSidebarOpen(false);
    }
  }, [isFocusPage, setSidebarOpen]);

  useEffect(() => {
    function isTypingTarget(target: EventTarget | null) {
      if (!(target instanceof HTMLElement)) return false;
      const tagName = target.tagName.toLowerCase();
      return (
        tagName === "input" ||
        tagName === "textarea" ||
        target.isContentEditable ||
        target.getAttribute("role") === "textbox"
      );
    }

    function handleKeyDown(event: KeyboardEvent) {
      if (isTypingTarget(event.target)) return;

      if (event.key === "/" && !event.metaKey && !event.ctrlKey && !event.altKey) {
        event.preventDefault();
        setCommandPaletteOpen(true);
        return;
      }

      if (commandPaletteOpen) return;

      if (event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey) {
        const key = event.key.toLowerCase();

        if (key === "t") {
          event.preventDefault();
          router.push("/tasks");
        } else if (key === "n") {
          event.preventDefault();
          router.push("/notes");
        } else if (key === "p") {
          event.preventDefault();
          router.push("/projects");
        } else if (key === "d") {
          event.preventDefault();
          router.push("/vault");
        } else if (key === "i") {
          event.preventDefault();
          router.push("/inbox");
        } else if (key === "f") {
          event.preventDefault();
          router.push("/focus");
        }
      }
    }

    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [
    commandPaletteOpen,
    router,
    setCommandPaletteOpen,
    setFocusReturnPath,
  ]);

  if (isFocusPage) {
    return (
      <div className="flex h-screen overflow-hidden bg-background text-foreground">
        <CommandPalette />
        <MobileSidebar />

        {sidebarOpen && (
          <div className="fixed inset-0 z-[9990] hidden md:block">
            <div
              className="absolute inset-0 bg-black/65 backdrop-blur-sm"
              onClick={() => setSidebarOpen(false)}
            />
            <div className="absolute inset-y-0 left-0 flex">
              <Sidebar />
            </div>
          </div>
        )}

        <div className="pointer-events-none fixed left-4 top-4 z-[10000]">
          <button
            onClick={() => setSidebarOpen(!sidebarOpen)}
            className="pointer-events-auto inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-white/[0.08] bg-[#111019]/86 text-white/65 shadow-[0_18px_50px_rgba(0,0,0,0.35)] backdrop-blur-xl transition-all hover:bg-[#181622] hover:text-white"
            title={sidebarOpen ? "Navigation schließen" : "Navigation öffnen"}
          >
            <Menu className="h-5 w-5" />
          </button>
        </div>

        <main className="flex-1 overflow-y-auto overscroll-contain">
          {children}
        </main>
      </div>
    );
  }

  return (
    <div className="flex h-screen overflow-hidden bg-background text-foreground">
      <Sidebar />
      <MobileSidebar />
      <CommandPalette />

      <div className="flex flex-1 flex-col min-w-0">
        <Topbar
          userName={userName}
          userAvatar={userAvatar}
          userUsername={userUsername}
          userEmail={userEmail}
        />

        {/* Focus bar sits between topbar and content — shifts content down naturally */}
        <FocusBar />

        <main className="flex-1 overflow-y-auto overscroll-contain px-5 py-5 pb-24 sm:px-6 sm:py-6 md:px-8 md:py-8 md:pb-8 xl:px-12 xl:py-10 2xl:px-16">
          <div className="mx-auto w-full max-w-[1680px]">
            {children}
          </div>
        </main>
      </div>

      <MobileNav />
      <FloatingTimer />
    </div>
  );
}
