'use client';

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

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

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const url = new URL(window.location.href);
      const adm = url.searchParams.get('adm');
      try {
        if (adm) {
          await authApi.session({ adm });
          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; };
  }, []);

  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}</>;
}
