"use client";

import { QuoteCard } from "@/components/quote-card";
import { Calendar } from "@/components/calendar";
import { News } from "@/components/news";
import { Duties } from "@/components/flow";
import { Email } from "@/components/email";
import { Parole } from "@/components/parole";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";

export default function Home() {
  const { data: session, status } = useSession();
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Check if logout is in progress - if so, redirect immediately
    const justLoggedOut = sessionStorage.getItem('just_logged_out') === 'true';
    const logoutCookie = document.cookie.split(';').some(c => c.trim().startsWith('logout_in_progress=true'));
    
    if (justLoggedOut || logoutCookie) {
      // Clear the flags and redirect
      sessionStorage.removeItem('just_logged_out');
      document.cookie = 'logout_in_progress=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC';
      window.location.href = '/signin?logout=true';
      return;
    }

    if (status !== "loading") {
      setIsLoading(false);
    }
  }, [status]);

  // Don't render widgets if logout is in progress
  const justLoggedOut = sessionStorage.getItem('just_logged_out') === 'true';
  const logoutCookie = document.cookie.split(';').some(c => c.trim().startsWith('logout_in_progress=true'));
  
  if (isLoading || justLoggedOut || logoutCookie) {
    return (
      <main className="h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-gray-900"></div>
      </main>
    );
  }

  return (
    <main className="h-screen overflow-auto">
      <div className="container mx-auto p-4 mt-12">
        {/* First row */}
        <div className="grid grid-cols-12 gap-4 mb-4">
          <div className="col-span-3">
            <QuoteCard />
          </div>
          <div className="col-span-3">
            <Calendar />
          </div>
          <div className="col-span-3">
            <News />
          </div>
          <div className="col-span-3">
            <Duties />
          </div>
        </div>
        
        {/* Second row */}
        <div className="grid grid-cols-12 gap-4">
          <div className="col-span-6">
            <Email />
          </div>
          <div className="col-span-6">
            <Parole />
          </div>
        </div>
      </div>
    </main>
  );
}
