'use client';

import React, { useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { useAuthStore } from '@/stores/authStore';
import { useProfileStore } from '@/stores/profileStore';
import { useUIStore } from '@/stores/uiStore';
import Header from '@/components/layout/Header';
import Sidebar from '@/components/layout/Sidebar';
import Spinner from '@/components/ui/Spinner';
import ProfileSelection from '@/components/profile/ProfileSelection';
import GlobalPlayer from '@/components/player/GlobalPlayer';
import { cn } from '@/lib/utils';

export default function MainLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const { isAuthenticated, _hasHydrated: isAuthHydrated, user } = useAuthStore();
  const { activeProfile, _hasHydrated: isProfileHydrated } = useProfileStore();
  const { sidebarCollapsed } = useUIStore();

  const isHydrated = isAuthHydrated && isProfileHydrated;

  // Auth guard
  useEffect(() => {
    if (isHydrated && !isAuthenticated) {
      router.replace('/login');
    }
  }, [isHydrated, isAuthenticated, router]);

  if (!isHydrated || !isAuthenticated) {
    return (
      <div className="min-h-screen bg-dark flex items-center justify-center">
        <Spinner size="xl" color="primary" />
      </div>
    );
  }

  // If no profile is selected, force selection screen
  if (!activeProfile) {
    return <ProfileSelection />;
  }

  return (
    <div className="min-h-screen bg-dark">
      <Header />
      <Sidebar />
      <main className={cn(
        "pt-16 transition-all duration-300 min-h-screen",
        sidebarCollapsed ? "lg:pl-20" : "lg:pl-64"
      )}>
        <div className="p-4 lg:p-6 pb-24">
          {children}
        </div>
      </main>
      <GlobalPlayer />
    </div>
  );
}
