"use client";
import React, { useState, useEffect, useRef } from "react";
import Cookies from "js-cookie";
import dynamic from "next/dynamic";
import { useRouter } from "next/navigation";
import "./serveportal.css";
import "./stepsSep.css";
import {
  updateCampaignFormAlt,
  removeFromSelectedEvents,
  setAdvertRedirectUrl,
  updateSelectedEventDuration,
  setSelectedEvents,
  setCampaignForm,
  resetCampaignForm,
  resetCampaignState,
} from "../../../redux/features/main/campaigns/advertAction";
import { useAppDispatch, useAppSelector } from "../../../hooks/useDispatch";
import { useSepData, useSummaryData } from "@/app/hooks/useData";
import ImageCropper from "./ImageCropper";
import {
  formatDate,
  calculateTotalPriceForAllEvents,
  formatEventDisplay,
  isValidUrl,
} from "@/app/utils/datehelpers";
import {
  searchLocations,
  fetchGeoPricingLocations,
} from "@/app/redux/services/main/advert/advertServices";
import { useDebouncedSearch } from "@/app/hooks/usedebounceSearch";
import PriceSelector from "./PriceSelector";
import {
  calculateTotalPriceFromEvents,
  sendCampaignToBackend,
  prepareCampaignData,
  getDynamicDimensions,
  getRequiredDimensionsForSize,
} from "@/app/utils/campaigns/campaignHelpers";
import Swal from "sweetalert2";
import { getUserInfo } from "@/app/utils/token";
import { createServerSearchParamsForServerPage } from "next/dist/server/request/search-params";
const MapSift = dynamic(() => import("./Map"), {
  ssr: false,
});
const ServePortal: React.FC = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const [showCropper, setShowCropper] = useState(false);
  const [imageToCrop, setImageToCrop] = useState<string | null>(null);
  const [isMapVisible, setIsMapVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [activeAdvertType, setActiveAdvertType] = useState("image");
  const [activeAdvertSize, setActiveAdvertSize] = useState("large");
  const [events, setEvents] = useState<any[]>([]);
  const [error, setError] = useState<string | null>(null);
  const { selectedEvents, campaignForm, geoPricingData, isLoadingGeoPricing } =
    useAppSelector((state) => state.compaign);
  const [expandedSlots, setExpandedSlots] = useState<number[]>([]);
  const [selectedMedia, setSelectedMedia] = useState<string | null>(null);
  const [mediaType, setMediaType] = useState<
    "image" | "video" | "richtext" | null
  >(null);
  const [mediaFile, setMediaFile] = useState<File | null>(null);
  const [isProcessingPayment, setIsProcessingPayment] = useState(false);
  const [isProcessingCallback, setIsProcessingCallback] = useState(false);
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [showResults, setShowResults] = useState(false);
  const [isSelecting, setIsSelecting] = useState(false);
  const { searchTerm, setSearchTerm, debouncedTerm } = useDebouncedSearch(500);
  const [isClosingMap, setIsClosingMap] = useState(false);
  // Ref to track if payment callback has been processed
  const paymentCallbackProcessed = useRef(false);
  // Add these states for price selector modal
  const [showPriceSelector, setShowPriceSelector] = useState(false);
  const [selectedEventForPrice, setSelectedEventForPrice] = useState<any>(null);
  const [selectedEventIndex, setSelectedEventIndex] = useState<number | null>(
    null
  );

  const [imageDimensions, setImageDimensions] = useState({
    width: 0,
    height: 0,
  });
  const [isValidDimension, setIsValidDimension] = useState(true);
  const [requiredDimensions, setRequiredDimensions] = useState({
    width: 1050,
    height: 840,
  });
  const [isMounted, setIsMounted] = useState(false);
  const { data: sepData } = useSepData();
  const { data: summaryData } = useSummaryData();

  const toggleMap = () => {
    if (isMapVisible) {
      setIsClosingMap(true);
      setTimeout(() => {
        setIsMapVisible(false);
        setIsClosingMap(false);
      }, 1500);
    } else {
      setIsMapVisible(true);
      setIsSelecting(false);
      setShowResults(false);
    }
  };
  const toggleSlot = (index: number) => {
    setExpandedSlots((prev) => (prev.includes(index) ? [] : [index]));
  };
  useEffect(() => {
    const performSearch = async () => {
      if (debouncedTerm.length < 3) {
        setSearchResults([]);
        setShowResults(false);
        setIsSelecting(false);
        return;
      }
      setIsSearching(false);
      setIsSearching(true);
      setShowResults(true);

      try {
        const response = await searchLocations(debouncedTerm);
        if (response.status === 200) {
          setSearchResults(response.getResult || []);
        } else {
          setSearchResults([]);
        }
      } catch (error) {
        setSearchResults([]);
      } finally {
        setIsSearching(false);
      }
    };

    performSearch();
  }, [debouncedTerm]);
  const onUrlChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const url = e.target.value.trim();
    dispatch(setAdvertRedirectUrl(url));
  };

  const handleLocationSelect = (location: any) => {
    setIsMapVisible(true);
    setIsSelecting(true);
    setSearchTerm(`${location.city_name}, ${location.postal_code}`);
    setShowResults(false);
    dispatch(
      updateCampaignFormAlt({
        key: "mapCentercommune",
        value: location.city_name,
      })
    );
    dispatch(
      updateCampaignFormAlt({
        key: "mapCenterlat",
        value: `${location.lat}`,
      })
    );
    dispatch(
      updateCampaignFormAlt({
        key: "mapCenterlang",
        value: `${location.lng}`,
      })
    );
  };
  const handleInputChange = (value: string) => {
    setSearchTerm(value);
    if (value.length === 0) {
      setShowResults(false);
      setSearchResults([]);
      dispatch(
        updateCampaignFormAlt({
          key: "mapCenterlang",
          value: "",
        })
      );
      dispatch(
        updateCampaignFormAlt({
          key: "mapCenterlat",
          value: "",
        })
      );
    }
  };
  const handleInputFocus = () => {
    if (searchResults.length > 0 && searchTerm.length >= 3) {
      setShowResults(true);
    }
  };

  useEffect(() => {
    if (selectedEvents.length > 0) {
      setExpandedSlots([selectedEvents.length - 1]);
    } else {
      setExpandedSlots([]);
    }
  }, [selectedEvents.length]);
  useEffect(() => {
    const totalPrice = calculateTotalPriceForAllEvents(selectedEvents);
    dispatch(
      updateCampaignFormAlt({
        key: "totalprice",
        value: totalPrice,
      })
    );
  }, [selectedEvents, dispatch]);

  const fetchRandomEvents = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const url = `${process.env.NEXT_PUBLIC_API_URL_New}/events/all-active-events`;

      const res = await fetch(url, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });
      if (!res.ok) {
        throw new Error(`Failed to fetch events: ${res.status}`);
      }

      const eventsData = await res.json();
      setEvents(eventsData.events || []);
      setIsLoading(false);
    } catch (err) {
      setError(
        err instanceof Error
          ? err.message
          : "Échec de la récupération des événements"
      );
      console.error("Erreur lors de la récupération des événements:", err);
      setEvents([]);
      setIsLoading(false);
    }
  };
  const handleAdvertTypeSelect = (type: string) => {
    if (activeAdvertType !== type && selectedMedia) {
      handleRemoveMedia();
    }

    setActiveAdvertType(type);

    if (type === "video") {
      setActiveAdvertSize("large");
      const dynamicDims = getDynamicDimensions(350, 280);
      setSelectedMedia(null);
      setMediaType(null);
      setMediaFile(null);
      dispatch(
        updateCampaignFormAlt({
          key: "advert_type",
          value: "large",
        })
      );
      dispatch(
        updateCampaignFormAlt({
          key: "format",
          value: `${dynamicDims.width} x ${dynamicDims.height} px`,
        })
      );
    }
    if (type === "rich text") {
      setActiveAdvertSize("large");
      const dynamicDims = getDynamicDimensions(350, 280);
      dispatch(
        updateCampaignFormAlt({
          key: "advert_type",
          value: "large",
        })
      );
      dispatch(
        updateCampaignFormAlt({
          key: "format",
          value: `${dynamicDims.width} x ${dynamicDims.height} px`,
        })
      );
    }
    dispatch(
      updateCampaignFormAlt({
        key: "media_type",
        value: type,
      })
    );
    dispatch(
      updateCampaignFormAlt({
        key: "image",
        value: "",
      })
    );
  };
  const shouldShowSize = (size: string): boolean => {
    if (activeAdvertType === "video" || activeAdvertType === "rich text") {
      // For video, only enable large size
      return size === "large";
    }
    return true;
  };

  const handleAdvertSizeSelect = (
    size: string,
    dimensions: string,
    pricePerDay: string
  ) => {
    setActiveAdvertSize(size);
    const dynamicDims = getRequiredDimensionsForSize(size);
    setRequiredDimensions(dynamicDims);
    setSelectedMedia(null);
    setMediaType(null);
    setMediaFile(null);
    if (selectedMedia && mediaType === "image") {
      const isValid =
        imageDimensions.width === dynamicDims.width &&
        imageDimensions.height === dynamicDims.height;
      setIsValidDimension(isValid);
    }

    dispatch(
      updateCampaignFormAlt({
        key: "advert_type",
        value: size,
      })
    );

    dispatch(
      updateCampaignFormAlt({
        key: "format",
        value: `${dynamicDims.width} x ${dynamicDims.height} px`,
      })
    );
    dispatch(
      updateCampaignFormAlt({
        key: "image",
        value: "",
      })
    );
  };
  const handleRemoveEvent = (eventId: string) => {
    dispatch(removeFromSelectedEvents(eventId));
  };
  const getPriceForAdvert = (size: string): string => {
    if (!geoPricingData) return "";

    switch (activeAdvertType) {
      case "image":
        if (size === "medium") {
          return geoPricingData.image;
        } else if (size === "large") {
          return geoPricingData.large_image;
        } else if (size === "pop under") {
          return geoPricingData.banner;
        }
        break;

      case "video":
        if (size === "large") {
          return geoPricingData.large_image_video;
        }
        return ""; // Disabled sizes

      case "rich text":
        // For rich text, show appropriate prices
        if (size === "medium") {
          return geoPricingData.image; // Use image price for medium rich text
        } else if (size === "large") {
          return geoPricingData.large_image_rich_text;
        } else if (size === "pop under") {
          return geoPricingData.banner;
        }
        break;

      default:
        return "";
    }
    return "";
  };

  useEffect(() => {
    fetchRandomEvents();
    dispatch(fetchGeoPricingLocations());
    // Mark component as mounted (client-side only)
    setIsMounted(true);

    // Check if we're returning from payment (cancellation or success)
    const urlParams = new URLSearchParams(window.location.search);
    const paymentCancelled = urlParams.get("payment_cancelled");
    const paymentSuccess = urlParams.get("payment_success");

    // If NOT returning from payment (neither cancelled nor success), clear any saved data
    // This handles page refresh or direct navigation to the page
    if (!paymentCancelled && !paymentSuccess && typeof window !== "undefined") {
      localStorage.removeItem("pending_campaign_data");
      try {
        deleteFileFromIndexedDB("pending_media_file");
      } catch (error) {
        // Ignore errors when clearing
      }
      // Reset Redux state and local state
      dispatch(resetCampaignState());
      setActiveAdvertType("image");
      setActiveAdvertSize("large");
      setSelectedMedia(null);
      setMediaFile(null);
      setMediaType(null);
      setSearchTerm("");
      setImageDimensions({ width: 0, height: 0 });
      setIsValidDimension(true);
      setRequiredDimensions({ width: 1050, height: 840 });
    }
  }, []);

  // Cleanup: Clear saved data when component unmounts (user navigates away)
  useEffect(() => {
    return () => {
      // Clear saved data when navigating away (unless we're processing payment callback)
      if (typeof window !== "undefined") {
        const urlParams = new URLSearchParams(window.location.search);
        const paymentCancelled = urlParams.get("payment_cancelled");
        const paymentSuccess = urlParams.get("payment_success");

        // Only clear if we're not in a payment flow (cancelled or success)
        // This prevents clearing data when user is returning from checkout
        if (!paymentCancelled && !paymentSuccess) {
          localStorage.removeItem("pending_campaign_data");
          try {
            deleteFileFromIndexedDB("pending_media_file");
          } catch (error) {
            // Ignore errors when clearing
          }
          // Reset Redux state
          dispatch(resetCampaignState());
        }
      }
    };
  }, []);

  const handleMediaUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    if (activeAdvertType === "image") {
      if (!file.type.startsWith("image/")) {
        Swal.fire({
          icon: "error",
          title:
            sepData?.errors?.invalid_file_type_image_title ||
            "Type de fichier invalide",
          text:
            sepData?.errors?.invalid_file_type_image_text ||
            "Veuillez télécharger un fichier image (JPEG, PNG, GIF, etc.)",
          confirmButtonText: sepData?.processing?.ok || "OK",
        });
        return;
      }

      if (file.size > 5 * 1024 * 1024) {
        Swal.fire({
          icon: "error",
          title:
            sepData?.errors?.file_too_large_image_title ||
            "Fichier trop volumineux",
          text:
            sepData?.errors?.file_too_large_image_text ||
            "La taille de l'image doit être inférieure à 5 Mo",
          confirmButtonText: sepData?.processing?.ok || "OK",
        });
        return;
      }

      // Check image dimensions
      const img = new Image();
      img.onload = () => {
        setImageDimensions({ width: img.width, height: img.height });

        // Get dynamic required dimensions for current size
        const dynamicRequiredDims =
          getRequiredDimensionsForSize(activeAdvertSize);

        const isValid =
          img.width === dynamicRequiredDims.width &&
          img.height === dynamicRequiredDims.height;
        setIsValidDimension(isValid);

        if (!isValid) {
          // Auto-show cropper immediately for invalid dimensions
          const imageUrl = URL.createObjectURL(file);
          setImageToCrop(imageUrl);
          setShowCropper(true);

          // Still set the media but mark as invalid
          setSelectedMedia(imageUrl);
          setMediaFile(file);
          setMediaType("image");
          dispatch(
            updateCampaignFormAlt({
              key: "image",
              value: file.name,
            })
          );

          return; // stop the normal upload flow
        }

        // If dimensions are valid, continue with normal upload
        const mediaUrl = URL.createObjectURL(file);
        setSelectedMedia(mediaUrl);
        setMediaFile(file);
        setMediaType("image");
        dispatch(
          updateCampaignFormAlt({
            key: "image",
            value: file.name,
          })
        );
      };

      img.src = URL.createObjectURL(file);
    } else if (activeAdvertType === "video") {
      // ... rest of video handling code remains the same
      if (!file.type.startsWith("video/")) {
        Swal.fire({
          icon: "error",
          title:
            sepData?.errors?.invalid_file_type_video_title ||
            "Type de fichier invalide",
          text:
            sepData?.errors?.invalid_file_type_video_text ||
            "Veuillez télécharger un fichier vidéo (MP4, MOV, AVI, etc.)",
          confirmButtonText: sepData?.processing?.ok || "OK",
        });
        return;
      }

      if (file.size > 50 * 1024 * 1024) {
        Swal.fire({
          icon: "error",
          title:
            sepData?.errors?.file_too_large_video_title ||
            "Fichier trop volumineux",
          text:
            sepData?.errors?.file_too_large_video_text ||
            "La taille de la vidéo doit être inférieure à 50MB",
          confirmButtonText: sepData?.processing?.ok || "OK",
        });
        return;
      }

      setMediaType("video");
      const mediaUrl = URL.createObjectURL(file);
      setSelectedMedia(mediaUrl);
      setMediaFile(file);
      dispatch(
        updateCampaignFormAlt({
          key: "image",
          value: file.name,
        })
      );
    } else if (activeAdvertType === "rich text") {
      // ... rest of rich text handling code remains the same
      const allowedRichTextTypes = [
        "text/rtf",
        "application/rtf",
        "text/plain",
        "application/msword",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      ];

      const isRTF = file.name.toLowerCase().endsWith(".rtf");
      const isTextFile = file.type.startsWith("text/");
      const isAllowedType = allowedRichTextTypes.includes(file.type);

      if (!isRTF && !isTextFile && !isAllowedType) {
        Swal.fire({
          icon: "error",
          title:
            sepData?.errors?.invalid_rich_text_file_title || "Fichier invalide",
          text:
            sepData?.errors?.invalid_rich_text_file_text ||
            "Veuillez télécharger un fichier RTF ou un document texte.",
          confirmButtonText: sepData?.processing?.ok || "OK",
        });
        return;
      }

      if (file.size > 5 * 1024 * 1024) {
        Swal.fire({
          icon: "error",
          title:
            sepData?.errors?.file_too_large_rich_text_title ||
            "Fichier trop volumineux",
          text:
            sepData?.errors?.file_too_large_rich_text_text ||
            "La taille du fichier texte enrichi doit être inférieure à 50 Mo.",
          confirmButtonText: sepData?.processing?.ok || "OK",
        });
        return;
      }

      setMediaType("richtext");
      const mediaUrl = URL.createObjectURL(file);
      setSelectedMedia(mediaUrl);
      setMediaFile(file);
      dispatch(
        updateCampaignFormAlt({
          key: "image",
          value: file.name,
        })
      );
    }
  };
  const getUploadText = () => {
    if (activeAdvertType === "image") {
      return `${sepData?.steps?.[2].instructions.uploadImage}`;
    } else if (activeAdvertType === "video") {
      return `${sepData?.steps?.[2].instructions.uploadVideo}`;
    } else if (activeAdvertType === "rich text") {
      return `${sepData?.steps?.[2].instructions.uploadRichText}`;
    }
    return sepData?.steps?.[2]?.default_upload_text || "Click to upload media";
  };

  const handleRemoveMedia = () => {
    if (selectedMedia) {
      URL.revokeObjectURL(selectedMedia); // Clean up the object URL
    }
    setSelectedMedia(null);
    setMediaType(null);
    setMediaFile(null);
    dispatch(
      updateCampaignFormAlt({
        key: "image",
        value: "",
      })
    );
    // Clear the file input
    const fileInput = document.getElementById(
      "media-upload"
    ) as HTMLInputElement;
    if (fileInput) {
      fileInput.value = "";
    }
  };
  const handleRemoveImage = () => {
    Swal.fire({
      title: sepData?.errors?.remove_media_title || "Supprimer le média ?",
      text:
        sepData?.errors?.remove_media_text ||
        "Êtes-vous sûr de vouloir supprimer ce média ?",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#d33",
      cancelButtonColor: "#3085d6",
      confirmButtonText:
        sepData?.errors?.remove_media_confirm || "Oui, supprimer !",
      cancelButtonText: sepData?.errors?.remove_media_cancel || "Annuler",
    }).then((result) => {
      if (result.isConfirmed) {
        handleRemoveMedia();
      }
    });
  };
  const handleConfirmImage = () => {};

  const getAcceptedFileTypes = () => {
    if (activeAdvertType === "image") {
      return "image/*";
    } else if (activeAdvertType === "video") {
      return "video/*";
    } else if (activeAdvertType === "rich text") {
      return ".rtf,.txt,text/rtf,application/rtf,text/plain,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    }
    return "*";
  };
  const renderMediaPreview = () => {
    if (!selectedMedia) return null;

    if (mediaType === "image") {
      return (
        <img
          src={selectedMedia}
          alt={sepData?.steps?.[2]?.alt_uploaded_media || "Uploaded media"}
          className="max-h-[180px] mx-auto object-contain"
        />
      );
    } else if (mediaType === "video") {
      return (
        <video
          src={selectedMedia}
          className="max-h-[180px] mx-auto object-contain"
          controls
        >
          {sepData?.steps?.[2]?.video_not_supported ||
            "Your browser does not support the video tag."}
        </video>
      );
    } else if (mediaType === "richtext") {
      return (
        <div className="flex flex-col items-center justify-center p-4">
          <img
            src="/document-icon.png" // You can add a document icon
            alt={sepData?.steps?.[2]?.alt_document || "Document"}
            className="w-16 h-16 mx-auto mb-2 opacity-50"
          />
          <p className="text-sm text-gray-600 text-center">
            {sepData?.steps?.[2]?.rich_text_uploaded ||
              "Rich Text File Uploaded"}
          </p>
          <p className="text-xs text-gray-500 text-center">
            {selectedMedia.split("/").pop()}
          </p>
        </div>
      );
    }

    return null;
  };
  // Helper function to convert File to base64
  const fileToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });
  };

  // IndexedDB helper functions for large files (videos/richtext)
  const openDB = (): Promise<IDBDatabase> => {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open("CampaignMediaDB", 1);

      request.onerror = () => reject(request.error);
      request.onsuccess = () => resolve(request.result);

      request.onupgradeneeded = (event) => {
        const db = (event.target as IDBOpenDBRequest).result;
        if (!db.objectStoreNames.contains("media")) {
          db.createObjectStore("media");
        }
      };
    });
  };

  const saveFileToIndexedDB = async (
    key: string,
    file: File
  ): Promise<void> => {
    const db = await openDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction(["media"], "readwrite");
      const store = transaction.objectStore("media");
      const request = store.put(file, key);

      request.onsuccess = () => resolve();
      request.onerror = () => reject(request.error);
    });
  };

  const getFileFromIndexedDB = async (key: string): Promise<File | null> => {
    const db = await openDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction(["media"], "readonly");
      const store = transaction.objectStore("media");
      const request = store.get(key);

      request.onsuccess = () => resolve(request.result || null);
      request.onerror = () => reject(request.error);
    });
  };

  const deleteFileFromIndexedDB = async (key: string): Promise<void> => {
    const db = await openDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction(["media"], "readwrite");
      const store = transaction.objectStore("media");
      const request = store.delete(key);

      request.onsuccess = () => resolve();
      request.onerror = () => reject(request.error);
    });
  };

  // Helper function to convert base64 back to File
  const base64ToFile = async (
    base64String: string,
    fileName: string,
    mimeType: string
  ): Promise<File> => {
    const response = await fetch(base64String);
    const blob = await response.blob();
    return new File([blob], fileName, { type: mimeType });
  };

  // Function to restore form data from localStorage
  const restoreFormData = async () => {
    // Only restore on client side after mount
    if (typeof window === "undefined" || !isMounted) {
      return;
    }

    try {
      const savedDataStr = localStorage.getItem("pending_campaign_data");
      if (!savedDataStr) {
        console.log("No saved campaign data found");
        return;
      }

      const savedData = JSON.parse(savedDataStr);

      // Restore campaignForm to Redux
      if (savedData.campaignForm) {
        dispatch(setCampaignForm(savedData.campaignForm));

        // Restore local state from campaignForm
        if (savedData.campaignForm.media_type) {
          setActiveAdvertType(savedData.campaignForm.media_type);
        }
        if (savedData.campaignForm.advert_type) {
          setActiveAdvertSize(savedData.campaignForm.advert_type);
        }
        if (savedData.campaignForm.mapCentercommune) {
          setSearchTerm(savedData.campaignForm.mapCentercommune);
        }

        // Restore required dimensions based on advert size
        if (savedData.campaignForm.advert_type) {
          const dynamicDims = getRequiredDimensionsForSize(
            savedData.campaignForm.advert_type
          );
          setRequiredDimensions(dynamicDims);
        }
      }

      // Restore selectedEvents to Redux
      if (savedData.selectedEvents && Array.isArray(savedData.selectedEvents)) {
        dispatch(setSelectedEvents(savedData.selectedEvents));
      }

      // Restore media file
      if (savedData.useIndexedDB) {
        // Retrieve large files from IndexedDB
        try {
          const fileFromDB = await getFileFromIndexedDB("pending_media_file");
          if (fileFromDB) {
            setMediaFile(fileFromDB);
            setMediaType(
              savedData.mediaFileType?.startsWith("video/")
                ? "video"
                : savedData.mediaFileType?.includes("rtf") ||
                  savedData.mediaFileType?.includes("text/")
                ? "richtext"
                : "image"
            );
            const mediaUrl = URL.createObjectURL(fileFromDB);
            setSelectedMedia(mediaUrl);

            // If it's an image, check dimensions
            if (savedData.mediaFileType?.startsWith("image/")) {
              const img = new Image();
              img.onload = () => {
                setImageDimensions({ width: img.width, height: img.height });
                const advertSize =
                  savedData.campaignForm?.advert_type || activeAdvertSize;
                const dynamicRequiredDims =
                  getRequiredDimensionsForSize(advertSize);
                const isValid =
                  img.width === dynamicRequiredDims.width &&
                  img.height === dynamicRequiredDims.height;
                setIsValidDimension(isValid);
              };
              img.src = mediaUrl;
            }
          }
        } catch (error) {
          console.error("Error restoring media file from IndexedDB:", error);
        }
      } else if (
        savedData.mediaFileBase64 &&
        savedData.mediaFileName &&
        savedData.mediaFileType
      ) {
        // Retrieve small images from base64 in localStorage
        try {
          const restoredFile = await base64ToFile(
            savedData.mediaFileBase64,
            savedData.mediaFileName,
            savedData.mediaFileType
          );
          setMediaFile(restoredFile);
          setMediaType("image");
          const mediaUrl = URL.createObjectURL(restoredFile);
          setSelectedMedia(mediaUrl);

          // Check image dimensions
          const img = new Image();
          img.onload = () => {
            setImageDimensions({ width: img.width, height: img.height });
            const advertSize =
              savedData.campaignForm?.advert_type || activeAdvertSize;
            const dynamicRequiredDims =
              getRequiredDimensionsForSize(advertSize);
            const isValid =
              img.width === dynamicRequiredDims.width &&
              img.height === dynamicRequiredDims.height;
            setIsValidDimension(isValid);
          };
          img.src = mediaUrl;
        } catch (error) {
          console.error("Error restoring media file from base64:", error);
        }
      }

      console.log("Form data restored successfully");
    } catch (error) {
      console.error("Error restoring form data:", error);
    }
  };

  // Handle payment success and cancellation callbacks
  useEffect(() => {
    // Only run on client side after component is mounted
    if (typeof window === "undefined" || !isMounted) {
      return;
    }

    const handlePaymentCallback = async () => {
      console.log("just above handlePaymentCallback");
      // Prevent duplicate execution
      if (paymentCallbackProcessed.current) {
        return;
      }

      const urlParams = new URLSearchParams(window.location.search);
      const paymentSuccess = urlParams.get("payment_success");
      const paymentCancelled = urlParams.get("payment_cancelled");
      const sessionId = urlParams.get("session_id");
      console.log("paymentSuccess", paymentSuccess);
      console.log("paymentCancelled", paymentCancelled);
      console.log("sessionId", sessionId);
      // If no payment-related params, exit early
      if (!paymentSuccess && !paymentCancelled) {
        return;
      }

      // Mark as processed immediately to prevent duplicate calls
      paymentCallbackProcessed.current = true;

      // Clean up URL params immediately to prevent re-execution
      window.history.replaceState({}, document.title, window.location.pathname);

      // Handle payment cancellation
      if (paymentCancelled === "true") {
        // Wait a bit to ensure hydration is complete before restoring
        setTimeout(async () => {
          // Restore form data so user can continue from where they left off
          await restoreFormData();
        }, 100);

        Swal.fire({
          icon: "info",
          title: sepData?.errors?.payment_cancelled_title || "Paiement annulé",
          text:
            sepData?.errors?.payment_cancelled_text ||
            "Votre paiement a été annulé. Vous pouvez réessayer quand vous le souhaitez.",
          confirmButtonText: sepData?.processing?.ok || "OK",
        });
        return;
      }

      // Handle payment success
      if (paymentSuccess === "true" && sessionId) {
        setIsProcessingPayment(true);
        setIsProcessingCallback(true);

        try {
          // Get user token
          const token = Cookies.get("token");
          if (!token) {
            throw new Error("Utilisateur non authentifié");
          }

          // Restore campaign data from localStorage
          const savedDataStr = localStorage.getItem("pending_campaign_data");

          console.log("savedDataStr in payment success", savedDataStr);
          if (!savedDataStr) {
            throw new Error(
              sepData?.errors?.campaign_data_not_found ||
                "Données de campagne introuvables. Veuillez essayer de créer à nouveau la campagne."
            );
          }

          const savedData = JSON.parse(savedDataStr);

          // Restore media file from IndexedDB or base64
          let restoredMediaFile: File | undefined;

          if (savedData.useIndexedDB) {
            // Retrieve large files from IndexedDB
            try {
              const fileFromDB = await getFileFromIndexedDB(
                "pending_media_file"
              );
              if (fileFromDB) {
                restoredMediaFile = fileFromDB;
                console.log("Restored file from IndexedDB:", fileFromDB.name);
              } else {
                throw new Error(
                  sepData?.errors?.media_file_not_found ||
                    "Fichier de média introuvable"
                );
              }
            } catch (error) {
              console.error(
                "Error restoring media file from IndexedDB:",
                error
              );
              throw new Error(
                sepData?.errors?.failed_restore_storage ||
                  "Échec de la restauration du fichier média depuis le stockage"
              );
            }
          } else if (
            savedData.mediaFileBase64 &&
            savedData.mediaFileName &&
            savedData.mediaFileType
          ) {
            // Retrieve small images from base64 in localStorage
            try {
              restoredMediaFile = await base64ToFile(
                savedData.mediaFileBase64,
                savedData.mediaFileName,
                savedData.mediaFileType
              );
            } catch (error) {
              console.error("Error restoring media file from base64:", error);
              throw new Error(
                sepData?.errors?.failed_restore_media ||
                  "Failed to restore media file"
              );
            }
          }

          console.log("just above session details response");

          // Retrieve session details from Stripe to get discount information
          const sessionDetailsResponse = await fetch(
            `/api/payment/session-details?session_id=${sessionId}`
          );
          if (!sessionDetailsResponse.ok) {
            throw new Error(
              sepData?.errors?.failed_retrieve_payment ||
                "Failed to retrieve payment details"
            );
          }

          const sessionDetails = await sessionDetailsResponse.json();
          const walletDiscount = sessionDetails.walletDiscount || 0;
          const stripeDiscount = sessionDetails.stripeDiscount || 0;
          const totalDiscount = walletDiscount + stripeDiscount;
          const originalAmount = sessionDetails.amount;
          const finalAmount = sessionDetails.finalAmount;
          const couponCode = sessionDetails.couponCode || null;

          // Prepare campaign data with Stripe session ID and all discount info
          const campaignData = prepareCampaignData(
            savedData.campaignForm,
            savedData.selectedEvents,
            restoredMediaFile,
            sessionId,
            originalAmount, // Original amount before any discounts
            totalDiscount, // Total discount amount (wallet + promo)
            finalAmount, // Final amount after all discounts
            walletDiscount, // Wallet discount amount
            stripeDiscount, // Stripe promo code discount amount
            couponCode // Stripe coupon code if applied
          );
          console.log("campaignData", campaignData);
          console.log("just above sendCampaignToBackend");

          // Send to Nest.js backend
          const result = await sendCampaignToBackend(campaignData, token);

          if (result.success) {
            // Clean up saved data only on success
            localStorage.removeItem("pending_campaign_data");

            // Clean up IndexedDB media file - ensure it's deleted
            try {
              await deleteFileFromIndexedDB("pending_media_file");
              console.log("Successfully deleted media file from IndexedDB");
            } catch (error) {
              // If deletion fails, log the error but don't block success flow
              console.error("Error deleting media file from IndexedDB:", error);
              // Try to verify if file still exists
              try {
                const fileExists = await getFileFromIndexedDB(
                  "pending_media_file"
                );
                if (fileExists) {
                  console.warn(
                    "Media file still exists in IndexedDB after deletion attempt"
                  );
                  // Retry deletion
                  await deleteFileFromIndexedDB("pending_media_file");
                  console.log(
                    "Retry: Successfully deleted media file from IndexedDB"
                  );
                }
              } catch (verifyError) {
                console.error(
                  "Error verifying IndexedDB file deletion:",
                  verifyError
                );
              }
            }

            Swal.fire({
              icon: "success",
              title:
                sepData?.errors?.payment_successful_title ||
                "Paiement réussi !",
              text:
                sepData?.errors?.payment_successful_text ||
                "Votre campagne a été créée avec succès.",
              confirmButtonText: sepData?.processing?.ok || "OK",
            }).then(() => {
              // Redirect to the campaigns page
              router.push("/campaigns/sepCampaigns");
            });
          } else {
            // Payment succeeded but campaign creation failed
            // Don't clean up data - user might need to retry
            Swal.fire({
              icon: "warning",
              title:
                sepData?.errors?.payment_success_creation_failed_title ||
                "Paiement réussi !",
              text:
                sepData?.errors?.payment_success_creation_failed_text ||
                "Paiement réussi, mais la création de la campagne a échoué. Veuillez contacter le support.",
              confirmButtonText: sepData?.processing?.ok || "OK",
            });
          }
        } catch (error: any) {
          console.error("Error creating campaign:", error);
          // Don't clean up data on error - user might need to retry
          Swal.fire({
            icon: "error",
            title:
              sepData?.errors?.campaign_creation_failed_title ||
              "Échec de la création de la campagne.",
            text:
              error.message ||
              sepData?.errors?.campaign_creation_failed_text ||
              "Une erreur est survenue lors de la création de votre campagne.",
            confirmButtonText: sepData?.processing?.ok || "OK",
          });
        } finally {
          setIsProcessingPayment(false);
          setIsProcessingCallback(false);
        }
      }
    };

    handlePaymentCallback();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isMounted]);
  function convertFrenchNumberToStandard(frenchNumber: string) {
    if (!frenchNumber || typeof frenchNumber !== "string") {
      return 0;
    }
    let standardNumber = frenchNumber
      .replace(/\s/g, "") // Remove any spaces
      .replace(",", "."); // Replace comma with dot

    // Convert to number
    const numberValue = parseFloat(standardNumber);

    // Return the number, or 0 if conversion fails
    return isNaN(numberValue) ? 0 : numberValue;
  }
  const handleCropComplete = (croppedImage: string) => {
    if (!croppedImage) {
      Swal.fire({
        icon: "error",
        title: sepData?.errors?.crop_failed_title || "Échec du recadrage.",
        text:
          sepData?.errors?.crop_failed_text ||
          "Le recadrage de l'image a échoué. Veuillez réessayer.",
        confirmButtonText: sepData?.processing?.ok || "OK",
      });
      return;
    }

    // Convert base64 to blob and create file
    fetch(croppedImage)
      .then((res) => {
        if (!res.ok)
          throw new Error(
            sepData?.errors?.failed_fetch_cropped_image ||
              "Échec de la récupération de l'image recadrée."
          );
        return res.blob();
      })
      .then((blob) => {
        const file = new File(
          [blob],
          mediaFile?.name || `cropped-${Date.now()}.jpg`,
          {
            type: "image/jpeg",
          }
        );

        // Create object URL for the cropped image
        const croppedImageUrl = URL.createObjectURL(blob);

        // Update states with cropped image
        setSelectedMedia(croppedImageUrl);
        setMediaFile(file);
        setImageDimensions({
          width: requiredDimensions.width,
          height: requiredDimensions.height,
        });
        setIsValidDimension(true);

        Swal.fire({
          icon: "success",
          title:
            sepData?.errors?.crop_success_title ||
            "Image recadrée avec succès !",
          text: `${
            sepData?.errors?.crop_success_text_prefix ||
            "L'image a été recadrée à "
          }${requiredDimensions.width}x${requiredDimensions.height}${
            sepData?.errors?.crop_success_text_suffix || "px"
          }`,
          confirmButtonText: sepData?.processing?.ok || "OK",
        });
      })
      .catch((error) => {
        console.error("Error processing cropped image:", error);
        Swal.fire({
          icon: "error",
          title:
            sepData?.errors?.crop_processing_failed_title ||
            "Échec du recadrage",
          text:
            sepData?.errors?.crop_processing_failed_text ||
            "Le traitement de l'image recadrée a échoué. Veuillez réessayer.",
          confirmButtonText: sepData?.processing?.ok || "OK",
        });
      })
      .finally(() => {
        setShowCropper(false);
        setImageToCrop(null);
      });
  };

  const onPayment = async () => {
    // Validation
    if (!isValidUrl(campaignForm.advert_redirect_url)) {
      Swal.fire({
        icon: "error",
        title: sepData?.errors?.invalid_url_title || "URL invalide",
        text:
          sepData?.errors?.invalid_url_text ||
          "Veuillez fournir une URL valide (ex: https://exemple.com)",
        confirmButtonText: sepData?.processing?.ok || "OK",
      });
      return;
    }
    if (selectedEvents.length === 0) {
      Swal.fire({
        icon: "warning",
        title:
          sepData?.errors?.no_events_selected_title ||
          "Aucun événement sélectionné",
        text:
          sepData?.errors?.no_events_selected_text ||
          "Veuillez sélectionner au moins un événement avant de procéder au paiement",
        confirmButtonText: sepData?.processing?.ok || "OK",
      });
      return;
    }
    if (activeAdvertType === "image" && mediaFile && !isValidDimension) {
      Swal.fire({
        icon: "error",
        title:
          sepData?.errors?.invalid_image_dimensions_title ||
          "Dimensions d'image incorrectes",
        text: `${
          sepData?.errors?.invalid_image_dimensions_text_prefix ||
          "Les dimensions de votre image ("
        }${imageDimensions.width}x${imageDimensions.height}${
          sepData?.errors?.invalid_image_dimensions_text_middle ||
          "px) ne correspondent pas aux dimensions requises ("
        }${requiredDimensions.width}x${requiredDimensions.height}${
          sepData?.errors?.invalid_image_dimensions_text_suffix ||
          "px). Veuillez redimensionner votre image avant de procéder au paiement."
        }`,
        confirmButtonText:
          sepData?.errors?.resize_image_button || "Redimensionner l'image",
        showCancelButton: true,
        cancelButtonText: sepData?.errors?.cancel_button || "Annuler",
      }).then((result) => {
        if (result.isConfirmed) {
          setIsMapVisible(false);
        }
      });
      return;
    }
    if (!mediaFile && !campaignForm.image) {
      Swal.fire({
        icon: "warning",
        title:
          sepData?.errors?.no_media_selected_title || "Aucun média sélectionné",
        text:
          sepData?.errors?.no_media_selected_text ||
          "Veuillez télécharger votre fichier média avant de procéder au paiement",
        confirmButtonText: sepData?.processing?.ok || "OK",
      });
      return;
    }

    if (!campaignForm.advert_redirect_url) {
      Swal.fire({
        icon: "warning",
        title:
          sepData?.errors?.missing_redirect_url_title ||
          "URL de redirection manquante",
        text:
          sepData?.errors?.missing_redirect_url_text ||
          "Veuillez fournir une URL de redirection pour l'annonce",
        confirmButtonText: sepData?.processing?.ok || "OK",
      });
      return;
    }

    setIsProcessingPayment(true);

    try {
      // Get user token and info
      const token = Cookies.get("token");
      const user_id = Cookies.get("user_id");
      const userinfo = getUserInfo();
      const customerEmail = userinfo?.email;
      console.log("customerEmail", customerEmail);
      console.log("user_id", user_id);
      console.log("token", token);

      if (!token) {
        throw new Error(
          sepData?.errors?.user_not_authenticated || "User not authenticated"
        );
      }

      // Calculate total price
      const totalPrice = convertFrenchNumberToStandard(campaignForm.totalprice);
      if (totalPrice <= 0) {
        throw new Error(
          sepData?.errors?.invalid_total_price || "Invalid total price"
        );
      }

      // Create checkout session
      const response = await fetch("/api/payment/create-intent", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          stripe_customer_id: Cookies.get("stripe_customer_id"),
          amount: totalPrice,
          currency: "eur",
          metadata: {
            user_id: localStorage.getItem("user_id") || "",
            event_count: selectedEvents.length.toString(),
          },
          successUrl: `${window.location.origin}/campaigns/createSepCampaigns?payment_success=true&session_id={CHECKOUT_SESSION_ID}`,
          cancelUrl: `${window.location.origin}/campaigns/createSepCampaigns?payment_cancelled=true`,
          selectedEvents,
          token,
          user_id,
          customerEmail,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(
          errorData.error ||
            sepData?.errors?.failed_checkout_session ||
            "Failed to create checkout session"
        );
      }

      const responseData = await response.json();
      const {
        url,
        discountApplied,
        originalAmount,
        finalAmount,
        walletBalance,
      } = responseData;

      if (url) {
        // Save campaign data before redirecting
        try {
          let mediaFileBase64 = "";
          let mediaFileName = "";
          let mediaFileType = "";
          let useIndexedDB = false;

          if (mediaFile) {
            mediaFileName = mediaFile.name;
            mediaFileType = mediaFile.type;

            // Use IndexedDB for large files (videos and richtext), localStorage for images
            const isLargeFile = mediaFile.size > 4 * 1024 * 1024; // > 4MB
            const isVideoOrRichText =
              mediaFile.type.startsWith("video/") ||
              mediaFile.type.includes("rtf") ||
              mediaFile.type.includes("text/");

            if (isLargeFile || isVideoOrRichText) {
              // Save large files to IndexedDB
              await saveFileToIndexedDB("pending_media_file", mediaFile);
              useIndexedDB = true;
              console.log("Saved large file to IndexedDB:", mediaFileName);
            } else {
              // Keep small images in localStorage as base64
              mediaFileBase64 = await fileToBase64(mediaFile);
            }
          }
          const campaignDataToSave = {
            selectedEvents,
            campaignForm,
            mediaFileBase64: useIndexedDB ? "" : mediaFileBase64,
            mediaFileName,
            mediaFileType,
            useIndexedDB, // Flag to indicate where media is stored
            // Save discount information
            discountApplied: discountApplied || 0,
            originalAmount: originalAmount || totalPrice,
            finalAmount: finalAmount || totalPrice,
            walletBalance: walletBalance || 0,
          };
          console.log("campaignDataToSave", campaignDataToSave);

          localStorage.setItem(
            "pending_campaign_data",
            JSON.stringify(campaignDataToSave)
          );

          console.log(
            "localStorage.getItem(pending_campaign_data)",
            JSON.parse(localStorage.getItem("pending_campaign_data") || "{}")
          );
        } catch (error) {
          console.error("Error saving campaign data:", error);
          if (
            error instanceof DOMException &&
            error.name === "QuotaExceededError"
          ) {
            throw new Error(
              sepData?.errors?.file_too_large_storage ||
                "Le fichier est trop volumineux pour être stocké. Veuillez utiliser un fichier plus petit ou contacter le support."
            );
          }
          throw new Error(
            sepData?.errors?.failed_save_data ||
              "Failed to save campaign data before payment"
          );
        }

        // Redirect to Stripe Checkout
        window.location.href = url;
      } else {
        throw new Error(
          sepData?.errors?.failed_get_checkout_url ||
            "Failed to get checkout URL"
        );
      }
    } catch (error: any) {
      console.error("Payment error:", error);
      Swal.fire({
        icon: "error",
        title: sepData?.errors?.payment_failed_title || "Échec du paiement",
        text:
          error.message ||
          sepData?.errors?.payment_failed_text ||
          "Une erreur est survenue lors du paiement",
        confirmButtonText: sepData?.processing?.ok || "OK",
      });
      setIsProcessingPayment(false);
    }
  };

  const handleDurationClick = (event: any, index: number) => {
    setSelectedEventForPrice(event);
    setSelectedEventIndex(index);
    setShowPriceSelector(true);
  };
  const handleDurationUpdate = (days: number, price: any) => {
    if (selectedEventIndex !== null && selectedEventForPrice) {
      let numericPrice = 0;

      if (typeof price === "number") {
        numericPrice = price;
      } else if (typeof price === "string") {
        numericPrice = parseFloat(
          price.replace(",", ".").replace("€", "").replace(/\s/g, "")
        );
      }
      if (isNaN(numericPrice)) {
        console.warn("Invalid price value:", price, "using 0 instead");
        numericPrice = 0;
      }
      dispatch(
        updateSelectedEventDuration({
          eventId: selectedEventForPrice.event_id,
          duration: days,
          price: numericPrice,
        })
      );
      const updatedEvents = selectedEvents.map((event, index) =>
        index === selectedEventIndex
          ? { ...event, duration: days, price: price }
          : event
      );

      // Close the modal
      setShowPriceSelector(false);
      setSelectedEventForPrice(null);
      setSelectedEventIndex(null);
    }
  };

  return (
    <>
      {/* Loading Overlay for Payment Processing - Only show during callback processing */}
      {isProcessingCallback && (
        <div className="fixed inset-0 backdrop-blur-md flex items-center justify-center z-[9999]">
          <div className="w-16 h-16 border-4 border-gray-300 border-t-blue-600 rounded-full animate-spin"></div>
        </div>
      )}
      <div className="w-full">
        <div className="flex flex-col lg:flex-row gap-1 lg:gap-8">
          {isMapVisible ? (
            <div className="transition-all delay-75 duration-500 ease-out w-full">
              {/* Map content */}
              <div className="overflow-hidden">
                {isLoading ? (
                  <div className="flex justify-center items-center h-[400px] flex-col gap-4 text-lg text-gray-600">
                    <div>
                      {sepData?.loading?.loading_events ||
                        "Chargement des événements..."}
                    </div>
                    <div className="text-sm text-gray-400">
                      {sepData?.loading?.loading_events_subtitle ||
                        "Patientez pendant le chargement des événements"}
                    </div>
                  </div>
                ) : (
                  <div
                    className={`${
                      isClosingMap
                        ? "slide-out-left-to-right"
                        : "slide-in-right-to-left"
                    } w-auto h-auto`}
                  >
                    <MapSift events={events} />
                  </div>
                )}
              </div>
            </div>
          ) : (
            <div className="w-full lg:flex-1">
              {/* Header Section */}
              <div className="flex items-center gap-4 mt-4">
                <img
                  className="w-10 h-10 sm:w-12 sm:h-12"
                  src="/cart.png"
                  alt=""
                />
                <h1 className="primary-heading text-2xl sm:text-3xl md:text-4xl">
                  {sepData?.pageInfo?.pageTitle}
                </h1>
              </div>

              <h2 className="secondary-heading event-h ml-12 sm:ml-14 md:ml-16 mt-3 text-xl sm:text-2xl">
                {sepData?.pageInfo?.sectionTitle}
              </h2>

              <p className="primary-para event-p ml-12 sm:ml-14 md:ml-16 mt-2 text-base sm:text-lg md:text-xl">
                {sepData?.pageInfo?.description}
              </p>

              {/* Content of steps */}
              {/* Content of steps */}
              <div className="w-full">
                {/* Step 1 */}
                <div className="mb-8 flex gap-2 sm:gap-4">
                  {/* Number with line */}
                  <div className="flex flex-col items-center flex-shrink-0">
                    <div className="w-8 h-8 sm:w-10 sm:h-10 bg-green-600 text-white rounded-full flex items-center justify-center font-bold text-sm sm:text-base z-10">
                      1
                    </div>
                    <div className="w-0.5 bg-green-600 flex-grow mt-2"></div>
                  </div>

                  {/* Content */}
                  <div className="flex-1 pb-4">
                    <h2 className="tertiary-heading text-xl sm:text-2xl mb-4">
                      {sepData?.steps?.[0]?.title}
                    </h2>
                    <div className="step-2-btn-container flex flex-col sm:flex-row gap-3 sm:gap-4">
                      <button
                        className={`imgBtn tertiary-para1 text-lg sm:text-xl md:text-2xl px-4 py-3 rounded-lg transition-all ${
                          activeAdvertType === "image" ? "active" : ""
                        }`}
                        onClick={() => handleAdvertTypeSelect("image")}
                      >
                        {sepData?.steps?.[0]?.options.image.label}
                      </button>
                      <button
                        className={`Step-2-Btn quaternary-heading text-lg sm:text-xl md:text-2xl font-medium px-4 py-3 rounded-lg transition-all ${
                          activeAdvertType === "rich text" ? "active" : ""
                        }`}
                        onClick={() => handleAdvertTypeSelect("rich text")}
                      >
                        {sepData?.steps?.[0]?.options.richText.label}
                      </button>
                      <button
                        className={`Step-2-Btn quaternary-heading text-lg sm:text-xl md:text-2xl font-medium px-4 py-3 rounded-lg transition-all ${
                          activeAdvertType === "video" ? "active" : ""
                        }`}
                        onClick={() => handleAdvertTypeSelect("video")}
                      >
                        {sepData?.steps?.[0]?.options.video.label}
                      </button>
                    </div>
                  </div>
                </div>

                {/* Step 2 */}
                <div className="mb-8 flex gap-2 sm:gap-4">
                  {/* Number with line */}
                  <div className="flex flex-col items-center flex-shrink-0">
                    <div className="w-8 h-8 sm:w-10 sm:h-10 bg-green-600 text-white rounded-full flex items-center justify-center font-bold text-sm sm:text-base z-10">
                      2
                    </div>
                    <div className="w-0.5 bg-green-600 flex-grow mt-2"></div>

                    {/* <div className={`w-0.5 flex-grow mt-2 ${
        selectedMedia ? 'bg-green-600' : 'bg-green-600'
      }`}></div> */}
                  </div>

                  {/* Content */}
                  <div className="flex-1 pb-4">
                    <h3 className="tertiary-heading text-xl sm:text-2xl mb-3">
                      {sepData?.steps?.[1]?.title}
                    </h3>
                    <p className="primary-para text-base sm:text-lg mb-4">
                      {sepData?.steps?.[1]?.subtitle}
                    </p>
                    <div className="cards grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
                      {shouldShowSize("medium") && (
                        <div
                          className={`card-container p-4 sm:p-6 border-2 rounded-lg cursor-pointer transition-all hover:shadow-lg ${
                            activeAdvertSize === "medium"
                              ? "active border-blue-500"
                              : "border-gray-300"
                          }`}
                          onClick={() =>
                            handleAdvertSizeSelect(
                              "medium",
                              "300 x 250px",
                              getPriceForAdvert("medium")
                            )
                          }
                        >
                          <h4 className="quaternary-heading uppercase text-center mt-4 text-base sm:text-lg">
                            {sepData?.steps?.[1]?.sizes.medium.label}
                          </h4>
                          <div className="flex justify-center my-6 sm:my-8">
                            <div className="blue-box px-4 py-2 bg-blue-100 rounded">
                              <p className="tertiary-para text-sm sm:text-base">
                                {(() => {
                                  const dimensions =
                                    sepData?.steps?.[1]?.sizes.medium
                                      .dimensions;
                                  if (!dimensions) return dimensions;

                                  const matches =
                                    dimensions.match(/(\d+)\s*x\s*(\d+)/);
                                  if (!matches) return dimensions;

                                  let width = parseInt(matches[1]);
                                  let height = parseInt(matches[2]);
                                  width = Math.round(width) * 3;
                                  height = Math.round(height) * 3;

                                  return `${width} x ${height} px`;
                                })()}
                              </p>{" "}
                            </div>
                          </div>
                          <p className="quaternary-para text-center text-sm sm:text-base">
                            {sepData?.steps?.[1]?.sizes.medium.from}
                          </p>
                          <p className="quaternary-para text-center text-xl sm:text-2xl font-bold mt-0">
                            {isLoadingGeoPricing
                              ? "..."
                              : `${getPriceForAdvert("medium")}€`}{" "}
                            /{sepData?.steps?.[1]?.sizes.medium.day}
                          </p>
                        </div>
                      )}

                      {/* Large Card */}
                      <div
                        className={`card-container btnCard p-4 sm:p-6 border-2 rounded-lg cursor-pointer transition-all hover:shadow-lg relative ${
                          activeAdvertSize === "large"
                            ? "active border-blue-500"
                            : "border-gray-300"
                        }`}
                        onClick={() =>
                          handleAdvertSizeSelect(
                            "large",
                            "350 x 280px",
                            getPriceForAdvert("large")
                          )
                        }
                      >
                        <button className="sellerBtn tertiary-para absolute top-2 right-2 px-3 py-1 bg-green-500 text-white text-xs sm:text-sm rounded">
                          {sepData?.steps?.[1]?.sizes.large.tag}
                        </button>
                        <h4 className="quaternary-heading uppercase text-center mt-4 text-base sm:text-lg">
                          {sepData?.steps?.[1]?.sizes.large.label}
                        </h4>
                        <div className="flex justify-center my-6 sm:my-8">
                          <div className="blue-box px-4 py-2 bg-blue-100 rounded">
                            <p className="tertiary-para text-sm sm:text-base">
                              {(() => {
                                const dimensions =
                                  sepData?.steps?.[1]?.sizes.large.dimensions;
                                if (!dimensions) return dimensions;

                                const matches =
                                  dimensions.match(/(\d+)\s*x\s*(\d+)/);
                                if (!matches) return dimensions;

                                let width = parseInt(matches[1]);
                                let height = parseInt(matches[2]);
                                width = Math.round(width) * 3;
                                height = Math.round(height) * 3;

                                return `${width} x ${height} px`;
                              })()}
                            </p>{" "}
                          </div>
                        </div>
                        <p className="quaternary-para text-center text-sm sm:text-base">
                          {sepData?.steps?.[1]?.sizes.large.from}
                        </p>
                        <p className="quaternary-para text-center text-xl sm:text-2xl font-bold mt-0">
                          {isLoadingGeoPricing
                            ? "..."
                            : `${getPriceForAdvert("large")}€`}{" "}
                          / {sepData?.steps?.[1]?.sizes.large.day}
                        </p>
                      </div>

                      {/* Pop Under Card */}
                      {shouldShowSize("pop under") && (
                        <div
                          className={`card-container p-4 sm:p-6 border-2 rounded-lg cursor-pointer transition-all hover:shadow-lg ${
                            activeAdvertSize === "pop under"
                              ? "active border-blue-500"
                              : "border-gray-300"
                          }`}
                          onClick={() =>
                            handleAdvertSizeSelect(
                              "pop under",
                              "720 x 300px",
                              getPriceForAdvert("pop under")
                            )
                          }
                        >
                          <h4 className="quaternary-heading uppercase text-center mt-4 text-base sm:text-lg">
                            {sepData?.steps?.[1]?.sizes.popUnder.label}
                          </h4>
                          <div className="flex justify-center my-6 sm:my-8">
                            <div className="blue-box pop px-6 py-2 bg-blue-100 rounded">
                              <p className="tertiary-para text-sm sm:text-base">
                                {(() => {
                                  const dimensions =
                                    sepData?.steps?.[1]?.sizes.popUnder
                                      .dimensions;
                                  if (!dimensions) return dimensions;

                                  const matches =
                                    dimensions.match(/(\d+)\s*x\s*(\d+)/);
                                  if (!matches) return dimensions;

                                  let width = parseInt(matches[1]);
                                  let height = parseInt(matches[2]);
                                  width = Math.round(width) * 3;
                                  height = Math.round(height) * 3;

                                  return `${width} x ${height} px`;
                                })()}
                              </p>{" "}
                            </div>
                          </div>
                          <p className="quaternary-para text-center text-sm sm:text-base">
                            {sepData?.steps?.[1]?.sizes.popUnder.from}
                          </p>
                          <p className="quaternary-para text-center text-xl sm:text-2xl font-bold mt-0">
                            {isLoadingGeoPricing
                              ? "..."
                              : `${getPriceForAdvert("pop under")}€`}{" "}
                            / {sepData?.steps?.[1]?.sizes.popUnder.day}
                          </p>
                        </div>
                      )}
                    </div>
                  </div>
                </div>

                {/* Step 3 - Media Upload */}
                <div className="mb-8 flex gap-2 sm:gap-4">
                  {/* Number with line */}
                  <div className="flex flex-col items-center flex-shrink-0">
                    <div
                      className={`w-8 h-8 sm:w-10 sm:h-10 rounded-full flex items-center justify-center font-bold text-sm sm:text-base z-10 ${
                        selectedMedia
                          ? "bg-green-600 text-white"
                          : "bg-green-600 text-white"
                      }`}
                    >
                      3
                    </div>

                    <div
                      className={`w-0.5 flex-grow mt-2 ${
                        selectedMedia
                          ? "bg-green-600"
                          : "w-0.5 flex-grow mt-2 bg-[linear-gradient(#dc2626_2px,transparent_2px),linear-gradient(transparent_6px,#dc2626_6px)] bg-[length:100%_8px]"
                      }`}
                    ></div>
                  </div>

                  {/* Content */}
                  <div className="flex-1 pb-4">
                    <h3 className="tertiary-heading text-xl sm:text-2xl mb-3">
                      {sepData?.steps?.[2].title}
                    </h3>
                    <p className="primary-para text-base sm:text-lg mb-4">
                      {sepData?.steps?.[2].subtitle}
                    </p>

                    <input
                      type="file"
                      accept={getAcceptedFileTypes()}
                      className="hidden"
                      id="media-upload"
                      onChange={handleMediaUpload}
                    />

                    <div className="relative">
                      <div
                        className="postcode-input border-dashed border-2 border-gray-300 cursor-pointer flex items-center justify-center min-h-[200px] rounded-lg hover:border-blue-400 transition-colors"
                        onClick={() =>
                          document.getElementById("media-upload")?.click()
                        }
                        onDragOver={(e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          e.currentTarget.classList.add(
                            "border-blue-500",
                            "bg-blue-50"
                          );
                        }}
                        onDragEnter={(e) => {
                          e.preventDefault();
                          e.currentTarget.classList.add(
                            "border-blue-500",
                            "bg-blue-50"
                          );
                        }}
                        onDragLeave={(e) => {
                          e.preventDefault();
                          if (
                            !e.currentTarget.contains(e.relatedTarget as Node)
                          ) {
                            e.currentTarget.classList.remove(
                              "border-blue-500",
                              "bg-blue-50"
                            );
                          }
                        }}
                        onDrop={(e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          e.currentTarget.classList.remove(
                            "border-blue-500",
                            "bg-blue-50"
                          );

                          const files = e.dataTransfer.files;
                          if (files.length > 0) {
                            const fakeEvent = {
                              target: {
                                files: files,
                              },
                            } as React.ChangeEvent<HTMLInputElement>;

                            handleMediaUpload(fakeEvent);
                          }
                        }}
                      >
                        {selectedMedia ? (
                          <div className="relative w-full h-full p-4 ">
                            {/* Enhanced Media Preview with Ratio Guidance */}
                            <div className="relative mx-auto max-w-md">
                              {renderMediaPreview()}

                              {/* Aspect Ratio Overlay Guide */}
                              {/* {mediaType === "image" && (
                                <div className="absolute inset-0 pointer-events-none">
                                  <div className="absolute -top-8 left-1/2 transform -translate-x-1/2 bg-green-500 text-white px-2 py-1 rounded text-xs whitespace-nowrap">
                                    Target: {requiredDimensions.width}×
                                    {requiredDimensions.height}
                                  </div>
                                </div>
                              )} */}
                            </div>

                            {mediaType === "image" && !isValidDimension && (
                              <div className="absolute">
                                {/* <div className="flex flex-col sm:flex-row items-center justify-center gap-2">
                                  <span>
                                    Current:{" "}
                                    <strong>
                                      {imageDimensions.width}×
                                      {imageDimensions.height}px
                                    </strong>
                                  </span>
                                  <span className="hidden sm:inline">•</span>
                                  <span>
                                    Required:{" "}
                                    <strong>
                                      {requiredDimensions.width}×
                                      {requiredDimensions.height}px
                                    </strong>
                                  </span>
                                  <span className="hidden sm:inline">•</span>
                                  <span>
                                    Ratio:{" "}
                                    <strong>
                                      {requiredDimensions.width / 100}:
                                      {requiredDimensions.height / 100}
                                    </strong>
                                  </span>
                                </div> */}
                              </div>
                            )}
                          </div>
                        ) : (
                          <div className="text-center text-gray-500 p-4">
                            <div className="mb-2">
                              <img
                                src="/upload-icon.svg"
                                alt={
                                  sepData?.steps?.[2]?.alt_upload || "Upload"
                                }
                                className="w-10 h-10 sm:w-12 sm:h-12 mx-auto opacity-50"
                              />
                            </div>
                            <p className="text-sm sm:text-base">
                              {getUploadText()}
                            </p>
                            <p className="text-xs sm:text-sm mt-2">
                              {sepData?.steps?.[2].instructions.dragDrop}
                            </p>
                            {/* Add dimension requirements info */}
                          </div>
                        )}
                      </div>

                      {/* Action buttons */}
                      {selectedMedia && (
                        <div className="flex  items-center gap-1 right-[30%] absolute top-4 ">
                          <img
                            className="cursor-pointer w-6 h-6 sm:w-8 sm:h-8"
                            src="/cross-blue.png"
                            alt={sepData?.steps?.[2]?.alt_remove || "Remove"}
                            onClick={handleRemoveImage}
                          />
                          <img
                            className="cursor-pointer w-6 h-6 sm:w-8 sm:h-8"
                            src="/check-blue.png"
                            alt={sepData?.steps?.[2]?.alt_confirm || "Confirm"}
                            onClick={handleConfirmImage}
                          />
                        </div>
                      )}
                    </div>
                    {selectedMedia &&
                      mediaType === "image" &&
                      !isValidDimension && (
                        <div className="mt-4 flex flex-col sm:flex-row gap-3 justify-center items-center">
                          <div className="flex gap-2">
                            {/* <button
                              onClick={handleResizeImage}
                              className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 sm:px-6 sm:py-3 rounded-lg flex items-center gap-2 transition-colors text-sm sm:text-base"
                            >
                              <img
                                src="/resize.png"
                                alt="Crop"
                                className="w-4 h-4"
                              />
                              Crop to {requiredDimensions.width}×
                              {requiredDimensions.height}
                            </button> */}
                          </div>
                        </div>
                      )}

                    {showCropper && imageToCrop && (
                      <ImageCropper
                        imageSrc={imageToCrop}
                        requiredDimensions={requiredDimensions}
                        onCropComplete={handleCropComplete}
                        onCancel={() => {
                          setShowCropper(false);
                          setImageToCrop(null);
                          handleRemoveMedia();
                        }}
                        translations={sepData?.cropper}
                      />
                    )}
                  </div>
                </div>

                {/* Step 4 - Target URL */}
                <div className="mb-8 flex gap-2 sm:gap-4">
                  {/* Number with line */}
                  <div className="flex flex-col items-center flex-shrink-0">
                    <div
                      className={`w-8 h-8 sm:w-10 sm:h-10 rounded-full flex items-center justify-center font-bold text-sm sm:text-base z-10 ${
                        campaignForm.advert_redirect_url &&
                        isValidUrl(campaignForm.advert_redirect_url)
                          ? "bg-green-600 text-white"
                          : "bg-green-600 text-white"
                      }`}
                    >
                      4
                    </div>
                    <div
                      className={`w-0.5 flex-grow mt-2 ${
                        campaignForm.advert_redirect_url &&
                        isValidUrl(campaignForm.advert_redirect_url)
                          ? "bg-green-600"
                          : "w-0.5 flex-grow mt-2 bg-[linear-gradient(#dc2626_2px,transparent_2px),linear-gradient(transparent_6px,#dc2626_6px)] bg-[length:100%_8px]"
                      }`}
                    ></div>
                  </div>

                  {/* Content */}
                  <div className="flex-1 pb-4">
                    <h3 className="tertiary-heading text-xl sm:text-2xl mb-3">
                      {sepData?.steps?.[3].title}
                    </h3>
                    <p className="primary-para text-base sm:text-lg mb-4">
                      {sepData?.steps?.[3].subtitle}
                    </p>
                    <input
                      placeholder={
                        sepData?.steps?.[3]?.placeholder ||
                        "https://example.com"
                      }
                      className="postcode-input w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:outline-none transition-colors text-sm sm:text-base"
                      type="url"
                      value={campaignForm.advert_redirect_url || ""}
                      onChange={onUrlChange}
                    />
                  </div>
                </div>

                {/* Step 5 - Location Search */}
                <div className="mb-8 flex gap-2 sm:gap-4">
                  <div className="flex flex-col items-center flex-shrink-0">
                    <div
                      className={`w-8 h-8 sm:w-10 sm:h-10 rounded-full flex items-center justify-center font-bold text-sm sm:text-base z-10 ${
                        searchTerm !== ""
                          ? "bg-green-600 text-white"
                          : "bg-green-600 text-white"
                      }`}
                    >
                      5
                    </div>
                    <div
                      className={`w-0.5 flex-grow mt-2 ${
                        searchTerm !== ""
                          ? "bg-green-600"
                          : "w-0.5 flex-grow mt-2 bg-[linear-gradient(#dc2626_2px,transparent_2px),linear-gradient(transparent_6px,#dc2626_6px)] bg-[length:100%_8px]"
                      }`}
                    ></div>
                  </div>
                  <div className="flex-1 pb-4">
                    <h3 className="tertiary-heading text-xl sm:text-2xl mb-3">
                      {sepData?.steps?.[4].title}
                    </h3>
                    <p className="primary-para text-base sm:text-lg mb-4">
                      {sepData?.steps?.[4].subtitle}
                    </p>
                    <div>
                      <div className="relative px-4 py-3 pr-12 border-2  postcode-input border-gray-300 rounded-lg focus:border-blue-500">
                        <input
                          placeholder={sepData?.steps?.[4]?.placeholder}
                          className="w-full  focus:outline-none transition-colors text-sm sm:text-base placeholder-ellipsis"
                          onChange={(e) => handleInputChange(e.target.value)}
                          onFocus={handleInputFocus}
                          value={searchTerm}
                          type="text"
                        />
                        <img
                          className="absolute  left-[92%] sm:left-[95%]    lg:left-[94%] top-[27%]  cursor-pointer w-6 h-6"
                          src="/right-arrow.png"
                          alt=""
                          onClick={toggleMap}
                        />
                      </div>
                      {showResults && !isSelecting && (
                        <div className="absolute z-50 w-[73%] sm:w-[80%] md:w-[60%] lg:w-[28%] xl:w-[30%] 2xl:w-[33%] mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto">
                          {isSearching ? (
                            <div className="px-4 py-3 text-sm text-gray-500 flex items-center">
                              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-500 mr-2"></div>
                              {sepData?.steps?.[4]?.searching || "Searching..."}
                            </div>
                          ) : searchResults.length > 0 ? (
                            searchResults.map((location) => (
                              <div
                                key={`${location.city_id}-${location.postal_code}`}
                                className="px-4 py-3 cursor-pointer hover:bg-blue-50 border-b border-gray-100 last:border-b-0 transition-colors duration-150"
                                onClick={() => handleLocationSelect(location)}
                              >
                                <div className="font-medium text-gray-900 text-sm sm:text-base">
                                  {location.city_name}, {location.postal_code}
                                </div>
                              </div>
                            ))
                          ) : debouncedTerm.length >= 3 ? (
                            <div className="px-4 py-3 text-sm text-gray-500">
                              {sepData?.steps?.[4]?.no_results ||
                                "No locations found for"}{" "}
                              "{debouncedTerm}"
                            </div>
                          ) : null}
                        </div>
                      )}
                    </div>
                  </div>
                </div>

                {/* Step 6 - Chosen Adverts */}
                <div className="mb-8 flex gap-2 sm:gap-4">
                  {/* Number with line */}
                  <div className="flex flex-col items-center flex-shrink-0">
                    <div
                      className={`w-8 h-8 sm:w-10 sm:h-10 rounded-full flex items-center justify-center font-bold text-sm sm:text-base z-10 ${
                        selectedEvents.length > 0
                          ? "bg-green-600 text-white"
                          : "bg-green-600 text-white"
                      }`}
                    >
                      6
                    </div>
                    <div
                      className={`w-0.5 flex-grow mt-2 ${
                        selectedEvents.length > 0
                          ? "bg-green-600"
                          : "w-0.5 flex-grow mt-2 bg-[linear-gradient(#dc2626_2px,transparent_2px),linear-gradient(transparent_6px,#dc2626_6px)] bg-[length:100%_8px]"
                      }`}
                    ></div>
                  </div>

                  {/* Content */}
                  <div className="flex-1 pb-4">
                    <h3 className="tertiary-heading text-xl sm:text-2xl mb-3">
                      {sepData?.steps?.[5]?.title}
                    </h3>
                    <p className="primary-para choose-p text-base sm:text-lg mb-4">
                      {sepData?.steps?.[5]?.subtitle}
                    </p>
                    {selectedEvents.length > 0 ? (
                      selectedEvents.map((event, index) => (
                        <div
                          key={event.event_id}
                          className="relative mt-3 first:mt-0 w-[70%]"
                        >
                          <input
                            placeholder={formatEventDisplay(event, index)}
                            className="choose-input w-full px-4 py-3 pr-24 border-2 border-gray-300 rounded-lg text-sm sm:text-base"
                            type="text"
                            readOnly
                          />
                          <div className="choose-icons absolute right-2 top-1/2 -translate-y-1/2 flex gap-2">
                            <img
                              className="cursor-pointer w-5 h-5 sm:w-6 sm:h-6"
                              src="/cross.png"
                              alt="Remove"
                              title="Remove event"
                              onClick={() => handleRemoveEvent(event.event_id)}
                            />
                          </div>
                        </div>
                      ))
                    ) : (
                      <div className="lg:py-8">
                        <p className="secondary-para text-gray-600 text-sm sm:text-base">
                          {sepData?.steps?.[5]?.notes}
                        </p>
                        <p className="secondary-para text-gray-600 text-xs sm:text-sm mt-2">
                          {sepData?.steps?.[5]?.notes1}
                        </p>
                      </div>
                    )}
                  </div>
                </div>

                {/* Step 7 - All Done */}
                <div className="mb-8 flex gap-2 sm:gap-4">
                  {/* Number without line (last step) */}
                  <div className="flex flex-col items-center flex-shrink-0">
                    <div className="w-8 h-8 sm:w-10 sm:h-10 bg-green-600 text-white rounded-full flex items-center justify-center font-bold text-sm sm:text-base z-10">
                      7
                    </div>
                  </div>

                  {/* Content */}
                  <div className="flex-1">
                    <h3 className="tertiary-heading text-xl sm:text-2xl mb-3">
                      {sepData?.steps?.[6]?.title}
                    </h3>
                    <p className="primary-para choose-p text-base sm:text-lg">
                      {sepData?.steps?.[6]?.subtitle}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Summary Sidebar */}
          <div className="summary-sticky-container">
            {/* summary */}
            <h3 className="sum-h penta-heading">{summaryData?.summary}</h3>
            <div className="sum-container">
              {selectedEvents.length > 0 ? (
                selectedEvents.map((event, index) => {
                  const isExpanded = expandedSlots.includes(index);
                  return (
                    <div key={index}>
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "space-between",
                          marginBottom: "1.5rem",
                          marginTop: index === 0 ? "0.5rem" : "0.5rem",
                        }}
                      >
                        <div
                          style={{
                            display: "flex",
                            alignItems: "center",
                            gap: "1rem",
                          }}
                        >
                          <h4 className="penta-heading2 slot-p">
                            {sepData?.summary?.slot ||
                              summaryData?.slot_label ||
                              "SLOT"}{" "}
                            {index + 1}
                          </h4>
                          <img
                            className="crossimage"
                            src="/cross.png"
                            onClick={() => handleRemoveEvent(event.event_id)}
                            alt={
                              sepData?.summary?.alt_remove_event ||
                              summaryData?.alt_remove_event ||
                              "Remove Event"
                            }
                          />
                        </div>
                        <img
                          style={{ width: "20px", cursor: "pointer" }}
                          src={
                            isExpanded ? "/top-arrow.png" : "/bottom-arrow.png"
                          }
                          onClick={() => toggleSlot(index)}
                          alt={
                            isExpanded
                              ? sepData?.summary?.alt_collapse || "Collapse"
                              : sepData?.summary?.alt_expand || "Expand"
                          }
                        />
                      </div>

                      {/* Animated Slot Content */}
                      <div
                        style={{
                          maxHeight: isExpanded ? "1000px" : "0",
                          opacity: isExpanded ? 1 : 0,
                          transform: `translateY(${
                            isExpanded ? "0" : "-20px"
                          })`,
                          transition: isExpanded
                            ? "max-height 0.3s ease-in-out, opacity 0.3s ease-in-out 0.1s, transform 0.3s ease-in-out"
                            : "max-height 0.3s ease-in-out, opacity 0.2s ease-in-out, transform 0.3s ease-in-out",
                          overflow: "hidden",
                        }}
                      >
                        <div
                          style={{
                            animation: isExpanded
                              ? "slideInDown 0.4s ease-out"
                              : "none",
                          }}
                        >
                          <div className="slot-1-content">
                            <p className="secondary-para">
                              {summaryData?.slot?.tier}
                            </p>
                            <p className="secondary-para">1</p>
                          </div>
                          <div className="slot-1-content">
                            <p className="secondary-para">
                              {summaryData?.slot?.format}
                            </p>
                            <p className="secondary-para">
                              {event.advert_type?.toUpperCase()} ({event.format}
                              )
                            </p>
                          </div>
                          <div className="slot-1-content">
                            <p className="secondary-para">
                              {summaryData?.slot?.fileType}
                            </p>
                            <p className="secondary-para">{event.media_type}</p>
                          </div>
                          <div className="slot-event-content">
                            <p className="secondary-para">
                              {summaryData?.slot?.commune}
                            </p>
                            <p className="secondary-para">
                              {event.commune}, {event.postcode}
                            </p>
                          </div>
                          <div className="slot-event-content">
                            <p className="secondary-para">
                              {summaryData?.slot?.event}
                            </p>
                            <p
                              className="secondary-para"
                              style={{
                                textOverflow: "ellipsis",
                                maxWidth: "220px",
                                overflow: "hidden",
                              }}
                            >
                              {event.title}
                            </p>
                          </div>
                          <div className="slot-1-content">
                            <p className="secondary-para">
                              {summaryData?.slot?.duration}
                            </p>
                            <div
                              style={{
                                display: "flex",
                                alignItems: "center",
                                gap: "8px",
                              }}
                            >
                              <img
                                style={{
                                  cursor: "pointer",
                                  width: "16px",
                                  height: "16px",
                                }}
                                src="/pencil.png"
                                onClick={() =>
                                  handleDurationClick(event, index)
                                }
                                alt={
                                  sepData?.summary?.alt_edit_duration ||
                                  "Edit duration"
                                }
                                title={
                                  sepData?.summary?.alt_edit_duration ||
                                  "Edit duration"
                                }
                              />
                              <p
                                style={{
                                  color: "#299B13",
                                  fontSize: "1.25rem",
                                }}
                                className="secondary-para"
                              >
                                {event?.duration}{" "}
                                {sepData?.summary?.days ||
                                  summaryData?.days ||
                                  "days"}
                              </p>
                            </div>
                          </div>
                          {showPriceSelector && selectedEventForPrice && (
                            <div className="price-selector-modal-overlay">
                              <div className="price-selector-modal-content">
                                <PriceSelector
                                  event={selectedEventForPrice}
                                  onDurationSelect={handleDurationUpdate}
                                  initialSelectedDay={
                                    selectedEventForPrice.duration || 5
                                  }
                                />
                                <button
                                  className="close-price-selector-btn"
                                  onClick={() => {
                                    setShowPriceSelector(false);
                                    setSelectedEventForPrice(null);
                                    setSelectedEventIndex(null);
                                  }}
                                >
                                  ×
                                </button>
                              </div>
                            </div>
                          )}
                          <div className="advert">
                            <div className="slot-1-content">
                              <p className="secondary-para">
                                {summaryData.slot.advertStarts}
                              </p>
                              <p className="secondary-para">
                                {formatDate(event.startDate)}, 00h00
                              </p>
                            </div>
                            <div className="slot-1-content">
                              <p className="secondary-para">
                                {summaryData.slot.advertEnds}
                              </p>
                              <p className="secondary-para">
                                {formatDate(event.endDate)}, 23h59
                              </p>
                            </div>
                          </div>
                          <div
                            style={{ marginTop: "1rem" }}
                            className="slot-1-content"
                          >
                            <p
                              style={{ color: "#299B13", fontSize: "1.5rem" }}
                              className="secondary-para"
                            >
                              {summaryData.slot.totalTTC}
                            </p>
                            <p
                              style={{ color: "#299B13", fontSize: "1.6rem" }}
                              className="secondary-para"
                            >
                              {calculateTotalPriceForAllEvents(selectedEvents)}€
                            </p>
                          </div>

                          {index < selectedEvents.length - 1 && (
                            <div
                              style={{
                                margin: "2rem 0",
                                borderTop: "1px solid #e0e0e0",
                              }}
                            />
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })
              ) : (
                <div style={{ textAlign: "center", padding: "2rem 0" }}>
                  <p className="secondary-para" style={{ color: "#6A6C5E" }}>
                    {summaryData?.notes}
                  </p>
                  <p
                    className="secondary-para"
                    style={{
                      color: "#6A6C5E",
                      fontSize: "0.9rem",
                      marginTop: "0.5rem",
                    }}
                  >
                    {summaryData?.notes1}
                  </p>
                </div>
              )}

              {selectedEvents.length > 0 && (
                <p style={{ color: "#6A6C5E" }} className="secondary-para">
                  {summaryData?.common?.couponText}
                </p>
              )}

              {selectedEvents.length > 0 && (
                <div
                  style={{
                    display: "flex",
                    justifyContent: "center",
                    marginTop: "2rem",
                  }}
                >
                  <button
                    className="paymentBtn penta-heading"
                    onClick={onPayment}
                    disabled={isProcessingPayment}
                  >
                    <img
                      style={{ width: "50px" }}
                      src="/cart-white.png"
                      alt={sepData?.summary?.alt_cart || "Cart"}
                    />
                    {isProcessingPayment
                      ? `${summaryData?.process}`
                      : `${summaryData?.payment?.paymentButton}`}
                  </button>
                </div>
              )}
            </div>

            {/* open map */}
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: "1rem",
                marginTop: "2rem",
              }}
            >
              <p
                onClick={toggleMap}
                style={{ color: "#0066B4", textAlign: "center" }}
                className="tertiary-heading uppercase cursor-pointer"
              >
                {isMapVisible ? (
                  <>
                    {sepData?.map?.close_map || "Close"} <br />{" "}
                    {sepData?.map?.map_label || "Map"}
                  </>
                ) : (
                  " "
                )}
              </p>
              {isMapVisible ? (
                <img
                  className="rotated-image"
                  style={{ width: "40px", cursor: "pointer" }}
                  src="/open-map.png"
                  onClick={toggleMap}
                />
              ) : (
                ""
              )}
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default ServePortal;
