'use client';

import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
import Image from 'next/image';
import { Footer } from '@/components/layout/Footer';
import { CommonHeader } from '@/components/layout/CommonHeader';
import { PresenceProvider } from '@/components/providers/presence-provider';

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

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

    // Don't redirect to /login here — the middleware handles that.
    // Doing it here causes race conditions during logout (layout detects
    // session loss and redirects to /login via client-side navigation,
    // which can conflict with the server-side logout redirect).
    if (!session) return;

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

  if (status === 'loading' || !session) {
    return (
      <div
        className="min-h-screen flex flex-col items-center justify-center"
        style={{ background: 'linear-gradient(to bottom, #c4d9d4, #f0f5fc)' }}
      >
        <Image src="/assets/images/splash-house.png" alt="" width={150} height={108} priority />
        <div className="mt-[35px]">
          <Image src="/assets/images/splash-logo.png" alt="RE-Quest" width={264} height={55} priority />
        </div>
        <div className="mt-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#00293d]" />
        </div>
      </div>
    );
  }

  return (
    <PresenceProvider>
      <div className="min-h-screen bg-white flex flex-col">
        {/* Main Content Area */}
        <main className="flex-1">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
            {/* Header Bar */}
            <CommonHeader />

            {/* Page Content */}
            <div className="mt-3">
              {children}
            </div>
          </div>
        </main>

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