"use client";

import * as React from "react";
import { cn } from "@/lib/utils";
import { TopBar } from "@/components/layout/top-bar";
import { Sidebar, SidebarProvider, useSidebar } from "@/components/layout/sidebar";
import { EmailVerificationBanner } from "@/components/layout/email-verification-banner";
import { CommandPalette } from "@/components/command-palette";
import { UploadModal } from "@/components/cards/upload-modal";
import { ContactSupportDialog } from "@/components/support/contact-support-dialog";

function ShellContent({ children }: { children: React.ReactNode }) {
  const { collapsed } = useSidebar();
  const [uploadOpen, setUploadOpen] = React.useState(false);
  const [uploadFiles, setUploadFiles] = React.useState<File[]>([]);

  React.useEffect(() => {
    function handleOpenUpload(e: Event) {
      const detail = (e as CustomEvent).detail;
      if (detail?.files) setUploadFiles(detail.files);
      setUploadOpen(true);
    }
    window.addEventListener("open-upload-modal", handleOpenUpload);
    return () => window.removeEventListener("open-upload-modal", handleOpenUpload);
  }, []);

  return (
    <div className="relative min-h-screen">
      <a
        href="#main-content"
        className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:left-4 focus:z-[100] focus:rounded-lg focus:bg-background focus:px-4 focus:py-2 focus:text-foreground focus:shadow-lg focus:ring-2 focus:ring-primary"
      >
        Skip to main content
      </a>
      <div className="gradient-mesh pointer-events-none fixed inset-0 z-0" />
      <TopBar />
      <Sidebar />
      <CommandPalette />
      <UploadModal
        open={uploadOpen}
        onOpenChange={setUploadOpen}
        initialFiles={uploadFiles.length > 0 ? uploadFiles : undefined}
      />
      <ContactSupportDialog />
      <main
        id="main-content"
        className={cn(
          "relative z-0 pt-16 transition-[margin-left] duration-200 ease-in-out",
          collapsed ? "ml-16" : "ml-60"
        )}
      >
        <div className="p-4 sm:p-6 lg:p-8">
          <EmailVerificationBanner />
          {children}
        </div>
      </main>
    </div>
  );
}

export function AppShell({ children }: { children: React.ReactNode }) {
  return (
    <SidebarProvider>
      <ShellContent>{children}</ShellContent>
    </SidebarProvider>
  );
}
