"use client";

import { useLocalizedNavigation } from "@/src/lib/hooks/useLocalizedNavigation";
import { useState, useEffect, useMemo, memo } from "react";
import { getJSONCookie, setJSONCookie } from "@/src/lib/utils/cookies";
import Image from "next/image";
import { AnimatePresence } from "framer-motion";
import { useSearchParams } from "next/navigation";
import ProgramsSliderFooter from "../ProgramsSlider-Footer";
import { withCDN } from "@/src/lib/utils";
import { submitFormAction } from "@/src/lib/actions/submitFormAction";
import { fetchLocationsAction } from "@/src/lib/actions/locationsAction";
import { fetchClassesAction } from "@/src/lib/actions/classesAction";
import type { Form, FormStep, FormFieldOption } from "@/src/lib/services/formsService";
import type { TenantData } from "@/src/lib/types/header";
import { FormSkeleton } from "../../ui/skeletons/FormSkeleton";
import { DynamicHeader, DynamicFormStep, AnimatedStep, ClassInfoStep, getFieldKey } from "./FormRenderer";
import { useSelectedClass } from "@/src/lib/context/SelectedClassContext";
import { useClassDetails } from "@/src/lib/context/ClassDetailsContext";

export default function FooterForm({ page, form, isLoading, tenant, isDetailsPage = false, cwProgramId }: { page?: string; form?: Form | null; isLoading?: boolean; tenant?: TenantData; isDetailsPage?: boolean; cwProgramId?: string | number | null }) {
  return (
    <section className={`relative w-full mt-[-120px] z-99  ${page == "programs" ? "mt-[330px] lg:mt-[180px] md:mt-[140px] xl:mt-[270px]" : "mt-[-70px] lg:mt-[-100px] xl:mt-[-110px] md:mt-[-130px]"}`}>
      {/* Desktop & Tablet */}
      <div
        className={`w-full bg-transparent z-100 sm:mt-[-160px] xl:mt-[-300px]  mt-[-300px]  ${page == "programs" ? "md:mt-[-240px]  lg:mt-[-280px]" : "md:mt-[-340px]  lg:mt-[-300px]"}`}
        style={{
          backgroundImage: `url('${withCDN("/form-footer.png")}')`,
          backgroundSize: "cover",
          backgroundPosition: "top",
          backgroundRepeat: "no-repeat" }}
        id="registration-form"
      >
        <div className="max-w-[1300px] mx-auto lg:px-5 md:px-10 xl:px-16">
            <FormContent form={form} isLoading={isLoading} slug={page || "home"} tenant={tenant} isDetailsPage={isDetailsPage} cwProgramId={cwProgramId} />
        </div>
      </div>

      {/* Footer slider */}
      {/* <div className="relative w-full bg-white z-30">
        <ProgramsSliderFooter />
      </div> */}
    </section>
  );
}

/* ---------- FORM CONTENT LAYOUT ---------- */

