/**
 * GetStartedView - Main view for the get-started flow
 *
 * Supports handoff from eligibility check flow:
 * - URL params: ?email=xxx&verified=true
 * - SessionStorage: get-started-email, get-started-verified
 */

"use client";

import { useState, useCallback, useEffect } from "react";
import { useSearchParams } from "next/navigation";
import { AuthLayout } from "@/components/templates/AuthLayout";
import { GetStartedForm } from "../components";
import { useGetStartedStore, type GetStartedStep } from "../stores/get-started.store";

export function GetStartedView() {
  const searchParams = useSearchParams();
  const { updateFormData, goToStep, setAccountStatus, setPrefill, setSessionToken } =
    useGetStartedStore();
  const [meta, setMeta] = useState({
    title: "Get Started",
    subtitle: "Enter your email to begin",
  });
  const [initialized, setInitialized] = useState(false);

  // Check for handoff from eligibility check on mount
  useEffect(() => {
    if (initialized) return;

    // Get params from URL or sessionStorage
    const emailParam = searchParams.get("email");
    const verifiedParam = searchParams.get("verified");

    const storedEmail = sessionStorage.getItem("get-started-email");
    const storedVerified = sessionStorage.getItem("get-started-verified");

    // Clear sessionStorage after reading
    sessionStorage.removeItem("get-started-email");
    sessionStorage.removeItem("get-started-verified");

    const email = emailParam || storedEmail;
    const isVerified = verifiedParam === "true" || storedVerified === "true";

    if (email && isVerified) {
      // User came from eligibility check - they have a verified email and SF Account
      updateFormData({ email });
      // The email is verified, but we still need to check account status
      // SF Account was already created during eligibility check, so status should be sf_unmapped
      setAccountStatus("sf_unmapped");
      // Go directly to complete-account step
      goToStep("complete-account");
    }

    setInitialized(true);
  }, [
    initialized,
    searchParams,
    updateFormData,
    goToStep,
    setAccountStatus,
    setPrefill,
    setSessionToken,
  ]);

  const handleStepChange = useCallback(
    (_step: GetStartedStep, stepMeta: { title: string; subtitle: string }) => {
      setMeta(stepMeta);
    },
    []
  );

  return (
    <AuthLayout title={meta.title} subtitle={meta.subtitle} wide>
      <GetStartedForm onStepChange={handleStepChange} />
    </AuthLayout>
  );
}

export default GetStartedView;
