import React, { useEffect, useState } from 'react';
import { Outlet } from 'react-router-dom';
import Sidebar from './Sidebar';
import Topbar from './Topbar';
import { useUiStore } from '../../stores/uiStore';

export default function AdminLayout() {
  const darkMode      = useUiStore((s) => s.darkMode);
  const density       = useUiStore((s) => s.density);
  const brandHue      = useUiStore((s) => s.brandHue);
  const sidebarOpen   = useUiStore((s) => s.sidebarOpen);
  const setSidebarOpen = useUiStore((s) => s.setSidebarOpen);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    const root = document.documentElement;
    root.classList.toggle('dark', darkMode);
    root.setAttribute('data-theme', darkMode ? 'dark' : 'light');
    root.setAttribute('data-density', density);
    root.style.setProperty('--brand-h', String(brandHue.h));
    root.style.setProperty('--brand-c', String(brandHue.c));
  }, [darkMode, density, brandHue]);

  return (
    <div
      className="app"
      data-collapsed={!sidebarOpen ? 'true' : 'false'}
      data-mobile-open={mobileOpen ? 'true' : 'false'}
    >
      <div className="scrim" onClick={() => setMobileOpen(false)} />
      <Sidebar mobileOpen={mobileOpen} onMobileClose={() => setMobileOpen(false)} />
      <div className="main">
        <Topbar onMobileMenuOpen={() => setMobileOpen(true)} />
        <main className="content">
          <Outlet />
        </main>
      </div>
    </div>
  );
}
