import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { BrandSplash } from "@/components/AppLogo";
import { installStatus } from "@/lib/install.functions";

export const Route = createFileRoute("/")({
  ssr: false,
  component: IndexRedirect,
});

function IndexRedirect() {
  const navigate = useNavigate();
  useEffect(() => {
    let cancelled = false;
    void (async () => {
      // A brand-new deployment (no backend configured, or setup never
      // completed) goes straight to the installation wizard.
      try {
        const status = await installStatus();
        if (cancelled) return;
        if (!status.configured || !status.installed) {
          navigate({ to: "/install", replace: true });
          return;
        }
      } catch {
        /* status unavailable — fall through to the normal sign-in flow */
      }
      const { data } = await supabase.auth.getSession();
      if (cancelled) return;
      navigate({ to: data.session ? "/app" : "/login", replace: true });
    })();
    return () => {
      cancelled = true;
    };
  }, [navigate]);
  return <BrandSplash label="Signing you in" />;
}

