'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/hooks/useAuth';
import Sidebar from '@/components/ui/Sidebar';
import { LogOut } from 'lucide-react';

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const { user, currentOrganization, isAuthReady, logout } = useAuth();
  const router = useRouter();

  console.log('LAYOUT STATE:', {
    user,
    currentOrganization,
    isAuthReady
  });

  // ✅ AUTH GUARD (runs once per navigation group)
  useEffect(() => {
    if (!isAuthReady) return;

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

    if (!currentOrganization) {
      router.replace('/select-organization');
      return;
    }
  }, [isAuthReady, user, currentOrganization, router]);

  // ✅ LOADING ONLY FOR INITIAL LOAD
  if (!isAuthReady) {
    return (
      <div className="h-screen flex items-center justify-center">
        Loading app...
      </div>
    );
  }

  if (!user || !currentOrganization) {
    return (
      <div className="h-screen flex items-center justify-center">
        Loading workspace...
      </div>
    );
  }

  return (
    <div className="flex h-screen bg-[#020d1a] text-white">
      <Sidebar />

      <div className="flex-1 flex flex-col">
        <header className="flex justify-between px-6 py-4 border-b border-white/10">
          <h2>{currentOrganization.name}</h2>

          <div className="flex gap-4">
            <span>{user.name}</span>
            <button onClick={logout}>
              <LogOut />
            </button>
          </div>
        </header>

        <main className="p-6 flex-1 overflow-y-auto">
          {children} {/* 🔥 THIS CHANGES */}
        </main>
      </div>
    </div>
  );
}