"use client";

import { useEffect, type ReactNode } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth";
import { Sidebar } from "@/components/sidebar";
import { CommandPaletteProvider } from "@/components/command-palette-provider";

export function AppShell({ children }: { children: ReactNode }) {
  const { auth, loading } = useAuth();
  const pathname = usePathname();
  const router = useRouter();

  const isLoginPage = pathname === "/login";

  useEffect(() => {
    if (!loading && !auth?.isAuthenticated && !isLoginPage) {
      router.push("/login");
    }
  }, [loading, auth, isLoginPage, router]);

  // Login page: no sidebar, no auth check
  if (isLoginPage) {
    return <>{children}</>;
  }

  // Loading auth state
  if (loading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-text-secondary text-sm">Loading...</div>
      </div>
    );
  }

  // Not authenticated: show nothing (redirect will happen)
  if (!auth?.isAuthenticated) {
    return null;
  }

  // Authenticated: full app shell
  return (
    <>
      <CommandPaletteProvider />
      <Sidebar />
      <main className="flex-1 ml-60 min-h-screen">
        {children}
      </main>
    </>
  );
}
