"use client";

import dynamic from "next/dynamic";

import { AiRemoveBgModal } from "@/components/image-editor/AiRemoveBgModal";
import { ImageCropControls } from "@/components/image-editor/ImageCropControls";
import { ImageEditorRightPanel } from "@/components/image-editor/ImageEditorRightPanel";
import { ImageEditorToolbar } from "@/components/image-editor/ImageEditorToolbar";
import { ImageEditorTopBar } from "@/components/image-editor/ImageEditorTopBar";
import { StudioMobileGate } from "@/components/studio/StudioMobileGate";
import { Toaster } from "@/components/ui/toaster";
import { useImageProjectPersistence } from "@/hooks/useImageProjectPersistence";
import { useIsMobile } from "@/hooks/useIsMobile";

const ImageEditorCanvas = dynamic(
  () =>
    import("@/components/image-editor/canvas/ImageEditorCanvas").then(
      (mod) => mod.ImageEditorCanvas
    ),
  { ssr: false, loading: () => <div className="h-full w-full bg-gray-950" /> }
);

export interface ImageEditorLayoutProps {
  projectId?: string;
}

export function ImageEditorLayout({ projectId }: ImageEditorLayoutProps) {
  const { isMobile, isReady } = useIsMobile();
  const { projectName, saveStatus, retrySave } =
    useImageProjectPersistence(projectId);

  if (!isReady) {
    return <div className="h-screen w-screen bg-gray-950" aria-hidden />;
  }

  if (isMobile) {
    return <StudioMobileGate variant="image" />;
  }

  return (
    <div className="flex h-screen w-screen flex-col overflow-hidden bg-gray-950 text-white">
      <Toaster />
      <ImageEditorTopBar
        projectId={projectId}
        projectName={projectName}
        saveStatus={saveStatus}
        onSaveRetry={retrySave}
      />
      <div className="flex min-h-0 flex-1">
        <ImageEditorToolbar />
        <main className="flex min-w-0 flex-1 flex-col">
          <ImageCropControls />
          <div className="min-h-0 flex-1">
            <ImageEditorCanvas />
          </div>
        </main>
        <ImageEditorRightPanel />
      </div>
      <AiRemoveBgModal />
    </div>
  );
}
