'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useMe } from '@/lib/auth';
import { AppHeader } from './app-header';
import { BottomNav } from './bottom-nav';

interface Props {
  children: React.ReactNode;
  role: 'captain' | 'volunteer';
}

export function AuthShell({ children, role }: Props) {
  const { data: user, isLoading, error } = useMe();
  const router = useRouter();

  useEffect(() => {
    if (isLoading) return;
    if (error || !user) router.replace('/login');
  }, [user, isLoading, error, router]);

  // Role mismatch guard - keeps a pure-volunteer out of /captain
  useEffect(() => {
    if (!user) return;
    if (role === 'captain' && !user.isCaptain) router.replace('/volunteer');
    if (role === 'volunteer' && !user.isVolunteer) router.replace('/captain');
  }, [user, role, router]);

  if (isLoading || !user) {
    return (
      <div className="min-h-screen bg-paper flex items-center justify-center">
        <div className="text-ink-400 text-sm">Loading…</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-paper flex flex-col">
      <AppHeader user={user} role={role} />
      <main className="flex-1 container max-w-2xl py-6 pb-20">{children}</main>
      <BottomNav role={role} />
    </div>
  );
}
