import React, { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import Navbar from './Navbar';
import Sidebar from './Sidebar';

const Layout = ({ children }) => {
  const location = useLocation();
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);

  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth <= 992) {
        setSidebarCollapsed(true);
      } else {
        setSidebarCollapsed(false);
      }
    };

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

  // Close sidebar on route change (mobile) so body scroll is restored on the new page
  useEffect(() => {
    if (window.innerWidth <= 992) {
      setSidebarCollapsed(true);
    }
  }, [location.pathname]);

  const toggleSidebar = () => {
    setSidebarCollapsed(!sidebarCollapsed);
  };

  useEffect(() => {
    // Only show overlay when sidebar is OPEN (visible) on mobile, not when it's closed
    if (!sidebarCollapsed && window.innerWidth <= 992) {
      document.body.classList.add('sidebar-open');
    } else {
      document.body.classList.remove('sidebar-open');
    }
    return () => {
      document.body.classList.remove('sidebar-open');
    };
  }, [sidebarCollapsed]);

  return (
    <>
      <Navbar onToggleSidebar={toggleSidebar} />
      <Sidebar collapsed={sidebarCollapsed} onToggleSidebar={toggleSidebar} />
      <main className="main-content">
        <div key={location.pathname} className="content-wrapper page-content-enter">
          {children}
        </div>
      </main>
    </>
  );
};

export default Layout;

