import { useQuery } from '@tanstack/react-query';
import { useAuth } from '../../contexts/AuthContext';
import { configApi } from '../../services/config';
import ServiceModePage from './ServiceModePage';

interface Props {
  children: React.ReactNode;
}

export default function ServiceModeGuard({ children }: Props) {
  const { user } = useAuth();
  const isAdmin = user?.groups?.includes('dashboard_admin') ?? false;

  const { data: serviceMode, isLoading } = useQuery({
    queryKey: ['service-mode'],
    queryFn: configApi.getServiceMode,
    refetchInterval: 60_000,
    retry: false,
  });

  // Don't render children until we know the service mode status
  if (isLoading) return null;

  if (serviceMode?.active && !isAdmin) {
    return <ServiceModePage message={serviceMode.message} />;
  }

  return <>{children}</>;
}
