import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";

import { authStore } from "@/lib/auth";
import { AppLayout } from "@/components/layout/AppLayout";
import { InAppCheckinModal } from "@/components/checkin/InAppCheckinModal";

/**
 * `_app` — layout pathless pour l'app authentifiée.
 * URL des enfants : /, /factures, /plans, /clients, /parametres
 *
 * Garde d'auth + onboarding :
 *  - Pas authentifié → /login (avec redirect)
 *  - Authentifié mais signature null → onboarding pas terminé → /onboarding/compte
 */
export const Route = createFileRoute("/_app")({
  beforeLoad: ({ location }) => {
    if (!authStore.isAuthenticated()) {
      throw redirect({ to: "/login", search: { redirect: location.href } });
    }
    // Onboarding incomplet : on a un user mais pas de signature → step 3 pas faite.
    // Côté API "vrai", on s'appuiera plutôt sur `organization.onboardingCompletedAt`.
    if (authStore.user && authStore.user.signature === null) {
      throw redirect({ to: "/onboarding/compte" });
    }
  },
  component: AppRouteComponent,
});

function AppRouteComponent() {
  return (
    <AppLayout>
      <Outlet />
      <InAppCheckinModal />
    </AppLayout>
  );
}
