"use client";

import { memo, useMemo } from 'react';
import { MainNav } from "@/components/main-nav";
import { Footer } from "@/components/footer";
import { AuthCheck } from "@/components/auth/auth-check";
import { Toaster } from "@/components/ui/toaster";
import { useBackgroundImage } from "@/components/background-switcher";

interface LayoutWrapperProps {
  children: React.ReactNode;
  isSignInPage: boolean;
  isAuthenticated: boolean;
}

// Use memo to prevent unnecessary rerenders of the entire layout
export const LayoutWrapper = memo(function LayoutWrapper({ 
  children, 
  isSignInPage, 
  isAuthenticated 
}: LayoutWrapperProps) {
  const { currentBackground, changeBackground } = useBackgroundImage();

  // Memoize the background style to prevent recalculation on each render
  const backgroundStyle = useMemo(() => {
    if (isSignInPage) return {};
    
    return {
      backgroundImage: `url('${currentBackground}')`,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      backgroundRepeat: 'no-repeat',
      backgroundAttachment: 'fixed',
      cursor: 'pointer',
      transition: 'background-image 0.5s ease-in-out'
    };
  }, [currentBackground, isSignInPage]);

  return (
    <AuthCheck>
      {!isSignInPage && isAuthenticated && <MainNav />}
      <div 
        className={isSignInPage ? "" : "min-h-screen"}
        style={!isSignInPage ? backgroundStyle : {}}
        onClick={!isSignInPage ? changeBackground : undefined}
      >
        <main>{children}</main>
      </div>
      {!isSignInPage && isAuthenticated && <Footer />}
      <Toaster />
    </AuthCheck>
  );
}); 