'use client';

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

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

  // ✅ 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 app-web-bg">
        Loading app...
      </div>
    );
  }

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

  return (
    <div className="flex h-screen app-web-bg text-text-primary">
      <Sidebar />

      <div className="flex-1 flex flex-col">
        <header className="flex justify-between px-6 py-4 border-b border-border/70 backdrop-blur-sm">
          <h2 className="text-lg font-medium">{currentOrganization.name}</h2>

          <div className="flex items-center gap-4">
            <ThemeToggle />
            <span className="text-sm text-text-secondary">{user.name}</span>
            <button
              onClick={logout}
              className="inline-flex items-center gap-2 text-sm text-text-secondary hover:text-text-primary transition-colors"
            >
              <LogOut className="w-4 h-4 icon-flat" />
              Logout
            </button>
          </div>
        </header>

        <main className="p-6 flex-1 overflow-y-auto">
          <div className="surface-panel p-6 min-h-full">
            {children}
          </div>
        </main>
      </div>
    </div>
  );
}