'use client';

import { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { authApi } from '@/lib/api';

export default function AdminGuard({ children }: { children: React.ReactNode }) {
  const params = useSearchParams();
  const [state, setState] = useState<'checking' | 'ok' | 'denied'>('checking');

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const adm = params.get('adm');
      try {
        if (adm) {
          await authApi.session({ adm });
          // strip the param from URL but keep route
          const url = new URL(window.location.href);
          url.searchParams.delete('adm');
          window.history.replaceState({}, '', url.toString());
        }
        const who = await authApi.whoami();
        if (cancelled) return;
        if (who.role === 'admin') setState('ok');
        else setState('denied');
      } catch {
        if (!cancelled) setState('denied');
      }
    })();
    return () => { cancelled = true; };
  }, [params]);

  if (state === 'checking') return <div className="min-h-screen flex items-center justify-center text-gray-500">Verificando…</div>;
  if (state === 'denied') return <div className="min-h-screen flex items-center justify-center text-center px-6">
    <div>
      <h1 className="text-2xl font-bold mb-2">Acesso restrito</h1>
      <p className="text-gray-500">Adicione <code>?adm=&lt;token&gt;</code> à URL para entrar.</p>
    </div>
  </div>;
  return <>{children}</>;
}