function FormContentComponent({ form, isLoading, slug, tenant, isDetailsPage = false, cwProgramId }: { form?: Form | null; isLoading?: boolean; slug?: string; tenant?: TenantData; isDetailsPage?: boolean; cwProgramId?: string | number | null }) {
  if (isLoading) {
    return (
      <FormSkeleton />
    );
  }

  if (!isLoading && (!form || !form.fields || !form.fields.steps || form.fields.steps.length === 0)) {
    return null;
  }

  const { classDetails: classDetailsCtx } = useClassDetails();
  const { selectedClass } = useSelectedClass();
  const { push } = useLocalizedNavigation();
  const searchParams = useSearchParams();
  const currentLang = searchParams.get("lang") || searchParams.get("language");


  // Determine steps from form data or use default
  const formSteps = form?.fields?.steps || [];

  // On details page: skip the last form step (class/program/location) – shown as info card instead.
  // On listing page with class selected: show first 2 form steps only.
  const displayFormSteps = isDetailsPage
    ? (formSteps.length > 1 ? formSteps.slice(0, -1) : formSteps)
    : selectedClass ? formSteps.slice(0, Math.min(formSteps.length, 2)) : formSteps;

  // On details page: step 1 = ClassInfoStep card, steps 2..N = displayFormSteps
  const totalSteps = isDetailsPage
    ? 1 + displayFormSteps.length
    : displayFormSteps.length;
  const maxStep = totalSteps + 1; // +1 for congratulations step

  // Helper: resolve the current form step object (null on details page step 1 = info card)
  const getEffectiveFormStep = (s: number) => {
    if (isDetailsPage) {
      if (s <= 1 || s > totalSteps) return null;
      return displayFormSteps[s - 2]; // step 2 → displayFormSteps[0]
    }
    return s <= displayFormSteps.length ? displayFormSteps[s - 1] : null;
  };

  type DynamicStep = 1 | 2 | 3 | 4 | 5;
  const [step, setStep] = useState<DynamicStep>(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitMessage, setSubmitMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  const [formData, setFormData] = useState<Record<string, string | boolean>>({});
  const [formIds, setFormIds] = useState<Record<string, string>>({});
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [dynamicOptions, setDynamicOptions] = useState<Record<string, FormFieldOption[]>>({});

  const [loadingOptions, setLoadingOptions] = useState<Record<string, boolean>>({});
  const [submittedData, setSubmittedData] = useState<Array<Record<string, string>> | null>(null);
  const [registrationId, setRegistrationId] = useState<string | null>(null);
  const [selectedClassData, setSelectedClassData] = useState<any>(null);
  const [hasAutoFilled, setHasAutoFilled] = useState(false);
  const [hasPrefilledFromCookie, setHasPrefilledFromCookie] = useState(false);

  // Cookie that remembers this form's entered values (per form/slug) so a
  // returning user's fields are prefilled. Keyed by form id so different forms
  // (home vs workshop) don't overwrite each other.
  const FORM_COOKIE_KEY = `ye_form_${form?.id || slug || "home"}`;

  // Class/location/program selection fields are context-specific — never
  // remembered (they should always reflect the current selection, not stale data).
  const isSelectionField = (fieldName: string) => {
    const f = fieldName.toLowerCase();
    return (
      f.includes("class") ||
      f.includes("choose") ||
      f.includes("program") ||
      f.includes("study") ||
      f.includes("location") ||
      f.includes("date") ||
      f.includes("group")
    );
  };

  // The formData keys (getFieldKey) that belong to selection fields — excluded
  // from the cookie so only personal details (name, email, phone, age…) persist.
  const selectionKeys = useMemo(() => {
    const keys = new Set<string>();
    formSteps.forEach((s) =>
      s.fields.forEach((fld) => {
        if (isSelectionField(fld.field)) keys.add(getFieldKey(s.order, fld.field));
      }),
    );
    return keys;
  }, [formSteps]);

  // Prefill personal fields from the saved cookie (once, when the form loads).
  useEffect(() => {
    if (hasPrefilledFromCookie || formSteps.length === 0) return;
    const saved = getJSONCookie<{
      formData?: Record<string, string | boolean>;
      formIds?: Record<string, string>;
    }>(FORM_COOKIE_KEY);
    const savedData = saved?.formData;
    const savedIds = saved?.formIds;
    if (savedData) {
      // Existing values (e.g. autofilled class/location) win over the cookie.
      setFormData((prev) => ({ ...savedData, ...prev }));
    }
    if (savedIds) {
      setFormIds((prev) => ({ ...savedIds, ...prev }));
    }
    setHasPrefilledFromCookie(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formSteps, hasPrefilledFromCookie]);

  // Persist the entered personal fields (not class selection / consent) to the cookie.
  const rememberFormValues = () => {
    const rememberData: Record<string, string | boolean> = {};
    const rememberIds: Record<string, string> = {};
    Object.entries(formData).forEach(([k, v]) => {
      if (selectionKeys.has(k) || k.startsWith("agree_step_")) return;
      rememberData[k] = v;
    });
    Object.entries(formIds).forEach(([k, v]) => {
      if (selectionKeys.has(k) || k.startsWith("agree_step_")) return;
      rememberIds[k] = v;
    });
    setJSONCookie(FORM_COOKIE_KEY, { formData: rememberData, formIds: rememberIds }, 30);
  };

  // Email validation regex
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  // Phone validation - accepts various formats
  const phoneRegex = /^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,5}[-\s\.]?[0-9]{1,4}$/;

  // Auto-scroll to form on details page mount
  useEffect(() => {
    if (isDetailsPage) {
      setTimeout(() => {
        const formEl = document.getElementById("registration-form");
        if (formEl) {
          formEl.scrollIntoView({ behavior: "smooth", block: "start" });
        }
      }, 300);
    }
  }, [isDetailsPage]);

  // Reset autofill flag when classDetailsCtx changes (for details page)
  useEffect(() => {
    if (isDetailsPage && classDetailsCtx) {
      console.log("[FormContent] ✓ classDetailsCtx received:", { id: classDetailsCtx.id, group_name: classDetailsCtx.group_name });
      setHasAutoFilled(false);
    }
  }, [classDetailsCtx, isDetailsPage]);

  // Helper function to strip HTML tags
  const stripHtmlTags = (str: string): string => {
    if (!str) return str;
    return str.replace(/<[^>]*>/g, "").trim();
  };

  // Autofill form when a class is selected (from context or fetched data)
  useEffect(() => {
    // On details page the info card shows class/program/location – no autofill needed.
    if (isDetailsPage) return;

    const dataToUse = selectedClass;

    if (!dataToUse || formSteps.length === 0 || hasAutoFilled) {
      return;
    }

    console.log("[FormContent] Starting autofill with data:", dataToUse);

    const lastStep = formSteps[formSteps.length - 1];
    if (!lastStep) return;

    // Find all relevant fields in the last step
    const classField = lastStep.fields.find(
      (f) =>
        f.field.toLowerCase().includes("class") ||
        f.field.toLowerCase().includes("choose") ||
        f.field.toLowerCase().includes("program") ||
        f.field.toLowerCase().includes("study")
    );
    const locationField = lastStep.fields.find((f) =>
      f.field.toLowerCase().includes("location")
    );
    const programField = lastStep.fields.find((f) =>
      f.field.toLowerCase().includes("program")
    );

    // Log all available fields in last step
    console.log("[FormContent] Last step fields:", lastStep.fields.map((f: any) => f.field));
    console.log("[FormContent] Found fields - class:", classField?.field, "location:", locationField?.field, "program:", programField?.field);

    // Also check step 2 for age field if it exists
    const step2 = formSteps[1];
    const ageField = step2?.fields.find((f) =>
      f.field.toLowerCase().includes("age")
    );

    const newFormData: Record<string, string | boolean> = {};
    const newFormIds: Record<string, string> = {};

    // Handle class field
    if (classField && dataToUse.group_name) {
      const k = getFieldKey(lastStep.order, classField.field);
      newFormData[k] = dataToUse.group_name.trim();
      newFormIds[k] = dataToUse.group_name.trim();
      console.log("[FormContent] Filled class field:", classField.field, "=", dataToUse.group_name.trim());
    } else {
      console.log("[FormContent] Class field not filled - classField:", !!classField, "group_name:", (dataToUse as any).group_name);
    }

    // Handle location field
    if (locationField) {
      const locationName = (dataToUse as any)?.p_o_s?.name || (dataToUse as any)?.location;
      console.log("[FormContent] Location lookup - p_o_s:", (dataToUse as any)?.p_o_s, "fallback location:", (dataToUse as any)?.location, "final value:", locationName);
      if (locationName) {
        const trimmedLocation = String(locationName).trim();
        const k = getFieldKey(lastStep.order, locationField.field);
        newFormData[k] = trimmedLocation;
        newFormIds[k] = trimmedLocation;
        console.log("[FormContent] Filled location field:", locationField.field, "=", trimmedLocation);
      } else {
        console.log("[FormContent] Location field found but no value - field:", locationField.field);
      }
    }

    // Handle program field
    if (programField) {
      let programName: string | undefined;
      const programValue = (dataToUse as any)?.program;
      if (typeof programValue === 'object') {
        // Try title first (with HTML tags), then name, then title from program object
        programName = programValue?.title || programValue?.name;
      } else if (typeof programValue === 'string') {
        programName = programValue;
      }
      if (programName) {
        // Strip HTML tags from program title
        const cleanProgram = stripHtmlTags(String(programName)).trim();
        if (cleanProgram) {
          const k = getFieldKey(lastStep.order, programField.field);
          newFormData[k] = cleanProgram;
          newFormIds[k] = cleanProgram;
          console.log("[FormContent] Filled program field:", programField.field, "=", cleanProgram);
        }
      }
    }

    // Handle age field
    if (ageField && step2) {
      const minAge = (dataToUse as any)?.min_age;
      if (minAge) {
        const trimmedAge = String(minAge).trim();
        const k = getFieldKey(step2.order, ageField.field);
        newFormData[k] = trimmedAge;
        newFormIds[k] = trimmedAge;
        console.log("[FormContent] Filled age field:", ageField.field, "=", trimmedAge);
      }
    }

    // Update form data
    setFormData((prev) => ({ ...prev, ...newFormData }));
    setFormIds((prev) => ({ ...prev, ...newFormIds }));

    setHasAutoFilled(true);
    console.log("[FormContent] Autofill completed with:", newFormIds);
  }, [classDetailsCtx, selectedClass, formSteps, hasAutoFilled, isDetailsPage]);

  // Fetch dynamic options for location and programs fields
  useEffect(() => {
    // On details page location is known from context – skip
    if (isDetailsPage) return;

    const fetchDynamicOptions = async () => {
      try {
        const currentFormStep = getEffectiveFormStep(step);
        if (!currentFormStep) return;

        for (const field of currentFormStep.fields) {
          if (field.type === "select") {
            if ((field.field.toLowerCase().includes("location") || field.field === "location") &&
              (!dynamicOptions[field.field] || dynamicOptions[field.field].length === 0)) {
              tryFetchLocations(field);
            }
          }
        }
      } catch (error) {
        console.error("[FormContent] Failed to fetch options:", error);
      }
    };

    const tryFetchLocations = async (field: any) => {
      setLoadingOptions(prev => ({ ...prev, [field.field]: true }));
      try {
        const response = await fetchLocationsAction(tenant?.zoho_franchise_id);
        if (response.success) {
          const locationOptions = response.data.map((loc: any) => {
            const trimmedName = loc.name.trim();
            return { id: trimmedName, name: trimmedName };
          });
          setDynamicOptions(prev => ({ ...prev, [field.field]: locationOptions }));
        }
      } catch (error) {
        console.error("[FormContent] Failed to fetch locations:", error);
      } finally {
        setLoadingOptions(prev => ({ ...prev, [field.field]: false }));
      }
    };

    if (displayFormSteps.length > 0) {
      fetchDynamicOptions();
    }
  }, [step, displayFormSteps, isDetailsPage, tenant]);

  // Ensure location is filled after location options are loaded (listing page only)
  useEffect(() => {
    if (isDetailsPage) return; // location handled via info card on details page
    const locationValue = selectedClass?.location;

    if (!locationValue || formSteps.length === 0 || !dynamicOptions) return;

    const lastStep = formSteps[formSteps.length - 1];
    if (!lastStep) return;

    const locationField = lastStep.fields.find((f) =>
      f.field.toLowerCase().includes("location")
    );

    if (locationField && dynamicOptions[locationField.field]?.length > 0) {
      const trimmedLocation = locationValue.trim();
      const k = getFieldKey(lastStep.order, locationField.field);
      setFormData(prev => ({ ...prev, [k]: trimmedLocation }));
      setFormIds(prev => ({ ...prev, [k]: trimmedLocation }));
    }
  }, [dynamicOptions, selectedClass?.location, isDetailsPage, formSteps]);

  // Fetch classes independently (no longer dependent on program or location)
  useEffect(() => {
    if (isDetailsPage) return; // class already known from context

    const fetchClasses = async () => {
      const currentFormStep = getEffectiveFormStep(step);
      if (!currentFormStep) return;

      const classesField = currentFormStep.fields.find(
        f => f.type === "select" && (
          f.field.toLowerCase().includes("class") || 
          f.field.toLowerCase().includes("date") ||
          f.field.toLowerCase().includes("program") ||
          f.field.toLowerCase().includes("study") ||
          f.field.toLowerCase().includes("group")
        )
      );

      if (!classesField) return;

      if (dynamicOptions[classesField.field] && dynamicOptions[classesField.field].length > 0) {
        return;
      }

      setLoadingOptions(prev => ({ ...prev, [classesField.field]: true }));
      try {
        const programIds = cwProgramId != null && cwProgramId !== "" ? [cwProgramId] : undefined;
        const response = await fetchClassesAction(tenant?.zoho_franchise_id, null, programIds);
        if (response.success) {
          // Filter by program_type so the workshop form only sees workshops and
          // the program/home form only sees study programs.
          const wantedType = slug === "workshop" ? "workshop" : "study";
          const filtered = response.data.filter(
            (cls: any) => cls?.program?.program_type === wantedType
          );

          const isWorkshopField = classesField.field.toLowerCase().includes("workshop");

          let options: FormFieldOption[];
          if (isWorkshopField) {
            // Workshop dropdown: dedupe by program so each workshop appears once.
            const seen = new Set<string | number>();
            options = [];
            for (const cls of filtered) {
              const program = (cls as any)?.program;
              if (!program || program.id == null) continue;
              if (seen.has(program.id)) continue;
              seen.add(program.id);
              const cleanTitle = stripHtmlTags(String(program.title || program.name || "")).trim();
              if (!cleanTitle) continue;
              options.push({
                id: cleanTitle,
                name: cleanTitle,
                image: program.image,
              });
            }
          } else {
            // Class/group dropdown: show each group individually.
            options = filtered.map((cls: any) => ({
              id: cls.group_name,
              name: cls.group_name,
              image: cls.program_logo,
              time: `${cls.start_date} | ${cls.start_time}`,
              fullData: cls,
            }));
          }

          setDynamicOptions(prev => ({
            ...prev,
            [classesField.field]: options,
          }));
        }
      } catch (error) {
        console.error("[FormContent] Failed to fetch classes:", error);
      } finally {
        setLoadingOptions(prev => ({ ...prev, [classesField.field]: false }));
      }
    };

    fetchClasses();
  }, [step, displayFormSteps, tenant, isDetailsPage, cwProgramId, slug]);

  const validateField = (fieldType: string, value: string, fieldName: string, isRequired: boolean = false, stepOrder?: number | string) => {
    const errorKey = stepOrder !== undefined ? getFieldKey(stepOrder, fieldName) : fieldName;

    if (!value && isRequired) {
      setErrors((prev) => ({ ...prev, [errorKey]: `${fieldName} is required` }));
      return;
    }

    if (fieldType === "email") {
      if (!value) {
        setErrors((prev) => ({ ...prev, [errorKey]: "" }));
      } else if (!emailRegex.test(value)) {
        setErrors((prev) => ({ ...prev, [errorKey]: "Please enter a valid email address" }));
      } else {
        setErrors((prev) => ({ ...prev, [errorKey]: "" }));
      }
    } else if (fieldType === "number") {
      if (!value) {
        setErrors((prev) => ({ ...prev, [errorKey]: "" }));
      } else if (!phoneRegex.test(value)) {
        setErrors((prev) => ({ ...prev, [errorKey]: "Please enter a valid phone number" }));
      } else {
        setErrors((prev) => ({ ...prev, [errorKey]: "" }));
      }
    } else if (fieldType === "text") {
      // Text validation - only letters, spaces, and hyphens allowed (for names)
      const textRegex = /^[a-zA-Z\s\-']*$/;
      if (!value) {
        setErrors((prev) => ({ ...prev, [errorKey]: "" }));
      } else if (!textRegex.test(value)) {
        setErrors((prev) => ({ ...prev, [errorKey]: `${fieldName} should only contain letters, spaces, and hyphens` }));
      } else {
        setErrors((prev) => ({ ...prev, [errorKey]: "" }));
      }
    }
  };

  const isCurrentStepValid = (): boolean => {
    // Info card step on details page is always valid
    if (isDetailsPage && step === 1) return true;

    const effectiveFormStep = getEffectiveFormStep(step);
    if (!effectiveFormStep) return true;

    const fieldsValid = effectiveFormStep.fields.every((field) => {
      const key = getFieldKey(effectiveFormStep.order, field.field);
      const value = formData[key];

      if (!value || String(value).trim() === "") return false;
      if (field.type === "email" && !emailRegex.test(String(value))) return false;
      if (field.type === "number" && !phoneRegex.test(String(value))) return false;

      if (field.type === "text") {
        const textRegex = /^[a-zA-Z\s\-']*$/;
        if (!textRegex.test(String(value))) return false;
      }

      if (errors[key]) return false;

      return true;
    });

    // Agreement checkbox is temporarily hidden (see FormRenderer) — not required for now
    const agreementRequired = false;
    const agreementValid = agreementRequired
      ? !!formData[`agree_step_${effectiveFormStep.order}`]
      : true;
    return fieldsValid && agreementValid;
  };

  const getAgreementText = (): string => {
    return form?.fields?.agree?.text || "I agree with the Data collection policy";
  };

  const normalizeFieldName = (fieldName: string): string => {
    let normalized = fieldName
      .toLowerCase()
      .replace(/['']/g, '')
      .replace(/\s+/g, '_')
      .replace(/[^a-z0-9_]/g, '');

    // The backend explicitly expects "choose_classes" for the class/date selection field
    if (
      normalized === 'choose_class' ||
      normalized === 'choose_classes' ||
      normalized === 'class' ||
      normalized.startsWith('class_') ||
      normalized === 'choose_date' ||
      normalized === 'date' ||
      normalized === 'group' ||
      normalized === 'select_classes' ||
      normalized === 'select_class' ||
      normalized === 'study_program'
    ) {
      return 'choose_classes';
    }

    // Also ensure program variations fall back to expected names if needed by backend
    if (normalized === 'program' || normalized === 'choose_program' || normalized === 'programs' || normalized === 'select_programs') {
      return 'programs';
    }

    if (normalized === 'location' || normalized === 'choose_location' || normalized === 'select_location') {
      return 'location';
    }

    return normalized;
  };

  const formatFormDataForSubmission = (): Array<Record<string, string>> => {
    const submissionData: Array<Record<string, string>> = [];

    // On details page we skip the last step here and add it synthetically later.
    // On listing page with selectedClass we must include all steps (including the hidden one) from formData.
    const stepsToProcess = isDetailsPage
      ? (formSteps.length > 1 ? formSteps.slice(0, -1) : formSteps)
      : formSteps;

    stepsToProcess.forEach((stepData, index) => {
      const stepEntry: Record<string, string> = {};

      const stepNumber = stepData.order || (index + 1);
      stepEntry[`step_${stepNumber}`] = stepData.heading.toLowerCase().replace(/\s+/g, "_");

      stepData.fields.forEach((field) => {
        const value = formData[getFieldKey(stepNumber, field.field)];
        if (value !== undefined && value !== "") {
          const normalizedFieldName = normalizeFieldName(field.field);
          let finalValue = String(value);

          if (field.field.toLowerCase().includes('age')) {
            finalValue = finalValue.replace(/\s*years?/gi, '').trim();
          }

          stepEntry[normalizedFieldName] = finalValue;
        }
      });

      submissionData.push(stepEntry);
    });

    return submissionData;
  };

  const handleConfirm = async () => {
    if (isCurrentStepValid()) {
      if (step < maxStep - 1) {
        setStep((step + 1) as DynamicStep);
      } else {
        setIsSubmitting(true);
        setSubmitMessage(null);

        try {
          const submissionData = formatFormDataForSubmission();

          // On details page: the last form step was skipped (shown as info card).
          // Append a synthetic entry for it so the backend still receives all 3 steps.
          if (isDetailsPage && classDetailsCtx && formSteps.length > 0) {
            const lastFormStep = formSteps[formSteps.length - 1];
            if (lastFormStep) {
              const stepEntry: Record<string, string> = {};
              const stepNumber = lastFormStep.order || formSteps.length;
              stepEntry[`step_${stepNumber}`] = lastFormStep.heading.toLowerCase().replace(/\s+/g, "_");

              const cleanProgramName = stripHtmlTags(
                classDetailsCtx.program?.title || classDetailsCtx.program?.name || ""
              );

              lastFormStep.fields.forEach((field: any) => {
                const normalizedName = normalizeFieldName(field.field);
                const fieldLower = field.field.toLowerCase();

                if (fieldLower.includes("location")) {
                  stepEntry[normalizedName] = classDetailsCtx.p_o_s?.name || "";
                } else if (fieldLower.includes("study") || fieldLower.includes("class") || fieldLower.includes("choose")) {
                  stepEntry[normalizedName] = classDetailsCtx.group_name || "";
                } else if (fieldLower.includes("program")) {
                  stepEntry[normalizedName] = cleanProgramName;
                }
              });

              submissionData.push(stepEntry);
            }
          }


          // Build class details for submission
          let classDetails: {
            group_id?: number | string;
            franchise_id?: number | string;
            group_name: string;
            program_name: string;
            instructor_name?: string;
            start_date: string;
            start_time: string;
            end_time: string;
            day: string[];
            location: string;
            min_age: number;
            max_age: number;
            price?: string | number;
            price_name?: string;
            payer_id?: string | number;
            invoice_tax_value?: string | number;
            invoice_tax_label?: string;
            company_name?: string;
            company_address?: string;
          } | undefined = undefined;

          if (isDetailsPage && classDetailsCtx) {
            // On details page: build from context (class was shown as info card)
            setSelectedClassData(classDetailsCtx);
            classDetails = {
              group_id: classDetailsCtx.id,
              franchise_id: classDetailsCtx.franchise_id,
              group_name: classDetailsCtx.group_name,
              program_name: stripHtmlTags(classDetailsCtx.program?.title || classDetailsCtx.program?.name || ''),
              instructor_name: classDetailsCtx.instructors?.[0]?.name || '',
              start_date: classDetailsCtx.start_date,
              start_time: classDetailsCtx.start_time,
              end_time: classDetailsCtx.end_time,
              day: classDetailsCtx.day || [],
              location: classDetailsCtx.p_o_s?.name || classDetailsCtx.p_o_s?.location || '',
              min_age: classDetailsCtx.min_age,
              max_age: classDetailsCtx.max_age,
              price: classDetailsCtx.value ?? classDetailsCtx.price,
              price_name: classDetailsCtx.fee_basis,
              payer_id: classDetailsCtx.payer_id,
              invoice_tax_value: classDetailsCtx.invoice_tax || classDetailsCtx.franchise?.invoice_tax_value,
              invoice_tax_label: classDetailsCtx.invoice_tax_label || classDetailsCtx.franchise?.invoice_tax_label,
              company_name: classDetailsCtx.franchise?.company_name,
              company_address: classDetailsCtx.franchise?.company_address };
          } else {
            // On listing page: find the class field by content.
            //
            // Class options always carry `fullData` (set in fetchClasses), location options don't.
            // So we scan dynamicOptions for the first field whose options have `fullData`, then
            // match the user's selected value against that field's options.
            let classFieldName: string | undefined;
            let selectedClassOption: any;

            for (const [fieldKey, options] of Object.entries(dynamicOptions)) {
              if (!Array.isArray(options) || options.length === 0) continue;
              if (!(options as any[]).some(o => o?.fullData)) continue; // not the class field

              // dynamicOptions is keyed by raw field name; formData is step-scoped.
              // Find which step owns this field to resolve the scoped key.
              const owningStep = formSteps.find(s => s.fields.some(f => f.field === fieldKey));
              if (!owningStep) continue;
              const userValue = formData[getFieldKey(owningStep.order, fieldKey)];
              if (!userValue) continue;

              const match = (options as any[]).find(o =>
                o?.name === userValue ||
                o?.id === userValue ||
                o?.fullData?.id === userValue ||
                o?.fullData?.group_name === userValue
              );

              if (match) {
                classFieldName = fieldKey;
                selectedClassOption = match;
                break;
              }
            }

            if (classFieldName) {
              if (selectedClassOption && selectedClassOption.fullData) {
                const classData = selectedClassOption.fullData;
                setSelectedClassData(classData);
                classDetails = {
                  group_id: classData.id,
                  franchise_id: classData.franchise_id,
                  group_name: classData.group_name,
                  program_name: classData.program?.title || classData.program?.name || '',
                  instructor_name: classData.instructor_list?.[0]?.name || '',
                  start_date: classData.start_date,
                  start_time: classData.start_time,
                  end_time: classData.end_time,
                  day: classData.day || [],
                  location: classData.p_o_s?.name || classData.p_o_s?.location || '',
                  min_age: classData.min_age,
                  max_age: classData.max_age,
                  price: classData.value ?? classData.price,
                  price_name: classData.fee_basis,
                  payer_id: classData.payer_id,
                  invoice_tax_value: classData.invoice_tax || classData.franchise?.invoice_tax_value,
                  invoice_tax_label: classData.invoice_tax_label || classData.franchise?.invoice_tax_label,
                  company_name: classData.franchise?.company_name,
                  company_address: classData.franchise?.company_address };
              }
            }
          }

          // Build payload
          const submitPayload = {
            form_id: form?.id || '',
            form_data: submissionData,
            slug: slug || 'home',
            class_details: classDetails };

          const response = await submitFormAction(submitPayload);

          if (response.status) {
            // Remember this user's entered details for prefill next time.
            rememberFormValues();
            const extractedRegistrationId = 'submission_id' in response
              ? (response as any).submission_id
              : ('data' in response)
                ? (response as any).data?.id || (response as any).data?.registration_id
                : null;

            setSubmittedData(submissionData);
            setRegistrationId(extractedRegistrationId);
            setSubmitMessage({ type: 'success', text: response.message });

            if (extractedRegistrationId) {
              if (slug === 'workshop') {
                push(`/thank-you/${extractedRegistrationId}`);
              } else {
                const targetClassId = classDetails?.group_id || classDetailsCtx?.id;
                if (targetClassId) {
                  push(`/class-registration/${targetClassId}?submission_id=${extractedRegistrationId}`);
                } else {
                  push(`/thank-you/${extractedRegistrationId}`);
                }
              }
            }
          } else {
            setSubmitMessage({ type: 'error', text: response.message });
          }

        } catch (error) {
          setSubmitMessage({ type: 'error', text: 'An error occurred while submitting the form' });
        } finally {
          setIsSubmitting(false);
        }
      }
    }
  };


  const currentFormStep = getEffectiveFormStep(step);
  const currentHeading = form?.name || currentFormStep?.main_heading || "";
  const currentSubheading = form?.description || currentFormStep?.main_subheading || "";

  // No disabled fields needed – on details page the last step is replaced by the info card
  const disabledFields: Record<string, boolean> = {};

  return (
    <div className="max-w-[1300px] mx-auto w-full flex flex-col md:flex-row items-center justify-center gap-8 md:gap-[20px] lg:gap-[90px] xl:gap-[111px] px-12 md:px-16 lg:px-32 xl:px-0 mt-[12px] md:mt-[-36] lg:mt-[-4px] xl:mt-[-10px] 2xl:mt-[-10px] mb-5 from-outer-wrapper">
      {/* Right image */}
      <div className="relative flex justify-center items-center w-full md:order-2 h-full z-70">
        <Image
          src={form?.form_setting?.featured_image || withCDN("/teacher.png")}
          alt="Teacher desktop"
          width={620}
          height={620}
          className="lg:block hidden md:absolute max-w-[640px] xl:w-[640px] lg:w-[50dvw] sm:w-[40dvw] w-[80dvw] sm:top-[-130px] lg:top-[-238px] xl:top-[-230px] xl:right-[0px] md:right-[-100px] rounded-full object-cover"
        />
        <Image
          src={form?.form_setting?.featured_image || withCDN("/teacher_two.png")}
          alt="Teacher tab"
          width={620}
          height={620}
          className="block lg:hidden object-contain md:absolute max-w-[600px] h-[380px] md:h-[400px] xl:w-[50dvw] md:w-[70dwv] sm:w-[40dvw] w-[80dvw]  sm:top-[-300px] md:top-[-180px]  md:right-[-30] "
        />
      </div>

      {/* Form */}
      <div
        className={`flex flex-col lg:mt-24 xl:mt-46 md:mt-26 items-center gap-4 md:gap-1 w-full md:max-w-[500px] lg:max-w-[600px]  md:order-1 h-auto overflow-visible footer-form-wrapper ${
          slug === "workshop"
            ? "xl:max-w-[416px] xl:ml-[65px]"
            : "xl:max-w-[400px] xl:ml-[75px]"
        }`}
      >
        <DynamicHeader
          heading={currentHeading}
          subheading={currentSubheading}
          step={step}
          totalSteps={totalSteps}
          className="mt-1 md:mt-13 lg:mt-24 xl:mt-16"
        />

        {submitMessage && (
          <div className={`w-full p-3 rounded-lg text-center text-sm mb-4 ${submitMessage.type === 'success'
            ? 'bg-green-100 text-green-700 border border-green-300'
            : 'bg-red-100 text-red-700 border border-red-300'
            }`}>
            {submitMessage.text}
          </div>
        )}

        <AnimatePresence mode="wait">
          {/* Step 1 on details page: show class info card */}
          {isDetailsPage && step === 1 && classDetailsCtx && (
            <AnimatedStep keyName="class-info">
              <ClassInfoStep
                classDetails={classDetailsCtx}
                onConfirm={handleConfirm}
                nextText={Array.isArray(form?.fields?.cta) ? form.fields.cta.find((c: any) => c.field?.toLowerCase() === 'next_button' || c.field?.toLowerCase() === 'next button')?.text || "Next" : "Next"}
              />
            </AnimatedStep>
          )}

          {/* Regular form steps */}
          {!(isDetailsPage && step === 1) && currentFormStep && (
            <AnimatedStep keyName={`step${step}`}>
              <DynamicFormStep
                step={currentFormStep}
                formData={formData}
                formIds={formIds}
                errors={errors}
                onChange={(fieldName: string, value: string | boolean, fieldId?: string) => {
                  // Agreement keys (agree_step_N) are already step-scoped by the renderer;
                  // pass them through unmodified.
                  const isAgreementKey = fieldName.startsWith("agree_step_");
                  const key = isAgreementKey ? fieldName : getFieldKey(currentFormStep.order, fieldName);
                  setFormData((prev) => ({ ...prev, [key]: value }));

                  // Note: `fieldId !== undefined` (not just truthy) so clearing a
                  // select (fieldId = "") resets formIds — the dropdown's display
                  // value reads from formIds, so an empty string must propagate.
                  if (fieldId !== undefined && typeof value === "string") {
                    setFormIds((prev) => ({ ...prev, [key]: fieldId }));
                  }

                  if (typeof value === "string" && !isAgreementKey) {
                    validateField(
                      currentFormStep.fields.find((f) => f.field === fieldName)?.type || "text",
                      value,
                      fieldName,
                      false,
                      currentFormStep.order
                    );
                  }
                }}
                onValidate={(fieldType, value, fieldName, isRequired) =>
                  validateField(fieldType, value, fieldName, isRequired, currentFormStep.order)
                }
                agreementText={getAgreementText()}
                policyFranchiseeId={classDetailsCtx?.franchise_id?.toString()}
                policyLanguage={currentLang}
                valid={isCurrentStepValid()}
                onConfirm={handleConfirm}
                onGoBack={() => setStep((step - 1) as DynamicStep)}
                isSubmitting={isSubmitting}
                dynamicOptions={dynamicOptions}
                loadingOptions={loadingOptions}
                disabledFields={disabledFields}
                isDetailsPage={isDetailsPage}
                classDetails={classDetailsCtx}
                showGoBack={isDetailsPage ? step > 1 : undefined}
                confirmText={step === totalSteps
                  ? (Array.isArray(form?.fields?.cta) ? form.fields.cta.find((c: any) => c.field?.toLowerCase() === 'submit_button' || c.field?.toLowerCase() === 'submit button')?.text || "Register" : "Register")
                  : (Array.isArray(form?.fields?.cta) ? form.fields.cta.find((c: any) => c.field?.toLowerCase() === 'next_button' || c.field?.toLowerCase() === 'next button')?.text || "Next" : "Next")}
                totalSteps={totalSteps}
              />
            </AnimatedStep>
          )}
        </AnimatePresence>

      </div>
    </div>
  );
}

// Export with memo to fix Turbopack static flag issue
export const FormContent = memo(FormContentComponent);
