'use client';

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

export default function HomePage() {
  const router = useRouter();
  const params = useSearchParams();
  const [state, setState] = useState<'checking' | 'guest' | 'none'>('checking');
  const [guestName, setGuestName] = useState<string>('');

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const adm = params.get('adm');
      const usr = params.get('usr');
      try {
        if (adm) {
          await authApi.session({ adm });
          router.replace('/admin');
          return;
        }
        if (usr) {
          await authApi.session({ usr });
        }
        const who = await authApi.whoami();
        if (cancelled) return;
        if (who.role === 'admin') {
          router.replace('/admin');
          return;
        }
        if (who.role === 'guest') {
          setGuestName(who.guest.name);
          setState('guest');
          return;
        }
        setState('none');
      } catch {
        if (!cancelled) setState('none');
      }
    })();
    return () => { cancelled = true; };
  }, [params, router]);

  if (state === 'checking') {
    return <div className="min-h-screen flex items-center justify-center text-gray-500">Carregando…</div>;
  }

  if (state === 'guest') {
    return (
      <div className="min-h-screen flex items-center justify-center text-center px-6">
        <div>
          <h1 className="text-3xl font-bold mb-2">Olá, {guestName}!</h1>
          <p className="text-gray-500">Visite o link da lista que você recebeu.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center text-center px-6">
      <div>
        <h1 className="text-3xl font-bold mb-2">Convite necessário</h1>
        <p className="text-gray-500">Esta página é por convite. Use o link que recebeu.</p>
      </div>
    </div>
  );
}
