"use client";

import Image from "next/image";
import { motion, AnimatePresence } from "framer-motion";
import { Button } from "@/src/components/ui/button";
import { withCDN } from "@/src/lib/utils";
import { getFeeBasisPriceLabel } from "@/src/lib/utils/registrationPricing";
import type { FormStep, FormFieldOption } from "@/src/lib/services/formsService";
import { useEffect, useRef, useState } from "react";
import { useWorkshops } from "@/src/lib/context/WorkshopsContext";
import { convertTo24Hour } from "@/src/lib/utils/formatTime";
import { ClearButton } from "@/src/components/ui/ClearButton";
import PhoneInput from "./PhoneInput";
import ThemedDatePicker from "@/src/components/ui/ThemedDatePicker";
import PolicyAgreement from "@/src/components/ui/PolicyAgreement";
import LanguageAwareLink from "@/src/lib/utils/LanguageAwareLink";

// Step-scoped storage key. Different steps may share a field name (e.g. parent
// "Name" in step 1 and child "Name" in step 2) — without scoping, they'd
// overwrite each other in formData/formIds/errors.
export const getFieldKey = (stepOrder: number | string, fieldName: string) =>
  `step_${stepOrder}__${fieldName}`;

export function DynamicHeader({
  heading,
  subheading,
  step,
  totalSteps,
  className = "",
}: {
  heading: string;
  subheading: string;
  step: number;
  totalSteps: number;
  className?: string;
}) {
  return (
    <div id="form-heading" className={`relative w-full text-center ${className}`}>
      <h2 className="text-[30px] md:text-[30px] lg:text-[40px] xl:text-[40px] 2xl:text-[40px] leading-tight font-bold text-[#58585A] uppercase tracking-wide lg:mt-[-20px] 2xl:mt-[-2px]">
        {heading}
      </h2>
      <p className="text-[14px] md:text-[14px] lg:text-[20px] xl:text-[18px] 2xl:text-[18px] text-[#58585A] mb-2">
        {subheading}
      </p>
      <div className="flex items-center gap-[3px] mt-1 md:mt-1 w-full justify-center h-[4px]">
        {Array.from({ length: totalSteps }, (_, index) => {
          const i = index + 1;

          return (
            <div
              key={i}
              className={`h-[4px] w-full rounded-[10px] transition-all duration-300 ${i < step
                ? "bg-[#00A538]"   // completed 
                : i === step
                  ? "bg-[#0097DC]"   // current 
                  : "bg-[#BDBDBD]"   // upcoming
                }`}
            />
          );
        })}
      </div>
    </div>
  );
}

// Renders the agreement sentence, turning "Privacy Policy" / "Terms of Use" into
// links that open the given pages in a new tab (instead of the policy modal).
function linkifyToPages(
  text: string,
  privacyHref: string,
  termsHref: string,
  linkClassName: string,
) {
  const regex = /(Privacy Policy|Terms of Use)/gi;
  const nodes: React.ReactNode[] = [];
  let lastIndex = 0;
  let key = 0;
  let match: RegExpExecArray | null;

  while ((match = regex.exec(text)) !== null) {
    if (match.index > lastIndex) {
      nodes.push(text.slice(lastIndex, match.index));
    }
    const matched = match[0];
    const href = matched.toLowerCase() === "privacy policy" ? privacyHref : termsHref;
    nodes.push(
      <LanguageAwareLink
        key={key++}
        href={href}
        target="_blank"
        rel="noopener noreferrer"
        className={linkClassName}
      >
        {matched}
      </LanguageAwareLink>,
    );
    lastIndex = match.index + matched.length;
  }
  if (lastIndex < text.length) {
    nodes.push(text.slice(lastIndex));
  }
  return nodes;
}

