"use client";
import React, { useEffect, useState, useRef } from "react";
import "./table.css";
import {
  fetchUserCampaigns,
  deleteUserCampaign,
  postponeUserCampaign,
} from "@/app/redux/services/main/campaigns/mycampaign";
import Swal from "sweetalert2";
import { useAppDispatch, useAppSelector } from "@/app/hooks/useDispatch";
import { useRouter } from "next/navigation";
import { calculatePaidDays } from "@/app/utils/datehelpers";
import InvoiceModal from "./InvoiceView";
import { useSepTableData } from "@/app/hooks/useData";

const Adverts = () => {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { data: translations } = useSepTableData();
  const t = translations?.Section || {};
  const invoiceModalRef = useRef<HTMLDivElement>(null);
  const [invoiceModal, setInvoiceModal] = useState({
    isOpen: false,
    invoiceData: null as any,
  });
  const [statusFilter, setStatusFilter] = useState<
    "all" | "active" | "postponed"
  >("all");
  const { userCampaigns, userCampaignsLoading } = useAppSelector(
    (state) => state.advertcompaign
  );
  const [postponedCampaigns, setPostponedCampaigns] = useState<Set<number>>(
    new Set()
  );
  const filteredCampaigns = userCampaigns?.filter((campaign: any) => {
    if (statusFilter === "all") return true;
    if (statusFilter === "active") return campaign.status !== "postpone";
    if (statusFilter === "postponed") return campaign.status === "postpone";
    return true;
  });

  const [openDropdownId, setOpenDropdownId] = useState<number | null>(null);
  const [mediaModal, setMediaModal] = useState({
    isOpen: false,
    type: "",
    url: "",
  });
  const togglePostpone = async (campaignId: number) => {
    await dispatch(postponeUserCampaign(campaignId)).unwrap();
    setPostponedCampaigns((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(campaignId)) {
        newSet.delete(campaignId);
      } else {
        newSet.add(campaignId);
      }
      return newSet;
    });
  };

  useEffect(() => {
    dispatch(fetchUserCampaigns());
  }, [dispatch]);
