'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '../lib/authContext';

export default function AuthGuard({ children }: { children: React.ReactNode }) {
  const { user, isLoading } = useAuth();
  const router = useRouter();
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!mounted) return;
    let t: ReturnType<typeof setTimeout>;
    if (!isLoading && !user) {
      t = setTimeout(() => router.replace('/login'), 0);
    } else if (!isLoading && user) {
      if (user.role === 'employee') t = setTimeout(() => router.replace('/employee'), 0);
      else if (user.role === 'hod') t = setTimeout(() => router.replace('/hod'), 0);
      else if (user.role === 'hos') t = setTimeout(() => router.replace('/hos'), 0);
      else if (user.role === 'finance') t = setTimeout(() => router.replace('/finance'), 0);
    }
    return () => clearTimeout(t);
  }, [user, isLoading, router, mounted]);

  if (!mounted || isLoading) return (
    <div className="min-h-screen flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #7B1FA2 0%, #4A0072 100%)' }}>
      <div className="text-center">
        <div className="w-12 h-12 flex items-center justify-center mx-auto mb-3">
          <i className="ri-loader-4-line text-white text-4xl animate-spin"></i>
        </div>
        <p className="text-white text-sm">Loading...</p>
      </div>
    </div>
  );

  if (!user || user.role === 'employee' || user.role === 'hod' || user.role === 'hos' || user.role === 'finance') return null;

  return <>{children}</>;
}