import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
import { cn } from "@/lib/utils";
import Header from "./header";
import Sidebar from "./sidebar";
import Footer from "./watermark-footer";
import { useIsMobile } from "@/hooks/use-mobile";
import useKeyboardShortcuts from "@/hooks/useKeyboardShortcuts";
import { useAuth } from "@/lib/auth-context";
import GlobalWorkNotifications from "@/components/GlobalWorkNotifications";

interface LayoutProps {
  children: React.ReactNode;
}

const Layout = ({ children }: LayoutProps) => {
  const isMobile = useIsMobile();
  const [isSidebarOpen, setIsSidebarOpen] = useState(!isMobile);
  const location = useLocation();
  const { isAuthenticated } = useAuth();
  
  // Check if we're on the download app page
  const isDownloadPage = location.pathname === "/download-app";
  const isLoginPage = location.pathname === "/login";
  
  // Initialize keyboard shortcuts
  useKeyboardShortcuts();

  // Close sidebar on mobile when route changes
  useEffect(() => {
    if (isMobile) {
      setIsSidebarOpen(false);
    }
  }, [location, isMobile]);

  // Update sidebar state when screen size changes
  useEffect(() => {
    setIsSidebarOpen(!isMobile);
  }, [isMobile]);

  // Update sidebar state when authentication changes
  useEffect(() => {
    if (isAuthenticated && !isMobile) {
      setIsSidebarOpen(true);
    }
  }, [isAuthenticated, isMobile]);

  return (
    <div className="relative flex h-full bg-background">
      {/* Only show sidebar when authenticated */}
      {isAuthenticated && (
        <Sidebar isOpen={isSidebarOpen} setIsOpen={setIsSidebarOpen} />
      )}
      
      <div
        className={cn(
          "flex-1 flex flex-col transition-all duration-300 ease-in-out",
          isSidebarOpen && !isMobile && isAuthenticated ? "ml-64" : "ml-0"
        )}
      >
        <Header 
          toggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} 
          isSidebarOpen={isSidebarOpen} 
        />
        
        <main className="flex-1 pt-16 overflow-x-hidden">
          <div className={cn(
            "px-4 py-6 md:p-6 mx-auto animate-fadeIn",
            isDownloadPage ? "max-w-5xl" : "max-w-7xl"
          )}>
            {children}
          </div>
        </main>
        <Footer />
      </div>
      
      {/* Overlay for mobile sidebar */}
      {isSidebarOpen && isMobile && (
        <div 
          className="fixed inset-0 bg-black/50 z-30"
          onClick={() => setIsSidebarOpen(false)}
        />
      )}
      
      {/* Global Work Notifications - Show on all pages when authenticated */}
      {isAuthenticated && <GlobalWorkNotifications />}
    </div>
  );
};

export default Layout;