useEffect(() => {
  const handleClickOutside = (event: MouseEvent) => {
    const modalContent = document.querySelector('.invoice-modal-content');
    const tableContent = document.querySelector('.table-card-content-parentdesktop-view');
    
    if (
      modalContent &&
      !modalContent.contains(event.target as Node) &&
      tableContent &&
      !tableContent.contains(event.target as Node) &&
      invoiceModal.isOpen
    ) {
      closeInvoiceModal();
    }
  };

  if (invoiceModal.isOpen) {
    document.addEventListener('mousedown', handleClickOutside);
    document.body.style.overflow = 'hidden';
  }

  return () => {
    document.removeEventListener('mousedown', handleClickOutside);
    document.body.style.overflow = 'unset';
  };
}, [invoiceModal.isOpen]);
  const handleDownloadInvoice = async (campaign: any) => {
    try {
      // Create invoice data for the campaign
      const invoiceData = {
        campaignId: campaign.id,
        campaignTitle: campaign.title,
        createdAt: campaign.created_at,
        organization: campaign.user.organization,
        name: campaign.user.name,
        address: campaign.user.address,
        userId: campaign.user_id,
        payment: campaign.payments?.[0] || {},
        totalAmount: campaign.payments?.[0]?.final_amount || "0.00",
        adverts:
          campaign.adverts?.map((advert: any) => ({
            advertId: advert.id,
            eventId: advert.event_id,
            eventTitle:
              advert.event?.title || advert.event?.event_no || "Untitled Event",
            eventNo: advert.event?.event_no,
            startDate: advert.start_date,
            endDate: advert.end_date,
            cost: advert.cost || "0.00",
            status: advert.status,
            price_per_day: advert.recorded_geo_price_per_day,
            geo_price_level: advert.geo_price_level,

            // Calculate days for each advert
            paidDays: calculatePaidDays(advert.start_date, advert.end_date),
          })) || [],

        // Media information
        mediaType: campaign.media_type,
        mediaFilePath: campaign.media_file_path,

        // Additional campaign details
        advertType: campaign.advert_type,
        status: campaign.status,
        userNotes: campaign.user_notes,
        adminNotes: campaign.admin_notes,
        discount: campaign.payments[0].discount,
      };
      setInvoiceModal({
        isOpen: true,
        invoiceData,
      });
      // await generateInvoicePDF(invoiceData);
    } catch (error) {
      console.error("Error downloading invoice:", error);
    }
  };
  const closeInvoiceModal = () => {
    setInvoiceModal({
      isOpen: false,
      invoiceData: null,
    });
  };
  const toggleDropdown = (campaignId: number, event: React.MouseEvent) => {
    event.stopPropagation();

    if (openDropdownId === campaignId) {
      setOpenDropdownId(null);
    } else {
      setOpenDropdownId(campaignId);
    }
  };

  useEffect(() => {
    if (openDropdownId !== null) {
      const handleClickOutside = () => {
        setOpenDropdownId(null);
      };

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

  const getEventData = (adverts: any[]) => {
    if (!adverts || adverts.length === 0)
      return [{ title: t.Common?.No_Events || "No events", slug: null }];

    return adverts.map((advert) => ({
      title:
        advert.event?.title ||
        advert.event?.event_no ||
        t.Common?.Untitled_Event ||
        "Untitled Event",
      slug: advert.event?.slug || null,
    }));
  };
  const handleEventClick = (slug: string | null) => {
    if (slug) {
      window.open(`https://eventx.fr/events/advert/${slug}`, "_blank");
      setOpenDropdownId(null);
    }
  };

  // Function to get file extension and determine media type
  const getMediaTypeFromPath = (filePath: string) => {
    if (!filePath) return "unknown";

    const extension = filePath.split(".").pop()?.toLowerCase();

    // Video extensions
    const videoExtensions = ["mp4", "mov", "avi", "wmv", "flv", "webm", "mkv"];
    // Rich text/document extensions
    const richTextExtensions = ["rtf", "doc", "docx", "txt", "pdf"];
    // Image extensions
    const imageExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "webp", "svg"];

    if (videoExtensions.includes(extension || "")) {
      return "video";
    } else if (richTextExtensions.includes(extension || "")) {
      return "richtext";
    } else if (imageExtensions.includes(extension || "")) {
      return "image";
    } else {
      return "unknown";
    }
  };
  const handleDeleteCampaign = async (campaignId: number) => {
    const result = await Swal.fire({
      title: t.SweetAlert?.Delete_Confirm_Title || "Are you sure?",
      text:
        t.SweetAlert?.Delete_Confirm_Text ||
        "You won't be able to revert this!",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#d33",
      cancelButtonColor: "#3085d6",
      confirmButtonText:
        t.SweetAlert?.Delete_Confirm_Button || "Yes, delete it!",
      cancelButtonText: t.SweetAlert?.Delete_Cancel_Button || "Cancel",
      reverseButtons: true,
      customClass: {
        confirmButton: "swal2-confirm",
        cancelButton: "swal2-cancel",
      },
    });

    if (result.isConfirmed) {
      try {
        await dispatch(deleteUserCampaign(campaignId)).unwrap();

        // Show success SweetAlert
        Swal.fire({
          title: t.SweetAlert?.Delete_Success_Title || "Deleted!",
          text:
            t.SweetAlert?.Delete_Success_Text ||
            "Your campaign has been deleted.",
          icon: "success",
          confirmButtonColor: "#3085d6",
          timer: 2000,
          showConfirmButton: false,
        });
      } catch (error: any) {
        console.error("Failed to delete campaign:", error);
        Swal.fire({
          title: t.SweetAlert?.Delete_Error_Title || "Error!",
          text:
            error ||
            t.SweetAlert?.Delete_Error_Text ||
            "Failed to delete campaign",
          icon: "error",
          confirmButtonColor: "#d33",
        });
      }
    }
  };
  const handleMediaPreviewClick = (campaign: any) => {
    const mediaType =
      campaign.media_type || getMediaTypeFromPath(campaign.media_file_path);
    const fileUrl = `${process.env.AWS_BUCKET}${campaign.media_file_path}`;

    setMediaModal({
      isOpen: true,
      type: mediaType,
      url: fileUrl,
    });
  };

  // Function to close media modal
  const closeMediaModal = () => {
    setMediaModal({ isOpen: false, type: "", url: "" });
  };
  const renderMediaPreview = (campaign: any) => {
    const mediaType =
      campaign.media_type || getMediaTypeFromPath(campaign.media_file_path);
    const filePath = campaign.media_file_path;
    const fileUrl = `${process.env.AWS_BUCKET}${filePath}`;

    switch (mediaType) {
      case "video":
        return (
          <div
            className="relative w-12 h-12 bg-gray-200 rounded flex items-center justify-center cursor-pointer hover:bg-gray-300 transition-colors"
            onClick={() => handleMediaPreviewClick(campaign)}
            title={t.Media_Modal?.Click_To_View_Video || "Click to view video"}
          >
            <svg
              className="w-6 h-6 text-gray-600"
              fill="currentColor"
              viewBox="0 0 24 24"
            >
              <path d="M8 5v14l11-7z" />
            </svg>
            <div className="absolute bottom-0 right-0 bg-black bg-opacity-70 text-white text-xs px-1 rounded-tl">
              MP4
            </div>
          </div>
        );

      case "richtext":
        return (
          <div
            className="relative w-12 h-12 bg-blue-100 rounded flex items-center justify-center cursor-pointer hover:bg-blue-200 transition-colors"
            onClick={() => handleMediaPreviewClick(campaign)}
            title={
              t.Media_Modal?.Click_To_View_Document || "Click to view document"
            }
          >
            <svg
              className="w-6 h-6 text-blue-600"
              fill="currentColor"
              viewBox="0 0 24 24"
            >
              <path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z" />
            </svg>
            <div className="absolute bottom-0 right-0 bg-blue-600 text-white text-xs px-1 rounded-tl">
              DOC
            </div>
          </div>
        );

      case "image":
      default:
        return (
          <div
            className="cursor-pointer"
            onClick={() => handleMediaPreviewClick(campaign)}
            title={t.Media_Modal?.Click_To_View_Image || "Click to view image"}
          >
            <img
              src={fileUrl || "/event-table-img.png"}
              alt={t.Alt_Text?.Ad || "Ad"}
              className="w-12 h-12 object-cover rounded hover:opacity-90 transition-opacity"
              onError={(e) => {
                // If image fails to load, show a fallback icon
                e.currentTarget.style.display = "none";
                const parent = e.currentTarget.parentElement;
                if (parent) {
                  const fallback = document.createElement("div");
                  fallback.className =
                    "w-12 h-12 bg-gray-200 rounded flex items-center justify-center cursor-pointer hover:bg-gray-300 transition-colors";
                  fallback.innerHTML = `
                    <svg class="w-6 h-6 text-gray-600" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/>
                    </svg>
                  `;
                  fallback.onclick = () => handleMediaPreviewClick(campaign);
                  parent.appendChild(fallback);
                }
              }}
            />
          </div>
        );
    }
  };

  // Function to render media modal content
  const renderMediaModalContent = () => {
    switch (mediaModal.type) {
      case "video":
        return (
          <div className="w-full max-w-4xl mx-auto">
            <video
              controls
              autoPlay
              className="w-full h-auto max-h-[80vh] rounded-lg"
            >
              <source src={mediaModal.url} type="video/mp4" />
              {t.Common?.Video_Not_Supported ||
                "Your browser does not support the video tag."}
            </video>
          </div>
        );

      case "richtext":
        return (
          <div className="w-full max-w-4xl mx-auto bg-white rounded-lg p-6">
            <div className="text-center mb-4">
              <svg
                className="w-16 h-16 text-blue-500 mx-auto mb-4"
                fill="currentColor"
                viewBox="0 0 24 24"
              >
                <path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z" />
              </svg>
              <h3 className="text-xl font-semibold text-gray-800">
                {t.Media_Modal?.Document || "document"}
              </h3>
              <p className="text-gray-600 mt-2">
                {t.Media_Modal?.Document_Description ||
                  "This is a document file that can be downloaded."}
              </p>
            </div>
          </div>
        );

      case "image":
        return (
          <div className="w-full max-w-4xl mx-auto">
            <img
              src={mediaModal.url}
              alt={t.Alt_Text?.Ad_Preview || "Ad preview"}
              className="w-full h-auto max-h-[80vh] object-contain rounded-lg"
            />
          </div>
        );

      default:
        return (
          <div className="text-center p-8">
            <p className="text-lg text-gray-600">
              {t.Media_Modal?.Unable_To_Preview ||
                "Unable to preview this file type."}
            </p>
          </div>
        );
    }
  };

  return (
    <>
      <h2 className="aileron-heavy text-[1.5rem] sm:text-[2rem] lg:text-[3.1rem] leading-none">
        {t.Title || "MY SEP CAMPAIGNS"}
      </h2>
      <p className="aileron-semibold text-[1.2rem] sm:text-[1.4rem] lg:text-[1.6rem] leading-none mt-2">
        {t.Subtitle || "By Event"}
      </p>

      {mediaModal.isOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4">
          <div className="relative bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-auto">
            <button
              onClick={closeMediaModal}
              className="absolute top-4 right-4 text-gray-500 hover:text-gray-700 z-10 bg-white rounded-full p-2"
            >
              <svg
                className="w-6 h-6"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
            <div className="p-6">{renderMediaModalContent()}</div>
          </div>
        </div>
      )}

      <div
        style={{ boxShadow: "rgba(0, 0, 0, 0.24) 0px 3px 8px" }}
        className="bg-[#F2F2F2] rounded-lg p-3 sm:p-4 lg:p-5 flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 sm:gap-6 lg:gap-8 mt-4 sm:mt-5 mb-8 sm:mb-10 lg:mb-12"
      >
        <select
          className="bg-white p-2.5 sm:p-3 w-full sm:w-2/6 rounded-lg border-[0.25px] border-grey text-[0.95rem] sm:text-[1rem] lg:text-[1.1rem] aileron-semibold"
          name=""
          id=""
          value={statusFilter}
          onChange={(e) =>
            setStatusFilter(e.target.value as "all" | "active" | "postponed")
          }
        >
          <option value="active">{t.Filters?.Filter_2 || "Online"}</option>
          <option value="postponed"></option>
          <option value="all">{t.Filters?.Filter_1 || "All"}</option>
        </select>

        <button
          onClick={() => router.push("/campaigns/createSepCampaigns")}
          className="bg-gradient-to-r from-[#C1272D] to-[#a02025] hover:from-[#a02025]  hover:to-[#8a1b20] text-white px-4 sm:px-6 lg:px-8 py-2.5 sm:py-3 rounded-lg text-[0.95rem] sm:text-[1rem] lg:text-[1.1rem] aileron-bold transition-all duration-300 flex items-center justify-center gap-2 sm:gap-3 shadow-lg hover:shadow-xl transform hover:scale-105 w-full sm:w-auto"
        >
          <svg
            width="18"
            height="18"
            className="sm:w-5 sm:h-5"
            viewBox="0 0 24 24"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M12 5V19M5 12H19"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          <span>{t.Buttons?.Add_New_Campaign || "Add New Campaign"}</span>
        </button>
      </div>

      {/* Table Container with proper responsiveness */}
      <div className="w-full mt-4 sm:mt-5">
        {invoiceModal.isOpen && (
          <div
            className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4"
          >
            <div
              className="relative bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-auto"
              onClick={(e) => e.stopPropagation()}
            >
              <button
                onClick={closeInvoiceModal}
                className="absolute top-4 right-4 text-gray-500 hover:text-gray-700 z-10 bg-white rounded-full p-2"
              >
                <svg
                  className="w-6 h-6"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M6 18L18 6M6 6l12 12"
                  />
                </svg>
              </button>
              <InvoiceModal
                isOpen={invoiceModal.isOpen}
                onClose={closeInvoiceModal}
                invoiceData={invoiceModal.invoiceData}
              />
            </div>
          </div>
        )}

        {/* Desktop Table (hidden on mobile) */}
        <div className=" table-card-content-parentdesktop-view " ref={invoiceModalRef}>
          <div className="overflow-hidden sm:rounded-md">
            <table className="min-w-full bg-white">
              <thead>
                <tr className="text-xs leading-4 tracking-wider border-b">
                  <th className="px-3 xl:px-6 py-3 text-center aileron-bold">
                    <p>
                      {(t.Table_Columns?.Column_1 || "Ad Id").split(" ")[0]}{" "}
                      {(t.Table_Columns?.Column_1 || "Ad Id").split(" ")[1]}
                    </p>
                  </th>
                  <th className="px-3 xl:px-6 py-3 text-center aileron-bold">
                    <p>{t.Table_Columns?.Column_2 || "Ad Size"}</p>
                  </th>
                  <th className="px-3 xl:px-6 py-3 text-center aileron-bold">
                    <p>{t.Table_Columns?.Column_3 || "Ad Type"}</p>
                  </th>
                  <th className="px-3 xl:px-6 py-3 text-center aileron-bold">
                    <p>{t.Table_Columns?.Column_4 || "Actions"}</p>
                  </th>
                  <th className="px-3 xl:px-6 py-3 text-center aileron-bold">
                    <p>{t.Table_Columns?.Column_5 || "Postpone"}</p>
                  </th>
                  <th className="px-3 xl:px-6 py-3 text-center aileron-bold">
                    <p>{t.Table_Columns?.Column_6 || "Stats"}</p>
                  </th>
                  <th className="px-2 xl:px-6 py-3 text-center aileron-bold">
                    <p>{t.Table_Columns?.Column_7 || "Bill.pdf"}</p>
                  </th>
                  <th className="px-3 xl:px-6 py-3 text-center aileron-bold">
                    <p>{t.Table_Columns?.Column_8 || "Refunded"}</p>
                  </th>
                  <th className="px-3 xl:px-6 py-3 text-center aileron-bold">
                    <p>{t.Table_Columns?.Column_9 || "Cost€"}</p>
                  </th>
                  <th className="px-3 xl:px-6 py-3 text-center aileron-bold">
                    <p>{t.Table_Columns?.Column_10 || "Notes"}</p>
                  </th>
                </tr>
              </thead>
              <tbody>
                {userCampaignsLoading ? (
                  <tr>
                    <td colSpan={10} className="px-6 py-8 text-center">
                      <p className="aileron-semibold text-[1.2rem] sm:text-[1.4rem] text-gray-500">
                        {t.Loading?.Loading_Campaigns || "Loading campaigns"}
                      </p>
                    </td>
                  </tr>
                ) : (
                  filteredCampaigns?.map((campaign: any) => (
                    <tr
                      key={`${campaign.id}`}
                      className="bg-[#fafdff] border-b hover:bg-gray-50"
                    >
                      <td className="px-3 xl:px-6 py-4 whitespace-no-wrap">
                        <div className="flex items-center justify-center">
                          <p className="avenir-roman text-sm">
                            {campaign.title}
                          </p>
                        </div>
                      </td>
                      <td className="px-3 xl:px-6 py-4 whitespace-no-wrap">
                        <div className="flex items-center justify-center">
                          {renderMediaPreview(campaign)}
                        </div>
                      </td>
                      <td className="px-3 xl:px-6 py-4 whitespace-no-wrap">
                        <div className="flex items-center justify-center">
                          <p className="text-sm">
                            {campaign.advert_type ||
                              t.Common?.Medium ||
                              "Medium"}
                          </p>
                        </div>
                      </td>
                      <td className="px-3 xl:px-6 py-4 whitespace-no-wrap">
                        <div className="flex items-center justify-center gap-2 relative">
                          <div className="relative inline-block">
                            <img
                              className="cursor-pointer w-5 h-5"
                              src="/blue-eye-icon.png"
                              alt={t.Alt_Text?.View_Events || "View Events"}
                              onClick={(e) => toggleDropdown(campaign.id, e)}
                            />
                            <img
                              className="cursor-pointer w-5 h-5 mt-[3px]"
                              src="/delete-icon.png"
                              alt={t.Alt_Text?.Delete || "Delete"}
                              onClick={() => handleDeleteCampaign(campaign.id)}
                            />
                            {openDropdownId === campaign.id && (
                              <div
                                className="absolute right-50px top-[30px] mt-1 w-64 bg-white border border-gray-200 rounded-lg shadow-lg z-50 max-h-60 overflow-y-auto dropdown-container"
                                onClick={(e) => e.stopPropagation()}
                                ref={(el) => {
                                  if (el) {
                                    // Check if dropdown would go off-screen
                                    const rect = el.getBoundingClientRect();
                                    const viewportHeight = window.innerHeight;

                                    if (rect.bottom > viewportHeight - 20) {
                                      // Position above instead of below
                                      el.style.top = "auto";
                                      el.style.bottom = "100%";
                                      el.style.marginTop = "0";
                                      el.style.marginBottom = "5px";
                                    }
                                  }
                                }}
                              >
                                <div className="p-3">
                                  <h4 className="font-semibold text-gray-800 mb-2 border-b pb-2">
                                    {t.Dropdown?.Events_In_Campaign ||
                                      "Events in Campaign"}
                                  </h4>
                                  <div className="space-y-2">
                                    {getEventData(campaign.adverts || []).map(
                                      (event, index) => (
                                        <div
                                          key={index}
                                          className={`p-2 rounded cursor-pointer text-sm border-b last:border-b-0 ${
                                            event.slug
                                              ? "hover:bg-gray-100 text-gray-700"
                                              : "text-gray-400 cursor-not-allowed"
                                          }`}
                                          onClick={() =>
                                            handleEventClick(event.slug)
                                          }
                                        >
                                          {event.title}
                                          {!event.slug && (
                                            <span className="text-xs text-gray-500 ml-1">
                                              {t.Dropdown?.No_Link ||
                                                "(No link)"}
                                            </span>
                                          )}
                                        </div>
                                      )
                                    )}
                                  </div>
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="px-3 xl:px-6 py-4 whitespace-no-wrap">
                        <div className="flex items-center justify-center">
                          <label className="relative inline-block w-10 h-5 cursor-pointer">
                            <input
                              type="checkbox"
                              checked={campaign.status === "postpone"}
                              onChange={() => togglePostpone(campaign.id)}
                              className="hidden"
                            />
                            <div
                              className={`absolute inset-0 border-2 rounded-full transition-all duration-200 ${
                                postponedCampaigns.has(campaign.id) ||
                                campaign.status === "postpone"
                                  ? "border-green-500 bg-green-100"
                                  : "border-black bg-white"
                              }`}
                            ></div>
                            <div
                              className={`absolute top-1/2 -translate-y-1/2 w-3.5 h-3.5 rounded-full transition-all duration-200 ${
                                postponedCampaigns.has(campaign.id) ||
                                campaign.status === "postpone"
                                  ? "left-[calc(100%-1.1rem)] bg-green-500"
                                  : "left-[0.2rem] bg-black"
                              }`}
                            ></div>
                          </label>
                        </div>
                      </td>
                      <td className="px-3 xl:px-6 py-4 whitespace-no-wrap">
                        <div className="flex items-center justify-center">
                          <img
                            className="cursor-pointer w-5 h-5"
                            src="/blue-eye-icon.png"
                            alt={t.Alt_Text?.Stats || "Stats"}
                          />
                        </div>
                      </td>
                      <td className="px-2 xl:px-6 py-4 whitespace-no-wrap">
                        <div
                          className="flex items-center justify-center"
                          onClick={() => handleDownloadInvoice(campaign)}
                        >
                          <img
                            className="cursor-pointer w-5 h-5"
                            src="/blue-eye-icon.png"
                            alt={t.Alt_Text?.Invoice || "Invoice"}
                          />
                        </div>
                      </td>
                      <td className="px-3 xl:px-6 py-4 whitespace-no-wrap">
                        <div className="flex items-center justify-center">
                          <img
                            className="cursor-pointer w-5 h-5"
                            src="/red-circle.png"
                            alt={t.Alt_Text?.Refund || "Refund"}
                          />
                        </div>
                      </td>
                      <td className="px-3 xl:px-6 py-4 whitespace-no-wrap">
                        <div className="flex items-center justify-center">
                          <p className="avenir-roman text-sm">
                            {campaign.payments?.[0]?.final_amount || "0"}
                          </p>
                        </div>
                      </td>
                      <td className="px-3 xl:px-6 py-4 whitespace-no-wrap">
                        <div className="flex items-center justify-center">
                          <img
                            className="cursor-pointer w-5 h-5"
                            src="/blue-eye-icon.png"
                            alt={t.Alt_Text?.Notes || "Notes"}
                          />
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Mobile/Tablet Card View (visible below 1024px) */}
        <div className="space-y-4 table-card-content-parentmobile-view">
          {userCampaignsLoading ? (
            <div className="bg-white rounded-lg shadow p-6 text-center">
              <p className="aileron-semibold text-[1.2rem] text-gray-500">
                {t.Loading?.Loading_Campaigns || "Loading campaigns"}
              </p>
            </div>
          ) : (
            filteredCampaigns?.map((campaign: any) => (
              <div
                key={`${campaign.id}`}
                className="bg-[#fafdff] rounded-lg shadow-md p-4 sm:p-5 space-y-3"
              >
                {/* Row 1: Ad ID, Ad Type, Cost, Ad Size */}
                <div className="flex items-center justify-between border-b pb-3">
                  <div className="flex-1">
                    <p className="text-xs text-gray-500 aileron-bold mb-1">
                      {t.Mobile_View?.Ad_ID || "Ad ID"}
                    </p>
                    <p className="avenir-roman text-base font-semibold">
                      {campaign.id}
                    </p>
                  </div>
                  <div className="flex-1 text-center">
                    <p className="text-xs text-gray-500 aileron-bold mb-1">
                      {t.Mobile_View?.Ad_Type || "Ad Type"}
                    </p>
                    <p className="text-sm">
                      {campaign.advert_type || t.Common?.Medium || "Medium"}
                    </p>
                  </div>
                  <div className="flex-1 text-center">
                    <p className="text-xs text-gray-500 aileron-bold mb-1">
                      {t.Mobile_View?.Cost || "Cost€"}
                    </p>
                    <p className="avenir-roman text-sm font-semibold">
                      {campaign.payments?.[0]?.final_amount || "0"}
                    </p>
                  </div>
                  <div className="flex-1 flex flex-col items-end">
                    <p className="text-xs text-gray-500 aileron-bold mb-1">
                      {t.Mobile_View?.Ad_Size || "Ad Size"}
                    </p>
                    {renderMediaPreview(campaign)}
                  </div>
                </div>

                {/* Row 2: Actions, Postpone, Refund */}
                <div className="flex items-center justify-between border-b pb-3">
                  <div className="flex-1 text-center">
                    <p className="text-xs text-gray-500 aileron-bold mb-2">
                      {t.Mobile_View?.Postpone || "Postpone"}
                    </p>
                    <div className="flex justify-center">
                      <label className="relative inline-block w-10 h-5 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={postponedCampaigns.has(campaign.id)}
                          onChange={() => togglePostpone(campaign.id)}
                          className="hidden"
                        />
                        <div
                          className={`absolute inset-0 border-2 rounded-full transition-all duration-200 ${
                            postponedCampaigns.has(campaign.id)
                              ? "border-green-500 bg-green-100"
                              : "border-black bg-white"
                          }`}
                        ></div>
                        <div
                          className={`absolute top-1/2 -translate-y-1/2 w-3.5 h-3.5 rounded-full transition-all duration-200 ${
                            postponedCampaigns.has(campaign.id)
                              ? "left-[calc(100%-1.1rem)] bg-green-500"
                              : "left-[0.2rem] bg-black"
                          }`}
                        ></div>
                      </label>
                    </div>
                  </div>
                  <div className="flex-1 text-center">
                    <p className="text-xs text-gray-500 aileron-bold mb-1">
                      {t.Mobile_View?.Refund || "Refund"}
                    </p>
                    <img
                      className="cursor-pointer w-6 h-6 mx-auto"
                      src="/red-circle.png"
                      alt={t.Alt_Text?.Refund || "Refund"}
                    />
                  </div>
                  <div className="flex-1">
                    <p className="text-xs text-gray-500 text-center aileron-bold mb-1">
                      {t.Mobile_View?.Actions || "Actions"}
                    </p>
                    <div className="flex items-center justify-center gap-3">
                      <div className="relative">
                        <img
                          className="cursor-pointer w-6 h-6"
                          src="/blue-eye-icon.png"
                          alt={t.Alt_Text?.View || "View"}
                          onClick={(e) => toggleDropdown(campaign.id, e)}
                        />
                        {openDropdownId === campaign.id && (
                          <div
                            className="absolute right-0 top-[30px] mt-1 w-64 bg-white border border-gray-200 rounded-lg shadow-lg z-50 max-h-60 overflow-y-auto"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <div className="p-3">
                              <h4 className="font-semibold text-gray-800 mb-2 border-b pb-2">
                                {t.Dropdown?.Events_In_Campaign ||
                                  "Events in Campaign"}
                              </h4>
                              <div className="space-y-2">
                                {getEventData(campaign.adverts || []).map(
                                  (event, index) => (
                                    <div
                                      key={index}
                                      className={`p-2 rounded cursor-pointer text-sm border-b last:border-b-0 ${
                                        event.slug
                                          ? "hover:bg-gray-100 text-gray-700"
                                          : "text-gray-400 cursor-not-allowed"
                                      }`}
                                      onClick={() =>
                                        handleEventClick(event.slug)
                                      }
                                    >
                                      {event.title}
                                      {!event.slug && (
                                        <span className="text-xs text-gray-500 ml-1">
                                          {t.Dropdown?.No_Link || "(No link)"}
                                        </span>
                                      )}
                                    </div>
                                  )
                                )}
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                      <img
                        className="cursor-pointer w-6 h-6"
                        src="/delete-icon.png"
                        alt={t.Alt_Text?.Delete || "Delete"}
                        onClick={() => handleDeleteCampaign(campaign.id)}
                      />
                    </div>
                  </div>
                </div>

                {/* Row 3: Stats, Bill.pdf, Notes */}
                <div className="flex items-center justify-between pt-2">
                  <div className="text-center flex-1">
                    <p className="text-xs text-gray-500 aileron-bold mb-1">
                      {t.Mobile_View?.Stats || "Stats"}
                    </p>
                    <img
                      className="cursor-pointer w-6 h-6 mx-auto"
                      src="/blue-eye-icon.png"
                      alt={t.Alt_Text?.Stats || "Stats"}
                    />
                  </div>
                  <div className="text-center flex-1">
                    <p className="text-xs text-gray-500 aileron-bold mb-1">
                      {t.Mobile_View?.Bill_Pdf || "Bill.pdf"}
                    </p>
                    <img
                      className="cursor-pointer w-6 h-6 mx-auto"
                      src="/blue-eye-icon.png"
                      alt={t.Alt_Text?.Invoice || "Invoice"}
                      onClick={() => handleDownloadInvoice(campaign)}
                    />
                  </div>
                  <div className="text-center flex-1">
                    <p className="text-xs text-gray-500 aileron-bold mb-1">
                      {t.Mobile_View?.Notes || "Notes"}
                    </p>
                    <img
                      className="cursor-pointer w-6 h-6 mx-auto"
                      src="/blue-eye-icon.png"
                      alt={t.Alt_Text?.Notes || "Notes"}
                    />
                  </div>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </>
  );
};

export default Adverts;
