"use client";

import React, { useState, useEffect, useMemo, useCallback } from "react";
import dynamic from "next/dynamic";
import { useRouter, useSearchParams } from "next/navigation";

import { useWizardContext } from "./wizardContext";
import type {
  WizardData,
  TabGroup,
  StepComponentProps,
  Step,
  StepStatus,
} from "./wizardTypes";
import ConfirmExitModal from "./ConfirmExitModal";
import VisionBoard from "./visionBoard";
import GroupNavigation from "./GroupNavigation";
import StepNavigation from "./StepNavigation";
import StepInfoPanel from "./StepInfoPanel";
import NavButtons from "./NavButtons";
import { postFormData } from "@/utils/postFormData";
import { getUserSessionId } from "@/utils/helper";


interface WizardProps {
  wizardData: WizardData;
  startPath: string;
}

export default function Wizard({ wizardData, startPath }: WizardProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { state } = useWizardContext();
  const externalId = searchParams.get("external");

  // === State ===
  const [showExitModal, setShowExitModal] = useState(false);
  const [isStepValid, setIsStepValid] = useState(true);
  const [activeGroupIdx, setActiveGroupIdx] = useState(0);
  const [activeStepIdx, setActiveStepIdx] = useState(0);
  const [stepStatus, setStepStatus] = useState<Record<string, StepStatus>>({});
  const [isStepInfoVisible, setStepInfoVisible] = useState(false);

  // Clean path for modal title
  const cleanStartPath = useMemo(
    () => startPath.replace(/[-\s]/g, " "),
    [startPath],
  );

  // Filter visible steps based on conditions and current state
  const filteredSteps = useMemo(() => {
    const group = wizardData.groups[activeGroupIdx];
    return (
      group?.steps.filter((step) =>
        step.condition
          ? state[step.condition.key] === step.condition.value
          : true,
      ) ?? []
    );
  }, [wizardData.groups, activeGroupIdx, state]);

  const currentStep = filteredSteps[activeStepIdx];

  // Dynamic step component import, memoized on component name
  const CurrentStepComponent = useMemo(() => {
    if (!currentStep?.component) return null;
    return dynamic<StepComponentProps>(
      () => import(`./${currentStep.component}`),
      { loading: () => <p></p>, ssr: false },
    );
  }, [currentStep?.component]);

  // Disable future groups until current group’s steps are done
  const isGroupDisabled = useCallback(
    (groupIdx: number) => {
      if (groupIdx <= activeGroupIdx) return false;
      const currentGroupSteps = wizardData.groups[activeGroupIdx].steps.filter(
        (step) =>
          !step.condition || state[step.condition.key] === step.condition.value,
      );
      return !currentGroupSteps.every((step) => stepStatus[step.id] === "done");
    },
    [wizardData.groups, activeGroupIdx, state, stepStatus],
  );

  // Load saved group/step from URL or localStorage on mount or state changes
  useEffect(() => {
    const savedGroupId =
      searchParams.get("group") || localStorage.getItem("wizardGroup");
    const savedStepId =
      searchParams.get("step") || localStorage.getItem("wizardStep");

    let foundGroupIdx = wizardData.groups.findIndex(
      (g) => g.id === savedGroupId,
    );
    foundGroupIdx = foundGroupIdx !== -1 ? foundGroupIdx : 0;

    const visibleSteps =
      wizardData.groups[foundGroupIdx]?.steps.filter(
        (step) =>
          !step.condition || state[step.condition.key] === step.condition.value,
      ) ?? [];

    let foundStepIdx = visibleSteps.findIndex((s) => s.id === savedStepId);
    foundStepIdx = foundStepIdx !== -1 ? foundStepIdx : 0;

    setActiveGroupIdx(foundGroupIdx);
    setActiveStepIdx(foundStepIdx);
  }, [wizardData.groups, searchParams, state]);

  useEffect(() => {
    if (externalId) {
      fetchExternalWizardData(externalId);
    }
  }, [externalId]);

  const fetchExternalWizardData = async (id: string) => {
    try {
      const response = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/co-creation/wizard/${id}`);
      const data = await response.json();

     

      // Example: pre-fill localStorage or context
      if (data) {
      
       //// localStorage.setItem("genderExpression", data.data.gender || "");
       //// localStorage.setItem("categoryName", data.category_name || "");
        // ... and so on
      }


    } catch (error) {
      console.error("Failed to fetch wizard data:", error);
    }
  };

  type PayLoadData = {
    stepId: string;
    step_name?: string;
    step_number?: number;
    vibe?: any;
    gender?: string;
    category_name?: string;
    category_type?: string;
    category_id?: string;
    sub_category_id?: string;
    category_single?: string;
    category_single_child?: string;
    silhouette_id?: string;
    fabric_family_id?: string;
    preferred_fabric?: string;
    selected_path_id?: string;
    wizard_step?: string;
    preferred_fabric_color?: string;
    choose_artwork_mode?: string;
    artwork_image?: string;
    technique_category?: string;
    artwork_technique_child?: string;
    artwork_prominent_id?: string;
    artwork_placement_id?: string;
    piece_imagine?: string;
    piece_note_share_artwork?: string;
    art_style?: string;
    art_work?: string;
    stepData?: object;
    session_id?: string;
    measurement?: any;
    standard_measurement?: any;
    custom_measurement?: any;
    external_id?: string;
    wizard_group?: string;
    selected_path_id_2?: string;
    outwear_category_id?: string;
    bottom_category_id?: string;
    vest_category_id?: string;
    bottom_silhouette_id?: string;
    outwear_silhouette_id?: string;
    category_basic?: string;
  };

  const saveStepDataToApi = useCallback(
    async (stepId: string) => {
      const stepData = localStorage.getItem(stepId);
      //console.log("Saving step data for:", stepId, stepData);
      ///return false; // 🔥 Remove this line to enable saving
      // if (!stepData) return;

      let payLoadData: PayLoadData;
      if (stepId === "define_vibe") {
        const vibeData = localStorage.getItem("DefineVibe");
        const vibeArray = vibeData ? JSON.parse(vibeData) : [];
        
        payLoadData = {
            stepId,
            step_name: "Define Vibe",
            step_number: 1,
            selected_path_id_2: localStorage.getItem("selectedPathId") || "",
            wizard_group: localStorage.getItem("wizardGroup") || "",
            vibe: vibeArray.join(","), // Convert array to comma-separated string
        };
        
        console.log("Saving define_vibe step:", payLoadData);
      } else if (stepId === "gender_expression") {
        payLoadData = {
          stepId,
          step_name: "Gender Expression",
          step_number: 2,
          gender: localStorage.getItem("genderExpression") || "",
        };
        // localStorage.removeItem("DefineVibe");
        
      } else if (stepId === "category_listing") {
        payLoadData = {
          stepId,
          step_name: "Category Listing",
          step_number: 3,
          category_name: localStorage.getItem("categoryName") || "",
          category_type: localStorage.getItem("CategoryType") || "",
          category_id: localStorage.getItem("categoryId") || "",
        };
        localStorage.removeItem("genderExpression");
      } else if (stepId === "category_single") {
        payLoadData = {
          stepId,
          step_name: "Category Single",
          step_number: 4,
          sub_category_id: localStorage.getItem("subcategoryId") || "",
          category_single: localStorage.getItem("CategorySingle") || "",
        };
      } else if (
        stepId === "category_single_child"
      ) {
        payLoadData = {
          stepId,
          step_name: "Category Single Child",
          step_number: 5,
          category_single_child:
          localStorage.getItem("categorySingleChild") || "",
          silhouette_id: localStorage.getItem("silhouette") || "",
          outwear_category_id: localStorage.getItem("silhouette") || "",
        };

        // localStorage.removeItem("CategorySingle");
        // localStorage.removeItem("subcategoryId");

      } else if (stepId === "fabric_family") {
        payLoadData = {
          stepId,
          step_name: "Fabric Family",
          step_number: 6,
          fabric_family_id: localStorage.getItem("fabricFamily") || "[]",
        };
      } else if (stepId === "preferred_fabric") {
        payLoadData = {
          stepId,
          step_name: "Preferred Fabric",
          step_number: 7,
          preferred_fabric: localStorage.getItem("preferredFabric") || "[]",
          selected_path_id: localStorage.getItem("selectedPathId") || "",
          wizard_step: localStorage.getItem("wizardStep") || "",
        };

        localStorage.removeItem("fabricFamily");

      } else if (stepId === "preferred_fabric_color") {
        payLoadData = {
          stepId,
          step_name: "Preferred Fabric Color",
          step_number: 8,
          preferred_fabric_color: localStorage.getItem("preferredColor") || "",
        };
      } else if (stepId === "choose_artwork_mode") {
        payLoadData = {
          stepId,
          step_name: "Choose Artwork Mode",
          step_number: 9,
          choose_artwork_mode: localStorage.getItem("artworkMode") || "",
        };
      } else if (stepId === "artwork_highlight") {
        payLoadData = {
          stepId,
          step_name: "Artwork Highlight",
          step_number: 10,
          choose_artwork_mode: localStorage.getItem("artworkMode") || "",
          artwork_image:
            localStorage.getItem("ImageData_ArtworkHighlight") || "",
        };
      } else if (stepId === "technique") {
        payLoadData = {
          stepId,
          step_name: "Technique",
          step_number: 11,
          technique_category:
            localStorage.getItem("technique_category") || "[]",
        };
      } else if (stepId === "technique_child") {
        payLoadData = {
          stepId,
          step_name: "Technique Child",
          step_number: 12,
          artwork_technique_child:
            localStorage.getItem("artworkTechniqueChild") || "[]",
        };
      } else if (stepId === "artwork_prominent") {
        payLoadData = {
          stepId,
          step_name: "Artwork Prominent",
          step_number: 13,
          artwork_prominent_id: localStorage.getItem("artworkProminent") || "",
        };
      } else if (stepId === "artwork_placement") {
        payLoadData = {
          stepId,
          step_name: "Artwork Placement",
          step_number: 14,
          artwork_placement_id: localStorage.getItem("artworkPlacement") || "",
        };
      } else if (stepId === "piece_imagine_artwork") {
        payLoadData = {
          stepId,
          step_name: "Piece Imagine Artwork",
          step_number: 15,
          piece_imagine: localStorage.getItem("piece_imagine") || "",
        };
      } else if (stepId === "piece_note_share_artwork") {
        payLoadData = {
          stepId,
          step_name: "Piece Note Share Artwork",
          step_number: 16,
          piece_note_share_artwork:
            localStorage.getItem("piece_note_share") || "",
        };
      } else if (stepId === "morni_art_collection") {
        payLoadData = {
          stepId,
          step_name: "Morni Art Collection",
          step_number: 17,
           choose_artwork_mode: localStorage.getItem("artworkMode") || "",
          art_style: localStorage.getItem("MorniArtCollection") || "[]",
        };
      } else if (stepId === "morni_pick_piece") {
        payLoadData = {
          stepId,
          step_name: "Morni Pick Piece",
          step_number: 18,
          art_work: localStorage.getItem("MorniPickPiece") || "[]",
        };
      } else if (stepId === "add_measurement") {
        payLoadData = {
          stepId,
          step_name: "Add Measurement",
          step_number: 19,
          measurement: JSON.stringify({
            for_whom: localStorage.getItem("forWhom") || "",
            radio_gender: localStorage.getItem("radioGender") || "",
            someone_name: localStorage.getItem("someoneName") || "",
            save_height: localStorage.getItem("saveHeight") || "",
            save_weight: localStorage.getItem("saveWeight") || "",
            radio_fit_type: localStorage.getItem("radioFitType") || "",
          }),
        };
      } else if (stepId === "standard_measurement") {
        payLoadData = {
          stepId,
          step_name: "Standard Measurement",
          step_number: 20,
          standard_measurement: JSON.stringify({
            selected_top_size: localStorage.getItem("selectedTopSize") || "",
            selected_bottom_size:
              localStorage.getItem("selectedBottomSize") || "",
          }),
        };
      } else if (stepId === "custom_measurement") {
        payLoadData = {
          stepId,
          step_name: "Custom Measurement",
          step_number: 21,
          custom_measurement: JSON.stringify({
            selected_top_size: localStorage.getItem("selectedTopSize") || "",
            selected_bottom_size:
              localStorage.getItem("selectedBottomSize") || "",
          }),
        };
      }else if (stepId === "category_three_piece") {
        payLoadData = {
          stepId,
          step_name: "outwear category three piece",
          step_number: 22,
          outwear_category_id: localStorage.getItem("outwearCategoryId") || "",
        };
      }else if (stepId === "category_three_piece_step2") {
        payLoadData = {
          stepId,
          step_name: "bottom category three piece step 2",
          step_number: 23,
          bottom_category_id: localStorage.getItem("bottomCategoryId") || "",
        };
      }else if (stepId === "category_three_piece_step3") {
        payLoadData = {
          stepId,
          step_name: "bottom category three piece step 3",
          step_number: 24,
          vest_category_id: localStorage.getItem("vestCategoryId") || "",
        };
      }else if (stepId === "category_two_piece_bottom") {
        payLoadData = {
          stepId,
          step_name: "bottom category two piece step 3",
          step_number: 25,
          bottom_category_id: localStorage.getItem("bottomCategoryId") || "",
        };
      }else if (stepId === "category_two_piece_bottom_child") {
        payLoadData = {
          stepId,
          step_name: "bottom category two piece step 3",
          step_number: 26,
          bottom_silhouette_id: localStorage.getItem("bottomSilhouetteId") || "",
        };
      }else if (stepId === "category_two_piece") {
        payLoadData = {
            stepId,
            step_name: "Category Two Piece",
            step_number: 27,
            category_single_child:
            localStorage.getItem("categorySingleChild") || "",
            silhouette_id: localStorage.getItem("silhouette") || "",
            outwear_category_id: localStorage.getItem("outwearCategoryId") || "",
            sub_category_id: localStorage.getItem("subcategoryId") || "",
            
        };
      }else if (stepId === "category_two_piece_step3") {
        payLoadData = {
            stepId,
            step_name: "Category Two Piece",
            step_number: 28,
            category_single_child:
            localStorage.getItem("categorySingleChild") || "",
            silhouette_id: localStorage.getItem("silhouette") || "",
            outwear_category_id: localStorage.getItem("outwearCategoryId") || "",
        };
      }else if (stepId === "category_two_piece_top") {
        payLoadData = {
          stepId, 
          step_name: "Category Two Piece",
          step_number: 29,
          sub_category_id: localStorage.getItem("subcategoryId") || "",
          ////category_single: localStorage.getItem("CategorySingle") || "",
        };
      }else if (stepId === "category_two_piece_top_child") {
        payLoadData = {
          stepId, 
          step_name: "Category Two Piece Step 3",
          step_number: 30,
          outwear_silhouette_id: localStorage.getItem("silhouette") || "",
          ////category_single: localStorage.getItem("CategorySingle") || "",
        };
      }else if (stepId === "category_basic") {
        payLoadData = {
          stepId,
          step_name: "Category Basic",
          step_number: 31,
          category_basic: localStorage.getItem("categoryBasic") || "",
        };
        localStorage.removeItem("genderExpression");
      } else {
        payLoadData = {
          stepId,
          stepData: {},
          step_name: "else part",
          step_number: 2100000,
        };
      }
      //i want to add session_id to the payload

      payLoadData.session_id = getUserSessionId();
      payLoadData.external_id = externalId || "";



      try {
        const response = await postFormData(payLoadData);
        console.log("Step data saved", stepId, stepData, response);
        
        // Check if response indicates failure
        if (response && !response.success) {
          console.error("Failed to save step:", response.message);
        }
      } catch (err: any) {
        console.error("Failed to save step:", err.message || err);
      }
    },
    [externalId],
  );

  // Navigation state update: sync URL & localStorage
  const updateNavigationState = useCallback(() => {
    const group = wizardData.groups[activeGroupIdx];
    const step = filteredSteps[activeStepIdx];
    if (group && step) {
      localStorage.setItem("wizardGroup", group.id);
      localStorage.setItem("wizardStep", step.id);
      router.replace(
        `${startPath}?group=${group.id}&step=${step.id}&external=${externalId}`,
        {
          scroll: false,
        },
      );
    }
  }, [
    activeGroupIdx,
    activeStepIdx,
    filteredSteps,
    wizardData.groups,
    router,
    startPath,
    externalId,
  ]);

  // Update URL & localStorage when active group/step changes
  useEffect(() => updateNavigationState(), [updateNavigationState]);

  // Compute step status map for navigation buttons
  useEffect(() => {
    const statusMap: Record<string, StepStatus> = {};
    wizardData.groups.forEach((group, gIdx) => {
      const visibleSteps = group.steps.filter(
        (step) =>
          !step.condition || state[step.condition.key] === step.condition.value,
      );
      visibleSteps.forEach((step, sIdx) => {
        if (
          gIdx < activeGroupIdx ||
          (gIdx === activeGroupIdx && sIdx < activeStepIdx)
        ) {
          statusMap[step.id] = "done";
        } else if (gIdx === activeGroupIdx && sIdx === activeStepIdx) {
          statusMap[step.id] = "current";
        } else {
          statusMap[step.id] = "upcoming";
        }
      });
    });
    setStepStatus(statusMap);
  }, [activeGroupIdx, activeStepIdx, wizardData.groups, state]);

  // === Navigation handlers ===
  const onNext = useCallback(async () => {
    const currentStepId = filteredSteps[activeStepIdx]?.id;

    if (currentStepId) {
      await saveStepDataToApi(currentStepId);
    }
    if (activeStepIdx < filteredSteps.length - 1) {
      setActiveStepIdx(activeStepIdx + 1);
    } else {
      for (let g = activeGroupIdx + 1; g < wizardData.groups.length; g++) {
        const nextSteps = wizardData.groups[g].steps.filter(
          (step) =>
            !step.condition ||
            state[step.condition.key] === step.condition.value,
        );
        if (nextSteps.length > 0) {
          setActiveGroupIdx(g);
          setActiveStepIdx(0);
          break;
        }
      }
    }
  }, [
    activeStepIdx,
    activeGroupIdx,
    filteredSteps,
    saveStepDataToApi,
    state,
    wizardData.groups,
  ]);

  const onPrev = useCallback(() => {
    if (activeStepIdx > 0) {
      setActiveStepIdx(activeStepIdx - 1);
    } else if (activeGroupIdx > 0) {
      const prevGroupIdx = activeGroupIdx - 1;
      const prevSteps = wizardData.groups[prevGroupIdx].steps.filter(
        (step) =>
          !step.condition || state[step.condition.key] === step.condition.value,
      );
      setActiveGroupIdx(prevGroupIdx);
      setActiveStepIdx(prevSteps.length - 1);
    }
  }, [activeStepIdx, activeGroupIdx, state, wizardData.groups]);

  const onJump = useCallback(
    (groupIdx: number, stepIdx: number) => {
      if (!isGroupDisabled(groupIdx)) {
        setActiveGroupIdx(groupIdx);
        setActiveStepIdx(stepIdx);
      }
    },
    [isGroupDisabled],
  );

  // Jump to step by ID anywhere in wizard
  const jumpToStepId = useCallback(
    (stepId: string) => {
      for (let gIdx = 0; gIdx < wizardData.groups.length; gIdx++) {
        const group = wizardData.groups[gIdx];
        const visibleSteps = group.steps.filter(
          (step) =>
            !step.condition ||
            state[step.condition.key] === step.condition.value,
        );
        const stepIdx = visibleSteps.findIndex((step) => step.id === stepId);
        if (stepIdx !== -1) {
          setActiveGroupIdx(gIdx);
          setActiveStepIdx(stepIdx);
          return;
        }
      }
      console.warn(`Step with ID '${stepId}' not found.`);
    },
    [wizardData.groups, state],
  );

  // Compute progress percent for group
  const getProgress = useCallback(
    (group: TabGroup): number => {
      const visibleSteps = group.steps.filter(
        (step) =>
          !step.condition || state[step.condition.key] === step.condition.value,
      );
      if (!visibleSteps.length) return 0;

      const doneSteps = visibleSteps.filter(
        (step) => stepStatus[step.id] === "done",
      ).length;
      const isActive = wizardData.groups[activeGroupIdx]?.id === group.id;

      return ((doneSteps + (isActive ? 1 : 0)) / visibleSteps.length) * 100;
    },
    [state, stepStatus, wizardData.groups, activeGroupIdx],
  );

  // Flags
  const isLastStep =
    activeGroupIdx === wizardData.groups.length - 1 &&
    activeStepIdx === filteredSteps.length - 1;
  const isFirstStep = activeGroupIdx === 0 && activeStepIdx === 0;
  const isNextDisabled =
    (currentStep?.requiresValidation && !isStepValid) || isLastStep;

  // === Keyboard navigation ===
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "ArrowLeft") {
        e.preventDefault();
        if (isFirstStep) setShowExitModal(true);
        else onPrev();
      } else if (e.key === "ArrowRight") {
        e.preventDefault();
        if (!isNextDisabled) onNext();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [isFirstStep, isNextDisabled, onPrev, onNext]);

  // Keyboard navigation for exit modal
  useEffect(() => {
    const handleConfirmModalKeys = (e: KeyboardEvent) => {
      if (!showExitModal) return;
      if (e.key === "Escape") {
        e.preventDefault();
        setShowExitModal(false);
      } else if (e.key === "Enter") {
        e.preventDefault();
        setShowExitModal(false);
        router.push("/design-journey");
      }
    };
    window.addEventListener("keydown", handleConfirmModalKeys);
    return () => window.removeEventListener("keydown", handleConfirmModalKeys);
  }, [showExitModal, router]);

  return (
    <>
      <div className="fixed top-13 md:top-11 left-[5%] flex h-[12%] w-[90%] flex-col">
        <div className="grid grid-cols-12 items-start gap-1 align-top">
          <div className="col-span-11 flex flex-col">
            {/* Group Navigation */}
            <GroupNavigation
              groups={wizardData.groups}
              activeGroupIdx={activeGroupIdx}
              setActiveGroupIdx={setActiveGroupIdx}
              getProgress={getProgress}
              isGroupDisabled={isGroupDisabled}
            />

            {/* Step Navigation */}
            {filteredSteps.length > 1 && (
              <StepNavigation
                steps={filteredSteps}
                stepStatus={stepStatus}
                activeStepIdx={activeStepIdx}
                setActiveStepIdx={setActiveStepIdx}
                isStepValid={isStepValid}
              />
            )}
          </div>
          <div className="relative -top-1 col-span-1 flex items-center justify-center align-top">
            {/* Step Info Toggle */}
            <button
              type="button"
              onClick={() => setStepInfoVisible((v) => !v)}
              className="z-50 p-3 text-gray-700 hover:text-gray-900"
              aria-label="Toggle steps info"
            >
              <i className="icon-[akar-icons--info]" />
            </button>
          </div>
        </div>
      </div>

      {/* Step Content */}
      <div className="fixed bottom-auto top-[21vh] md:top-[14vh] md:bottom-[5vh] left-[10%] z-10 flex h-[48vh] w-[80%] flex-col md:left-[5%] md:h-[80vh] md:w-[90%]">
        {CurrentStepComponent ? (
          <CurrentStepComponent
            onSkip={onNext}
            onJump={onJump}
            activeGroupIdx={activeGroupIdx}
            activeStepIdx={activeStepIdx}
            jumpToStepId={jumpToStepId}
            setIsStepValid={setIsStepValid}
            jumpToNext={onNext}
            wizardDataGroupSteps={filteredSteps.map(({ id, title }) => ({
              id,
              title,
            }))}
            startPath={startPath}
          />
        ) : (
          <p>No step to show.</p>
        )}
      </div>

      {/* Navigation Arrows */}
      <NavButtons
        onPrev={() => {
          if (isFirstStep) {
            setShowExitModal(true);
          } else {
            onPrev();
          }
        }}
        onNext={onNext}
        isFirstStep={isFirstStep}
        isNextDisabled={isNextDisabled}
      />

      {/* Confirm Exit Modal */}
      <ConfirmExitModal
        headingText="Leave this journey"
        isOpen={showExitModal}
        title={cleanStartPath}
        message="Are you sure you want to go back?"
        cancelText="Stay to continue"
        confirmText="Yes, Leave"
        onConfirm={() => {
          setShowExitModal(false);
          router.push("/design-journey");
        }}
        onCancel={() => setShowExitModal(false)}
      />

      {/* Vision Board */}
      {startPath === "morni-guidance" && (
        <VisionBoard jumpToStepId={jumpToStepId} />
      )}

      {/* Step Info Panel */}
      {isStepInfoVisible && (
        <StepInfoPanel
          steps={filteredSteps}
          stepStatus={stepStatus}
          activeStepIdx={activeStepIdx}
          isStepValid={isStepValid}
          setActiveStepIdx={setActiveStepIdx}
          onClose={() => setStepInfoVisible(false)}
        />
      )}
    </>
  );
}