function Checkbox({
  checked,
  onChange,
  text,
  franchiseeId,
  language,
  privacyHref,
  termsHref,
}: {
  checked: boolean;
  onChange: (checked: boolean) => void;
  text?: string;
  franchiseeId?: string | null;
  language?: string | null;
  /** When both hrefs are provided, links open these pages in a new tab
   * instead of the policy modal. */
  privacyHref?: string;
  termsHref?: string;
}) {
  const usePageLinks = !!privacyHref && !!termsHref;
  return (
    <div className="flex items-start gap-2 mt-2 md:mt-2 custom-checkbox">
      <input
        type="checkbox"
        checked={checked}
        onChange={(e) => onChange(e.target.checked)}
        className="w-[20px] h-[20px] md:w-[25px] md:h-[25px] border border-[#58585A] rounded-[6px]"
      />
      {usePageLinks ? (
        <span className="text-[#58585A] text-[14px] md:text-[14px]">
          {linkifyToPages(
            text || "",
            privacyHref!,
            termsHref!,
            "text-[#0097DC] cursor-pointer hover:underline",
          )}
        </span>
      ) : (
        <PolicyAgreement
          text={text || ""}
          franchiseeId={franchiseeId}
          language={language}
          className="text-[#58585A] text-[14px] md:text-[14px]"
        />
      )}
    </div>
  );
}

