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

import { authStore } from "@/lib/auth";
import { Brand } from "@/components/brand/Brand";
import { Stepper } from "@/components/ui/Stepper";

const ONBOARDING_STEPS = [
  { id: "compte", label: "Compte", path: "/onboarding/compte" },
  { id: "entreprise", label: "Entreprise", path: "/onboarding/entreprise" },
  { id: "signature", label: "Signature", path: "/onboarding/signature" },
] as const;

export const Route = createFileRoute("/onboarding")({
  beforeLoad: ({ location }) => {
    if (!authStore.isAuthenticated()) {
      throw redirect({ to: "/login", search: { redirect: location.href } });
    }
  },
  component: OnboardingLayout,
});

function OnboardingLayout() {
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const currentIndex = Math.max(
    0,
    ONBOARDING_STEPS.findIndex((s) => pathname.startsWith(s.path)),
  );

  return (
    <main className="min-h-screen bg-cream">
      {/* Header minimal — pas de sidebar, pas de nav, juste la marque + le stepper. */}
      <header className="border-b border-line bg-cream/85 backdrop-blur-sm">
        <div className="mx-auto flex max-w-[920px] items-center justify-between px-6 py-5 lg:px-8">
          <Link to="/login">
            <Brand withSuffix />
          </Link>
          <p className="hidden text-[12.5px] text-ink-3 sm:block">
            Étape {currentIndex + 1} sur {ONBOARDING_STEPS.length}
          </p>
        </div>
        <div className="mx-auto max-w-[920px] px-6 pb-6 lg:px-8">
          <Stepper
            steps={ONBOARDING_STEPS.map(({ id, label }) => ({ id, label }))}
            currentIndex={currentIndex}
          />
        </div>
      </header>

      <div className="mx-auto w-full max-w-[640px] px-6 py-12 lg:px-8 lg:py-16">
        <Outlet />
      </div>
    </main>
  );
}
