'use client';

import { useAuth } from '@/contexts/auth-context';
import { useRouter, usePathname } from 'next/navigation';
import { useEffect } from 'react';

export function ProtectedRoute({
  children,
  allowedRoles,
}: {
  children: React.ReactNode;
  allowedRoles?: string[];
}) {
  const { token, isLoading, user } = useAuth();
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    const isLoginPath = pathname === '/login' || pathname === '/auth/sign-up' || pathname === '/auth/callback';

    if (isLoading || isLoginPath) return;

    if (!token) {
      router.push('/login');
      return;
    }

    if (allowedRoles && allowedRoles.length > 0) {
      const userRole = (user?.role || '').toLowerCase();
      const normalizedAllowed = allowedRoles.map((r) => r.toLowerCase());
      if (!normalizedAllowed.includes(userRole)) {
        const pathMap: Record<string, string> = {
          super_admin: '/',
          operations_admin: '/',
          compliance_officer: '/kyc',
          finance_admin: '/ledger',
          support_agent: '/support',
        };
        router.push(pathMap[userRole] || '/');
      }
    }
  }, [token, isLoading, router, pathname, allowedRoles, user?.role]);

  if (isLoading || (!token && pathname !== '/login')) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gold-500"></div>
      </div>
    );
  }

  return <>{children}</>;
}