import React, { useState, useEffect } from 'react';
import Sidebar from './Sidebar';
import Topbar from './Topbar';

const MainLayout = ({ children }) => {
    const [isCollapsed, setIsCollapsed] = useState(() => {
        const saved = localStorage.getItem('sidebar_collapsed');
        return saved === 'true';
    });
    const [isMobile, setIsMobile] = useState(window.innerWidth <= 1024);

    useEffect(() => {
        const handleResize = () => {
            const mobile = window.innerWidth <= 1024;
            setIsMobile(mobile);
            if (mobile) {
                setIsCollapsed(true);
            }
        };

        window.addEventListener('resize', handleResize);
        handleResize(); // Initial check

        return () => window.removeEventListener('resize', handleResize);
    }, []);

    useEffect(() => {
        if (!isMobile) {
            localStorage.setItem('sidebar_collapsed', isCollapsed);
        }
    }, [isCollapsed, isMobile]);

    return (
        <div className="flex bg-bg-light dark:bg-bg-dark min-h-screen transition-colors duration-300 font-sans relative overflow-hidden">
            {/* Mobile Overlay */}
            {isMobile && !isCollapsed && (
                <div
                    className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[35] animate-in fade-in duration-300"
                    onClick={() => setIsCollapsed(true)}
                />
            )}

            <Sidebar isCollapsed={isCollapsed} setIsCollapsed={setIsCollapsed} isMobile={isMobile} />
            <div className={`flex-1 flex flex-col min-w-0 transition-all duration-300 overflow-x-hidden ${isMobile ? 'ml-0' : (isCollapsed ? 'ml-20' : 'ml-72')}`}>
                <Topbar toggleSidebar={() => setIsCollapsed(!isCollapsed)} />
                <main className="p-4 sm:p-8 lg:p-10 flex-1 overflow-y-auto">
                    <div className="max-w-[1600px] mx-auto animate-in fade-in slide-in-from-bottom-4 duration-700">
                        {children}
                    </div>
                </main>
            </div>
        </div>
    );
};

export default MainLayout;