export function DynamicFormStep({
  step,
  formData,
  formIds,
  errors,
  onChange,
  onValidate,
  agreementText,
  valid,
  onConfirm,
  onGoBack,
  isSubmitting = false,
  dynamicOptions = {},
  loadingOptions = {},
  disabledFields = {},
  isDetailsPage = false,
  classDetails = null,
  showGoBack,
  confirmText,
  totalSteps,
  policyFranchiseeId,
  policyLanguage,
  showAgreement = false,
  agreementPrivacyHref,
  agreementTermsHref,
  hideStepHeading = false,
}: {
  step: FormStep;
  formData: Record<string, string | boolean>;
  formIds: Record<string, string>;
  errors: Record<string, string>;
  onChange: (fieldName: string, value: string | boolean, fieldId?: string) => void;
  onValidate: (fieldType: string, value: string, fieldName: string, isRequired?: boolean) => void;
  agreementText: string;
  valid: boolean;
  onConfirm: () => void;
  onGoBack: () => void;
  isSubmitting?: boolean;
  confirmText?: string;
  dynamicOptions?: Record<string, FormFieldOption[]>;
  loadingOptions?: Record<string, boolean>;
  disabledFields?: Record<string, boolean>;
  isDetailsPage?: boolean;
  classDetails?: any | null;
  showGoBack?: boolean;
  totalSteps: number;
  policyFranchiseeId?: string | null;
  policyLanguage?: string | null;
  showAgreement?: boolean;
  /** When provided, the agreement links open these pages in a new tab
   * instead of the policy modal. */
  agreementPrivacyHref?: string;
  agreementTermsHref?: string;
  /** Hide the "N. <heading>" step title line entirely. */
  hideStepHeading?: boolean;
}) {
  return (
    <div className="flex flex-col items-start gap-2 w-full mt-3 md:mt-1 overflow-visible relative z-10">
      {!hideStepHeading && step.heading && (
        <p className="text-[#58585A] text-[16px] xl:text-[20px] mt-[20px] mb-[10px]">
          {step.order}. {step.heading}
          {step.subheading && (
            <span className="text-[12px] xl:text-[14px] text-[#828282] ml-2 font-normal">
              {step.subheading.trim().startsWith("(") ? step.subheading : `(${step.subheading})`}
            </span>
          )}
        </p>
      )}
      {step.fields.map((field) => {
        const isDisabled = disabledFields?.[field.field] || false;
        const fieldKey = getFieldKey(step.order, field.field);

        // Generate age options for age field on details page
        let fieldOptions = dynamicOptions[field.field] || (typeof field.options[0] === 'string' ? (field.options as string[]).map(opt => ({ id: opt, name: opt })) : (field.options as FormFieldOption[]));

        if (isDetailsPage && field.type === "select" && field.field.toLowerCase().includes("age") && classDetails?.min_age && classDetails?.max_age) {
          const ageOptions = [];
          for (let age = classDetails.min_age; age <= classDetails.max_age; age++) {
            ageOptions.push({ id: age.toString(), name: age.toString() });
          }
          fieldOptions = ageOptions;
        }

        return (
          <div key={fieldKey} className="w-full">
            {field.type === "text" && (
              <div>
                <TextInput
                  placeholder={field.placeholder || field.text || field.field}
                  value={String(formData[fieldKey] || "")}
                  onChange={(e) => onChange(field.field, e.target.value)}
                  onBlur={() => onValidate("text", String(formData[fieldKey] || ""), field.field, field.required)}
                  onClear={() => onChange(field.field, "")}
                  disabled={isDisabled}
                />
                {errors[fieldKey] && (
                  <p className="text-red-500 text-[12px] md:text-[13px] mt-1 ml-4 ">
                    {errors[fieldKey]}
                  </p>
                )}
              </div>
            )}

            {field.type === "textarea" && (
              <div>
                <textarea
                  placeholder={field.placeholder || field.text || field.field}
                  value={String(formData[fieldKey] || "")}
                  onChange={(e) => onChange(field.field, e.target.value)}
                  onBlur={() => onValidate("textarea", String(formData[fieldKey] || ""), field.field, field.required)}
                  rows={field.rows || 3}
                  disabled={isDisabled}
                  className={`w-full border border-[#58585A] rounded-[22px] py-[12px] lg:py-[10px] md:py-[10px] px-[20px] md:px-[30px] text-[#828282] text-[14px] md:text-[16px] outline-none resize-none ${isDisabled ? "bg-gray-100 cursor-not-allowed opacity-60" : ""}`}
                />
                {errors[fieldKey] && (
                  <p className="text-red-500 text-[12px] md:text-[13px] mt-1 ml-4 ">
                    {errors[fieldKey]}
                  </p>
                )}
              </div>
            )}

            {field.type === "email" && (
              <div>
                <TextInputWithValidation
                  placeholder={field.placeholder || field.text || field.field}
                  type="email"
                  value={String(formData[fieldKey] || "")}
                  onChange={(e) => onChange(field.field, e.target.value)}
                  onBlur={() => onValidate("email", String(formData[fieldKey] || ""), field.field, field.required)}
                  onClear={() => onChange(field.field, "")}
                  error={errors[fieldKey]}
                  disabled={isDisabled}
                />
              </div>
            )}

            {field.type === "number" && (
              <div>
                <PhoneInput
                  placeholder={field.placeholder || field.text || field.field}
                  value={String(formData[fieldKey] || "")}
                  onChange={(combined) => onChange(field.field, combined)}
                  onBlur={() => onValidate("number", String(formData[fieldKey] || ""), field.field, field.required)}
                  error={errors[fieldKey]}
                  disabled={isDisabled}
                />
              </div>
            )}

            {field.type === "select" && (
              <div>
                <SelectDropdown
                  placeholder={field.placeholder || field.text || field.field}
                  value={String(formIds[fieldKey] || "")}
                  onChange={(value, optionId) => onChange(field.field, value, optionId)}
                  options={fieldOptions}
                  isLoading={loadingOptions[field.field] || false}
                  disabled={isDisabled}
                />
                {errors[fieldKey] && (
                  <p className="text-red-500 text-[12px] md:text-[13px] mt-1 ml-4">
                    {errors[fieldKey]}
                  </p>
                )}
              </div>
            )}

            {field.type === "date" && (
              <div>
                <ThemedDatePicker
                  placeholder={field.placeholder || "dd-mm-yyyy"}
                  value={String(formData[fieldKey] || "")}
                  onChange={(v) => onChange(field.field, v)}
                  onClear={() => onChange(field.field, "")}
                  disabled={isDisabled}
                />
                {errors[fieldKey] && (
                  <p className="text-red-500 text-[12px] md:text-[13px] mt-1 ml-4 ">
                    {errors[fieldKey]}
                  </p>
                )}
              </div>
            )}
          </div>
        );
      })}

      {/* Agreement — opt-in per form (hidden by default) */}
      {showAgreement && agreementText && (
        <Checkbox
          checked={!!formData[`agree_step_${step.order}`]}
          onChange={(agree) => onChange(`agree_step_${step.order}`, agree)}
          text={agreementText}
          franchiseeId={policyFranchiseeId}
          language={policyLanguage}
          privacyHref={agreementPrivacyHref}
          termsHref={agreementTermsHref}
        />
      )}


      {/* Confirm button */}
      <ConfirmButton valid={valid} onClick={onConfirm} text={confirmText || "Next"} isLoading={isSubmitting} />

      {/* Go Back */}
      {(showGoBack !== undefined ? showGoBack : step.order > 1) && (
        <button
          onClick={onGoBack}
          className="text-[#828282] text-[14px] md:text-[16px] underline mt-3 cursor-pointer back-step"
        >
          Go back
        </button>
      )}
    </div>
  );
}

