import { useState, useEffect, useCallback } from 'react';
import { Outlet, useLocation } from 'react-router-dom';
import AppSidebar from './AppSidebar';
import AppTopbar from './AppTopbar';
import { BREAKPOINTS, LAYOUT } from '@/core/constants/app.constants';
import './AppLayout.scss';

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const handler = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);
  return width;
}

export default function AppLayout() {
  const width = useWindowWidth();
  const location = useLocation();

  const isMobile = width < BREAKPOINTS.tablet;
  const isTablet = width >= BREAKPOINTS.tablet && width < BREAKPOINTS.desktop;

  const [sidebarVisible, setSidebarVisible] = useState(!isMobile);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(isTablet);

  useEffect(() => {
    if (isMobile) {
      setSidebarVisible(false);
      setSidebarCollapsed(false);
    } else {
      setSidebarVisible(true);
      setSidebarCollapsed(isTablet);
    }
  }, [isMobile, isTablet]);

  // Close sidebar on route change (mobile)
  useEffect(() => {
    if (isMobile) setSidebarVisible(false);
  }, [location.pathname, isMobile]);

  const toggleSidebar = useCallback(() => {
    if (isMobile) {
      setSidebarVisible((v) => !v);
    } else {
      setSidebarCollapsed((c) => !c);
    }
  }, [isMobile]);

  const contentMarginLeft = isMobile
    ? '0'
    : sidebarCollapsed
      ? `${LAYOUT.sidebarCollapsedWidth}px`
      : `${LAYOUT.sidebarWidth}px`;

  return (
    <div className="app-layout">
      {isMobile && sidebarVisible && (
        <div className="app-layout__overlay" onClick={() => setSidebarVisible(false)} />
      )}

      <AppSidebar visible={sidebarVisible} collapsed={sidebarCollapsed && !isMobile} mobile={isMobile} />

      <div className="app-layout__main" style={{ marginLeft: contentMarginLeft }}>
        <AppTopbar onToggleSidebar={toggleSidebar} />
        <main className="app-layout__content">
          <Outlet />
        </main>
      </div>
    </div>
  );
}
