"use client";

import { useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';
import { ThemeProvider } from '@/components/theme-provider';
import { Toaster } from '@/components/ui/toaster';
import Navbar from '@/components/ui/Navbar';

interface ClientLayoutProps {
  children: React.ReactNode;
}

interface UserData {
  id_user: number;
  username?: string;
  nip?: string;
  role_user: string;
}

export default function ClientLayout({ children }: ClientLayoutProps) {
  const [user, setUser] = useState<UserData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const pathname = usePathname();

  // Check for existing user session on mount
  useEffect(() => {
    checkUserSession();
  }, []);

  const checkUserSession = async () => {
    try {
      const response = await fetch('/api/auth/user');
      if (response.ok) {
        const data = await response.json();
        setUser(data.user);
      }
    } catch (error) {
      console.error('Error checking session:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // Don't show navbar on the root page (login page)
  const showNavbar = pathname !== '/' && user;

  return (
    <ThemeProvider
      attribute="class"
      themes={["light", "dark"]}
      enableSystem={false}
      disableTransitionOnChange
    >
      <div className="min-h-screen">
        {showNavbar && <Navbar />}
        <main className="flex-1">
          {children}
        </main>
      </div>
      <Toaster />
    </ThemeProvider>
  );
} 