"use client"

import type React from "react"
import { useEffect, useState } from "react"
import { Sidebar } from "@/components/sidebar"
import { MaterialProvider } from "@/contexts/material-context"
import { ColorProvider } from "@/contexts/color-context"
import { DesignProvider } from "@/contexts/design-context"
import { SidebarProvider, useSidebar } from "@/contexts/sidebar-context"
import { ViewProvider } from "@/contexts/view-context"
import { RightSidebar } from "@/components/right-sidebar"
import { FixedHeader } from "@/components/fixed-header"
import { RightSidebarToggle } from "@/components/right-sidebar-toggle"
import { MobileDesignControls } from "@/components/mobile-design-controls"

// Create a wrapper component that uses the sidebar context
function AppLayoutContent({ children }: { children: React.ReactNode }) {
  const { sidebarVisible, toggleSidebar } = useSidebar()
  const [isInitialized, setIsInitialized] = useState(false)
  const [isFirstLoad, setIsFirstLoad] = useState(false)
  const [isMobile, setIsMobile] = useState(false)

  // Check if this is the first load of the app
  useEffect(() => {
    const hasLoadedBefore = sessionStorage.getItem("app-has-loaded")
    if (!hasLoadedBefore) {
      setIsFirstLoad(true)
      sessionStorage.setItem("app-has-loaded", "true")
    }
  }, [])

  // Check for mobile screen size
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 768) // md breakpoint
    }

    checkMobile()
    window.addEventListener("resize", checkMobile)

    return () => window.removeEventListener("resize", checkMobile)
  }, [])

  // Add event listener for the toggle-sidebar event
  useEffect(() => {
    const handleToggleSidebar = () => {
      toggleSidebar()
    }

    window.addEventListener("toggle-sidebar", handleToggleSidebar)
    return () => {
      window.removeEventListener("toggle-sidebar", handleToggleSidebar)
    }
  }, [toggleSidebar])

  // Mark as initialized after first render to enable transitions
  useEffect(() => {
    if (isFirstLoad) {
      const timer = setTimeout(() => {
        setIsInitialized(true)
      }, 300) // Only delay on first load
      return () => clearTimeout(timer)
    } else {
      // Immediately initialize if not first load
      setIsInitialized(true)
    }
  }, [isFirstLoad])

  // Calculate transform based on state
  const getTransform = () => {
    if (isFirstLoad && !isInitialized) {
      // First load entrance animation
      return "translate3d(-16px, 0, 0)"
    } else if (sidebarVisible) {
      // Visible state (both mobile and desktop)
      return "translate3d(0, 0, 0)"
    } else {
      // Hidden state - slide out to the left
      return "translate3d(-100%, 0, 0)"
    }
  }

  return (
    <div className="min-h-screen bg-background-primary">
      {/* Fixed Header */}
      <FixedHeader />

      {/* Left Sidebar - Works the same on both mobile and desktop */}
      <div
        className="fixed top-0 left-0 h-screen w-64 bg-background-secondary z-40"
        style={{
          transform: getTransform(),
          opacity: isFirstLoad && !isInitialized ? 0 : 1,
          transition: isInitialized
            ? "transform 400ms cubic-bezier(0.23, 1, 0.32, 1), opacity 400ms cubic-bezier(0.23, 1, 0.32, 1)"
            : isFirstLoad
              ? "transform 500ms cubic-bezier(0.23, 1, 0.32, 1), opacity 400ms cubic-bezier(0.23, 1, 0.32, 1)"
              : "none",
          willChange: "transform, opacity",
        }}
      >
        <Sidebar isFirstLoad={isFirstLoad} />
      </div>

      {/* Main Content Area - Responsive margin and padding */}
      <div
        className="min-h-screen overflow-x-hidden"
        style={{
          marginLeft: sidebarVisible ? "16rem" : "0",
          transition: isInitialized
            ? "margin-left 400ms cubic-bezier(0.23, 1, 0.32, 1)"
            : isFirstLoad
              ? "margin-left 400ms cubic-bezier(0.23, 1, 0.32, 1)"
              : "none",
        }}
      >
        <div
          className={`min-h-screen ${isMobile ? "px-4" : "md:pr-72"}`}
          style={{
            width: isMobile ? "100vw" : "auto",
            minWidth: isMobile ? "100vw" : "auto",
          }}
        >
          {children}
        </div>
      </div>

      {/* Right Sidebar */}
      {!isMobile && (
        <div
          className="fixed top-16 right-4 bottom-0 w-64 flex-shrink-0 right-sidebar z-20 hidden md:flex opacity-100"
          style={{
            height: "calc(100vh - 64px)",
            borderRadius: "6px 6px 0 0",
            transition: "transform 400ms cubic-bezier(0.4, 0, 0.2, 1), opacity 400ms cubic-bezier(0.4, 0, 0.2, 1)",
          }}
        >
          <RightSidebar />
        </div>
      )}

      {/* Right Sidebar Toggle - Hidden on mobile */}
      {!isMobile && (
        <div className="fixed bottom-4 right-4 z-40">
          <RightSidebarToggle />
        </div>
      )}

      {/* Mobile Design Controls - Only visible on mobile */}
      {isMobile && <MobileDesignControls />}
    </div>
  )
}

// Main layout component that sets up providers
export default function AppLayout({ children }: { children: React.ReactNode }) {
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    setMounted(true)
  }, [])

  if (!mounted) {
    return (
      <div className="min-h-screen bg-background-primary">
        {/* Fixed Header placeholder */}
        <div className="fixed top-0 left-0 right-0 h-16 bg-background-primary border-b border-border z-50" />

        {/* Sidebar placeholder - hidden on mobile during loading */}
        <div className="fixed top-0 left-0 h-screen w-64 bg-background-secondary border-r border-border z-40 hidden md:block" />

        {/* Main content with responsive margin */}
        <div className="md:ml-64 pt-16 px-4 md:px-0">
          <div className="flex items-center justify-center h-96">
            <div className="text-muted-foreground">Loading...</div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <ColorProvider>
      <MaterialProvider>
        <DesignProvider>
          <SidebarProvider>
            <ViewProvider>
              <AppLayoutContent>{children}</AppLayoutContent>
            </ViewProvider>
          </SidebarProvider>
        </DesignProvider>
      </MaterialProvider>
    </ColorProvider>
  )
}
