'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/lib/stores/auth-store';
import type { UserRole } from '@/lib/constants/navigation';

/**
 * AuthGuard — client component that protects dashboard routes.
 *
 * Reads the Zustand auth store and redirects unauthenticated users to /login.
 * If the stored role is corrupted or invalid, clears state and redirects.
 * Client_Portal users are redirected to /portal since they should not access
 * the admin dashboard.
 *
 * Wrap dashboard layouts with this component to enforce simulated auth.
 */

const VALID_ROLES: readonly UserRole[] = ['Super_Admin', 'Publisher_Admin', 'Viewer', 'Client_Portal'] as const;

function isValidRole(role: unknown): role is UserRole {
  return typeof role === 'string' && (VALID_ROLES as readonly string[]).includes(role);
}

export default function AuthGuard({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const { isAuthenticated, role, logout } = useAuthStore();

  useEffect(() => {
    if (!isAuthenticated || !role) {
      router.replace('/login');
      return;
    }

    // If role state is corrupted or invalid, clear state and redirect
    if (!isValidRole(role)) {
      logout();
      router.replace('/login');
      return;
    }

    // Client_Portal users should not access dashboard routes — redirect to portal
    if (role === 'Client_Portal') {
      router.replace('/portal');
    }
  }, [isAuthenticated, role, logout, router]);

  // Don't render children until auth is confirmed valid
  if (!isAuthenticated || !role || !isValidRole(role)) {
    return null;
  }

  // Don't render dashboard for Client_Portal users
  if (role === 'Client_Portal') {
    return null;
  }

  return <>{children}</>;
}
