"use client";

// ============================================================================
// Root Page - Redirect to Dashboard
// ============================================================================

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2 } from "lucide-react";
import { authApi, workspacesApi } from "@/lib/api";
import { STORAGE_KEYS } from "@/lib/utils/constants";

export default function RootPage() {
  const router = useRouter();
  const [isChecking, setIsChecking] = useState(true);

  useEffect(() => {
    const checkAuthAndRedirect = async () => {
      // Check if user is authenticated
      const token = localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);
      
      if (!token) {
        router.replace("/login");
        return;
      }

      try {
        // Verify token is valid
        await authApi.me();

        // Get workspaces
        const { items: workspaces } = await workspacesApi.list({ size: 1 });

        if (workspaces.length > 0) {
          // Check for saved workspace
          const savedId = localStorage.getItem(STORAGE_KEYS.SELECTED_WORKSPACE);
          const workspaceId = savedId || workspaces[0].id;
          router.replace(`/dashboard/${workspaceId}`);
        } else {
          // No workspaces - show onboarding or create first workspace
          router.replace("/dashboard/onboarding");
        }
      } catch (err) {
        // Token invalid - redirect to login
        localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);
        router.replace("/login");
      }
    };

    checkAuthAndRedirect();
  }, [router]);

  return (
    <div className="flex min-h-screen items-center justify-center">
      <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
    </div>
  );
}

