import { useEffect } from 'react';
import { Outlet, useNavigate } from 'react-router';
import Sidebar from './Sidebar';
import { useAuthStore } from '@/stores/authStore';

export default function MainLayout() {
  const user = useAuthStore((s) => s.user);
  const navigate = useNavigate();

  // Eagerly fetch user profile on mount if not already in store
  useEffect(() => {
    if (user) return;

    let cancelled = false;

    async function init() {
      try {
        const res = await fetch('/api/auth/me', { credentials: 'include' });

        if (res.ok && !cancelled) {
          const { user: userData } = await res.json();
          useAuthStore.getState().setUser(userData);
        } else if (!cancelled) {
          // Not authenticated — redirect to login
          navigate('/login');
        }
      } catch {
        if (!cancelled) navigate('/login');
      }
    }

    init();
    return () => { cancelled = true; };
  }, [user, navigate]);

  return (
    <div className="flex h-screen w-full overflow-hidden">
      <Sidebar />
      <main className="flex flex-1 flex-col overflow-hidden bg-background">
        <Outlet />
      </main>
    </div>
  );
}
