'use client';

import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { Footer } from '@/components/layout/Footer';
import { CommonHeader } from '@/components/layout/CommonHeader';

export default function UserLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { data: session, status } = useSession();
  const router = useRouter();

  useEffect(() => {
    if (status === 'loading') return;

    if (!session) {
      router.replace('/login');
      return;
    }

    // Redirect agents to agent dashboard
    const userRole = (session.user as any)?.role;
    if (userRole === 'AGENT') {
      router.replace('/agent/dashboard');
    }
  }, [session, status, router]);

  if (status === 'loading' || !session) {
    return (
      <div className="min-h-screen bg-white flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#00293d]"></div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex flex-col">
      {/* Main Content with Header inside */}
      <main className="flex-1 relative">
        {/* Header overlaying the content */}
        <div className="absolute top-0 left-0 right-0 z-50 px-4 py-3">
          <div className="max-w-7xl mx-auto">
            <CommonHeader />
          </div>
        </div>
        {children}
      </main>

      {/* Footer */}
      <Footer />
    </div>
  );
}