export function AnimatedStep({
  children,
  keyName,
}: {
  children: React.ReactNode;
  keyName: string;
}) {
  return (
    <motion.div
      key={keyName}
      initial={{ x: 100, opacity: 0 }}
      animate={{ x: 0, opacity: 1 }}
      exit={{ x: -100, opacity: 0 }}
      transition={{ duration: 0.4 }}
      className="w-full"
    >
      {children}
    </motion.div>
  );
}

/* ---------- CLASS INFO STEP (Details Page Step 1) ---------- */

export function ClassInfoStep({
  classDetails,
  onConfirm,
  nextText = "Next",
}: {
  classDetails: any;
  onConfirm: () => void;
  nextText?: string;
}) {
  const programDataMap: Record<string, { image: string }> = {
    "ALGO BUDDY": { image: withCDN("/program-logo/logo_algo_buddy.svg") },
    "BIG BUILDERS": { image: withCDN("/program-logo/logo_big_builders.svg") },
    "SMARTIVO": { image: withCDN("/program-logo/logo_smartivo.svg") },
    "BRICKS CHALLENGE": { image: withCDN("/program-logo/logo_bricks_chalenge.svg") },
    "GALILEO TECHNICS": { image: withCDN("/program-logo/logo_galileo_technic.svg") },
    "GALILEO TECHNIC": { image: withCDN("/program-logo/logo_galileo_technic.svg") },
    "ALGO PLAY": { image: withCDN("/program-logo/logo_algo_play.svg") },
    "ROBO TOYS": { image: withCDN("/program-logo/logo_robo_toys.svg") },
    "ALGOC": { image: withCDN("/program-logo/logo_algo_c.svg") },
    "CAMPS": { image: withCDN("/program-logo/logo_big_builders.svg") },
  };

  const stripHtml = (str: string): string =>
    str ? str.replace(/<[^>]*>/g, "").trim() : "";

  const programName = stripHtml(
    classDetails?.program?.title || classDetails?.program?.name || ""
  );
  const programImage =
    programDataMap[programName.toUpperCase()]?.image ||
    classDetails?.program?.model_icon ||
    classDetails?.program?.image;

  const days = Array.isArray(classDetails?.day)
    ? classDetails.day.join(", ")
    : classDetails?.day || "";

  const rawUnitPrice = parseFloat(
    String(classDetails?.value ?? classDetails?.price ?? "0")
  );
  const formatMoney = (n: number) =>
    Number.isInteger(n) ? n.toString() : n.toFixed(2);

  const feeBasisPriceLabel = getFeeBasisPriceLabel(
    classDetails?.fee_basis ?? classDetails?.price_name
  );

  return (
    <div className="flex flex-col gap-4 w-full mt-3 md:mt-1">
      {/* Card */}
      <div className="w-full rounded-[20px] border border-[#D9D9D9] overflow-hidden bg-white shadow-md">

        {/* Program header row */}
        <div className="flex items-center gap-4 px-5 py-4 bg-gradient-to-r from-[#f0f9ff] to-[#e8f5ff] border-b border-[#D9D9D9]">
          {programImage && (
            <div className="flex-shrink-0 w-[67px] h-[47px] flex items-center justify-center">
              <img
                src={programImage}
                alt={programName}
                className="w-[67px] h-[45px] object-contain"
              />
            </div>
          )}
          <div>
            <p className="font-bold text-[17px] text-[#58585A] uppercase leading-tight">
              {programName}
            </p>
            <p className="text-[13px] text-[#0097DC] mt-0.5">
              Age: {classDetails?.min_age} – {classDetails?.max_age} years
            </p>
          </div>
        </div>

        {/* Detail rows */}
        <div className="px-5 py-4 flex flex-col gap-3">

          {/* Class Name */}
          <div className="flex items-start gap-3">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" className="text-[#0097DC] flex-shrink-0 mt-0.5">
              <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            <div>
              <p className="text-[12px] text-[#828282] ">Class</p>
              <p className="text-[14px] text-[#58585A] font-medium">{classDetails?.group_name}</p>
            </div>
          </div>

          {/* Location */}
          {classDetails?.p_o_s?.name && (
            <div className="flex items-start gap-3">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" className="text-[#0097DC] flex-shrink-0 mt-0.5">
                <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <circle cx="12" cy="9" r="2.5" stroke="currentColor" strokeWidth="2" />
              </svg>
              <div>
                <p className="text-[12px] text-[#828282]">Location</p>
                <p className="text-[14px] text-[#58585A]">{classDetails.p_o_s.name}</p>
              </div>
            </div>
          )}

          {/* Schedule */}
          {(days || classDetails?.start_time) && (
            <div className="flex items-start gap-3">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" className="text-[#0097DC] flex-shrink-0 mt-0.5">
                <rect x="3" y="4" width="18" height="18" rx="2" stroke="currentColor" strokeWidth="2" />
                <line x1="16" y1="2" x2="16" y2="6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                <line x1="8" y1="2" x2="8" y2="6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                <line x1="3" y1="10" x2="21" y2="10" stroke="currentColor" strokeWidth="2" />
              </svg>
              <div>
                <p className="text-[12px] text-[#828282] ">Schedule</p>
                <p className="text-[14px] text-[#58585A]">
                  {days}
                  {classDetails?.start_time && ` · ${convertTo24Hour(classDetails.start_time)}`}
                  {classDetails?.end_time && ` – ${convertTo24Hour(classDetails.end_time)}`}
                </p>
              </div>
            </div>
          )}

          {/* Price & frequency */}
          {rawUnitPrice > 0 && (
            <div className="flex items-start gap-3">
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                className="text-[#0097DC] flex-shrink-0 mt-0.5"
              >
                <path
                  d="M12 1v22M7 5h6a3 3 0 010 6H9a3 3 0 000 6h8"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
              <div>
                <p className="text-[12px] text-[#828282]">{feeBasisPriceLabel}</p>
                <p className="text-[14px] text-[#58585A] font-medium">
                  ${formatMoney(rawUnitPrice)}
                </p>
              </div>
            </div>
          )}

        </div>
      </div>

      {/* Continue button */}
      <ConfirmButton valid={true} onClick={onConfirm} text={nextText} />
    </div>
  );
}

function TextInput({
  placeholder,
  type = "text",
  value,
  onChange,
  onBlur,
  onClear,
  disabled = false,
}: {
  placeholder: string;
  type?: string;
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onBlur?: () => void;
  onClear?: () => void;
  disabled?: boolean;
}) {
  const showClear = !disabled && value !== "" && !!onClear;
  return (
    <div className="relative w-full">
      <input
        type={type}
        placeholder={placeholder}
        value={value}
        onChange={onChange}
        onBlur={onBlur}
        disabled={disabled}
        className={`w-full border border-[#58585A] rounded-full py-[12px] lg:py-[10px] md:py-[10px] pl-[20px] md:pl-[30px] ${showClear ? 'pr-[44px] md:pr-[50px]' : 'pr-[20px] md:pr-[30px]'} text-[#828282] text-[14px] md:text-[16px] outline-none ${disabled ? 'bg-gray-100 cursor-not-allowed opacity-60' : ''
          }`}
      />
      {showClear && (
        <ClearButton onClick={onClear} className="absolute right-[14px] md:right-[18px] top-1/2 -translate-y-1/2" />
      )}
    </div>
  );
}

export function TextInputWithValidation({
  placeholder,
  type = "text",
  value,
  onChange,
  onBlur,
  onClear,
  error,
  disabled = false,
}: {
  placeholder: string;
  type?: string;
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onBlur?: () => void;
  onClear?: () => void;
  error?: string;
  disabled?: boolean;
}) {
  const showClear = !disabled && value !== "" && !!onClear;
  return (
    <div className="w-full">
      <div className="relative w-full">
        <input
          type={type}
          placeholder={placeholder}
          value={value}
          onChange={onChange}
          onBlur={onBlur}
          disabled={disabled}
          className={`w-full border ${error ? 'border-red-500' : 'border-[#58585A]'} rounded-full py-[12px] lg:py-[10px] md:py-[10px] pl-[20px] md:pl-[30px] ${showClear ? 'pr-[44px] md:pr-[50px]' : 'pr-[20px] md:pr-[30px]'} text-[#828282] text-[14px] md:text-[16px] outline-none ${disabled ? 'bg-gray-100 cursor-not-allowed opacity-60' : ''
            }`}
        />
        {showClear && (
          <ClearButton onClick={onClear} className="absolute right-[14px] md:right-[18px] top-1/2 -translate-y-1/2" />
        )}
      </div>
      {error && (
        <p className="text-red-500 text-[12px] md:text-[13px] mt-1 ml-4 ">
          {error}
        </p>
      )}
    </div>
  );
}

export function SelectDropdown({
  placeholder,
  value,
  onChange,
  options,
  isLoading = false,
  disabled = false,
}: {
  placeholder: string;
  value: string;
  onChange: (value: string, optionId: string) => void;
  options: (string | FormFieldOption)[];
  isLoading?: boolean;
  disabled?: boolean;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const { workshops } = useWorkshops();

  const isOptionObject = options.length > 0 && typeof options[0] === 'object';

  // ✅ Comprehensive program data mapping with icons (Timings Removed)
  const programDataMap: Record<string, any> = {
    "ALGO BUDDY": { image: withCDN("/program-logo/logo_algo_buddy.svg") },
    "BIG BUILDERS": { image: withCDN("/program-logo/logo_big_builders.svg") },
    "SMARTIVO": { image: withCDN("/program-logo/logo_smartivo.svg") },
    "BRICKS CHALLENGE": { image: withCDN("/program-logo/logo_bricks_chalenge.svg") },
    "GALILEO TECHNICS": { image: withCDN("/program-logo/logo_galileo_technic.svg") },
    "GALILEO TECHNIC": { image: withCDN("/program-logo/logo_galileo_technic.svg") },
    "ALGO PLAY": { image: withCDN("/program-logo/logo_algo_play.svg") },
    "ROBO TOYS": { image: withCDN("/program-logo/logo_robo_toys.svg") },
    "ALGOC": { image: withCDN("/program-logo/logo_algo_c.svg") },
  };

  // ✅ Merge program data with options. STRICTLY uses static image, but API data for ageRange
  const enhancedOptions = isOptionObject
    ? (options as any[]).map((opt) => {
      // If it's a workshop field, try to find matching workshop data
      const workshopData = placeholder.toLowerCase().includes("workshop")
        ? workshops.find(w => w.id === opt.id || w.title === opt.name)
        : null;

      return {
        ...opt,
        image: workshopData?.activity_details?.image || programDataMap[opt.name]?.image || opt.image || opt.fullData?.program_logo, // Picks up workshop, static or API image
        ageRange: workshopData?.activity_details?.age || opt.ageRange || opt.age_range,
        time: opt.time || (opt.fullData ? `${opt.fullData.start_date} | ${opt.fullData.start_time}` : undefined), // Picks up the date/time
      };
    })
    : options;

  // Get display name for selected value
  const getDisplayName = () => {
    if (!value) return placeholder;

    if (isOptionObject) {
      const selected = (enhancedOptions as any[]).find(
        (opt) => opt.id === value
      );

      return selected?.name || placeholder;
    }

    return value;
  };

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleSelect = (option: string | any) => {
    if (isOptionObject) {
      onChange(option.name, option.id);
    } else {
      onChange(option as string, option as string);
    }
    setIsOpen(false);
  };

  const displayValue = getDisplayName();
  const hasValue = value && value !== "";

  // Dynamic Empty Message based on placeholder context
  const emptyMessage = (
    placeholder.toLowerCase().includes("class") || 
    placeholder.toLowerCase().includes("program") || 
    placeholder.toLowerCase().includes("study")
  ) ? "No classes found" : `No options found`;

  return (
    <div className="relative drop-btns w-full" ref={dropdownRef}>
      {/* Dropdown Button */}
      <button
        type="button"
        onClick={() => !isLoading && !disabled && setIsOpen(!isOpen)}
        disabled={isLoading || disabled}
        className={`w-full flex items-center border border-[#58585A] rounded-full py-[12px] lg:py-[10px] md:py-[10px] pl-[20px] md:pl-[30px] ${hasValue ? 'pr-[74px] md:pr-[86px]' : 'pr-[45px] md:pr-[50px]'} text-[14px] md:text-[16px] outline-none bg-white transition-all duration-200 text-left ${hasValue
          ? 'text-[#58585A] font-normal '
          : 'text-[#828282]'
          } ${isLoading || disabled ? 'opacity-60 cursor-not-allowed bg-gray-100' : 'hover:border-[#58585A] focus:border-[#58585A] cursor-pointer'} ${isOpen ? 'border-[#58585A] rounded-tl-[20px] rounded-tr-[20px] rounded-bl-none rounded-br-none border-b-0' : ''
          }`}

      >
        {isLoading ? `Loading ${placeholder}...` : displayValue}
      </button>

      {/* Clear selection button (shown only when a value is selected) */}
      {hasValue && !isLoading && !disabled && (
        <ClearButton
          onClick={() => {
            onChange("", "");
            setIsOpen(false);
          }}
          className="absolute right-[44px] md:right-[56px] top-1/2 -translate-y-1/2 z-10 !min-h-[22px]"
        />
      )}

      {/* Custom dropdown arrow */}
      <div className="absolute right-[20px] md:right-[30px] top-1/2 transform -translate-y-1/2 pointer-events-none">
        <motion.svg
          width="16"
          height="10"
          viewBox="0 0 16 10"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
          className={`transition-colors duration-200 ${hasValue ? 'text-[#0097DC]' : 'text-[#828282]'}`}
          animate={{ rotate: isOpen ? 180 : 0 }}
          transition={{ duration: 0.3 }}
        >
          <path
            d="M1 1L8 8L15 1"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </motion.svg>
      </div>

      {/* Dropdown List */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, y: -10, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -10, scale: 0.95 }}
            transition={{ duration: 0.2 }}
            className="absolute z-50 w-full mt-0 bg-white border-1 border-[#58585A] rounded-[23px] shadow-2xl  max-h-[280px] px-5 select-dropdown"
          >
            <div className="overflow-y-auto max-h-[280px] custom-dropdown-scrollbar pr-1">
              {/* Handle empty options state */}
              {options.length === 0 ? (
                <div className="w-full text-center px-[20px] py-[20px] text-[14px] md:text-[16px] text-[#828282]">
                  {emptyMessage}
                </div>
              ) : isOptionObject ? (
                (enhancedOptions as any[]).map((option, index) => (
                  <motion.button
                    key={option.id}
                    type="button"
                    initial={{ opacity: 0, x: -20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: index * 0.03 }}
                    onClick={() => handleSelect(option)}
                    className={`w-full text-center px-[20px] md:px-[0px] py-[14px] text-[14px] md:text-[16px] transition-all duration-200 border-b border-[#D9D9D9] last:border-b-0 ${value === option.id
                      ? 'bg-white text-[#00a7e1] font-semibold'
                      : 'text-[#58585A] hover:from-[#E8F0F7] hover:to-[#F0F8FF]'
                      }`}
                  >
                    <div className="flex items-center gap-3">
                      {value === option.id && (
                        <motion.div
                          initial={{ scale: 0 }}
                          animate={{ scale: 1 }}
                          transition={{ type: "spring", stiffness: 500, damping: 25 }}
                          className="flex-shrink-0 bg-[#0097DC] rounded-[50px]"
                        >
                          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="drop-shadow-sm">
                            <circle cx="8" cy="8" r="7" fill="white" fillOpacity="0.3" />
                            <path d="M4 8L7 11L12 5" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                          </svg>
                        </motion.div>
                      )}
                      <div className="flex items-center gap-4 dropdown-img w-full">
                        {/* Image Container */}
                        {option.image && (
                          <div className="flex-shrink-0 w-[80px] h-[55px] relative rounded-lg overflow-hidden border border-[#f0f0f0] bg-gray-50 shadow-sm">
                            <img
                              src={option.image}
                              alt={option.name}
                              className="w-full h-full object-contain"
                            />
                          </div>
                        )}

                        {/* Text Content */}
                        <div className="flex flex-col text-left items-start flex-grow">
                          <span className="font-medium text-[16px] text-[#58585A] leading-tight">
                            {option.name}
                          </span>
                          {option.ageRange && (
                            <span className="text-[13px] text-[#0097DC] mt-1 font-light">
                              Age: {option.ageRange}
                            </span>
                          )}
                          {option.time && (
                            <span className="text-[13px] text-[#828282] mt-0.5 font-light">
                              {option.time}
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                  </motion.button>
                ))
              ) : (
                (options as string[]).map((option, index) => (
                  <motion.button
                    key={index}
                    type="button"
                    initial={{ opacity: 0, x: -20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: index * 0.03 }}
                    onClick={() => handleSelect(option)}
                    className={`w-full !text-left px-[10px] md:px-[0px] py-[14px] text-[14px] md:text-[16px] transition-all duration-200 border-b border-[#D9D9D9] last:border-b-0  ${value === option
                      ? 'bg-white text-[#00a7e1] font-semibold'
                      : 'text-[#58585A] hover:bg-gradient-to-r hover:from-[#E8F0F7] hover:to-[#F0F8FF]'
                      }`}
                  >
                    <div className="flex items-center gap-3">
                      {/* Fixed-width slot, rendered for every row so the tick on
                          the selected one can't push its label out of line. */}
                      <span className="w-4 h-4 flex-shrink-0 flex items-center justify-center">
                        {value === option && (
                          <motion.div
                            initial={{ scale: 0 }}
                            animate={{ scale: 1 }}
                            transition={{ type: "spring", stiffness: 500, damping: 25 }}
                            className="bg-[#0097DC] rounded-[50px] flex"
                          >
                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="drop-shadow-sm">
                              <circle cx="8" cy="8" r="7" fill="white" fillOpacity="0.3" />
                              <path d="M4 8L7 11L12 5" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                            </svg>
                          </motion.div>
                        )}
                      </span>
                      <span className="truncate">{option}</span>
                    </div>
                  </motion.button>
                ))
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}



export function ConfirmButton({
  valid,
  onClick,
  text,
  isLoading = false,
}: {
  valid: boolean;
  onClick: () => void;
  text: string;
  isLoading?: boolean;
}) {
  return (
    <Button
      onClick={onClick}
      disabled={!valid || isLoading}
      className={`w-full h-12 md:h-12 rounded-full flex justify-center items-center gap-2 mt-4 text-[16px] transition-colors cursor-pointer ${(valid && !isLoading)
        ? "bg-[#0097DC] text-white hover:bg-[#0082c0]"
        : "bg-[#E0E0E0] text-[#828282]"
        }`}
    >
      {!isLoading && (
        <Image
          src={valid ? withCDN("/gear.png") : withCDN("/gear-grey.png")}
          alt="Confirm icon"
          width={20}
          height={20}
        />
      )}
      <span>{isLoading ? "Submitting..." : text}</span>
    </Button>
  );
}
