/**
 * GetStartedForm - Main form component for the unified get-started flow
 *
 * Flow: Email → OTP Verification → Account Status → Complete Account → Success
 */

"use client";

import { useEffect } from "react";
import { useGetStartedStore, type GetStartedStep } from "../../stores/get-started.store";
import {
  EmailStep,
  VerificationStep,
  AccountStatusStep,
  CompleteAccountStep,
  SuccessStep,
} from "./steps";

const stepComponents: Record<GetStartedStep, React.ComponentType> = {
  email: EmailStep,
  verification: VerificationStep,
  "account-status": AccountStatusStep,
  "complete-account": CompleteAccountStep,
  success: SuccessStep,
};

const stepTitles: Record<GetStartedStep, { title: string; subtitle: string }> = {
  email: {
    title: "Get Started",
    subtitle: "Enter your email to begin",
  },
  verification: {
    title: "Verify Your Email",
    subtitle: "Enter the code we sent to your email",
  },
  "account-status": {
    title: "Welcome",
    subtitle: "Let's get you set up",
  },
  "complete-account": {
    title: "Create Your Account",
    subtitle: "Just a few more details",
  },
  success: {
    title: "Account Created!",
    subtitle: "You're all set",
  },
};

interface GetStartedFormProps {
  /** Callback when step changes (for parent to update title) */
  onStepChange?: (step: GetStartedStep, meta: { title: string; subtitle: string }) => void;
}

export function GetStartedForm({ onStepChange }: GetStartedFormProps) {
  const { step, reset } = useGetStartedStore();

  // Reset form on mount to ensure clean state (but not if coming from handoff)
  useEffect(() => {
    // Check if user is coming from eligibility check handoff
    const hasHandoffParam = window.location.search.includes("handoff=");
    const hasHandoffToken = sessionStorage.getItem("get-started-handoff-token");

    // Don't reset if we have handoff data - let GetStartedView pre-fill the form
    if (!hasHandoffParam && !hasHandoffToken) {
      reset();
    }
  }, [reset]);

  // Notify parent of step changes
  useEffect(() => {
    onStepChange?.(step, stepTitles[step]);
  }, [step, onStepChange]);

  const StepComponent = stepComponents[step];

  return (
    <div className="w-full">
      <StepComponent />
    </div>
  );
}
