"use client";

import { ReactNode, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import { MapPin, Phone, UserRound } from "lucide-react";
import Image from "next/image";
import { BaseModal } from "@/components/modal";
import DynamicButton from "@/components/button";
import { useTranslations, useLocale } from "next-intl";
import axios from "axios";
import { useSession } from "@/auth/session-provider";
import { useAppToast } from "@/app/[lang]/providers";
import { useSetAtom } from "jotai";
import { loginModalAtom } from "@/components/state/loginAtom";
import { useWalletBalances } from "@/lib/clientQueries";
import { usePaymentSuccess } from "@/hooks/usePaymentSuccess";
import { usePaymentFailure } from "@/hooks/usePaymentFailure";
import { usePaymentCancelled } from "@/hooks/usePaymentCancelled";
import TopUpModal from "@/components/sections/wallet/TopUpModal";
import PaymentMethodSelector from "@/components/payment/PaymentMethodSelector";
import CamelDetailsSection from "../autionClient/parts/CamelDetails";
import SellerReviewsSection from "@/components/reviews/SellerReviewsSection";
import MediaSection from "./parts/MediaSection";
import VideosSection from "./parts/VideosSection";
import DocumentsSection from "./parts/DocumentsSection";
import Money from "@/components/ui/Money";
import PdfViewer from "@/components/viewers/PdfViewer";
import { AR_LOCALE_LATIN_DIGITS } from "@/lib/arDateFormat";
import { isValidLatLng, parseCoord } from "@/lib/coordinates";
import LocationMapView from "@/components/maps/LocationMapView";
import MobileActionBar, {
  MobileActionBarPrice,
  MobileActionBarButton,
} from "@/components/ui/MobileActionBar";
import DetailsCustom, {
  type DetailsSection,
} from "@/components/details-custom";
import ShareModal from "@/components/ShareModal";
import { API_BASE_URL } from "@/lib/axios";
import {
  getVaccinationStatusForDisplay,
  vaccinationStatusValueLabel,
} from "@/lib/animalVaccinationStatus";
import { parseMoneyValue, toMoneyNumber } from "@/lib/moneyParse";

const SAR_ICON = "/Riyal.svg";

const API_URL = API_BASE_URL;

const getYoutubeId = (url: string): string | null => {
  try {
    const u = new URL(url);
    const host = u.hostname;

    if (host.includes("youtu.be")) {
      const parts = u.pathname.split("/").filter(Boolean);
      return parts[0] || null;
    }

    if (host.includes("youtube.com")) {
      if (u.pathname === "/watch") {
        return u.searchParams.get("v");
      }

      if (u.pathname.startsWith("/shorts/")) {
        const parts = u.pathname.split("/").filter(Boolean);
        return parts[1] || null;
      }

      if (u.pathname.startsWith("/embed/")) {
        const parts = u.pathname.split("/").filter(Boolean);
        return parts[1] || null;
      }
    }
  } catch {
    return null;
  }

  return null;
};

const extractUrl = (v: any): string => {
  if (!v) return "";
  if (typeof v === "string") return v;
  if (typeof v === "object" && typeof v.url === "string") return v.url;
  return "";
};

const getDocKind = (url: string): "pdf" | "image" | "other" => {
  const v = (url || "").toLowerCase();
  if (v.endsWith(".pdf")) return "pdf";
  if (v.match(/\.(jpg|jpeg|png|gif|webp)$/i)) return "image";
  return "other";
};

function formatOfferCreatedAt(value: unknown, locale: string): string | null {
  if (value == null || String(value).trim() === "") return null;
  const d = new Date(String(value));
  if (Number.isNaN(d.getTime())) return String(value);
  const ar = (locale || "").toLowerCase().startsWith("ar");
  try {
    return new Intl.DateTimeFormat(ar ? AR_LOCALE_LATIN_DIGITS : "en-US", {
      dateStyle: "medium",
      timeStyle: "short",
    }).format(d);
  } catch {
    return d.toLocaleString("en-US");
  }
}

export default function HorseDetailsClient({ data }: { data: any }) {
  const router = useRouter();
  const t = useTranslations("HORSES_DETAILS");
  const tToast = useTranslations("TOAST");
  const tFilters = useTranslations("AUCTIONS_FILTERS");
  const tAuctionCard = useTranslations("AUCTION_CARD");
  const tAuctionSidebar = useTranslations("SINGLE_AUCTION.SIDEBAR");
  const tStep4 = useTranslations("ADD_LISTING.STEP4");
  const tVax = useTranslations("ANIMAL_VACCINATION_STATUS");
  const lang = useLocale();
  const session = useSession();
  const toast = useAppToast();
  const setLoginModal = useSetAtom(loginModalAtom);
  const { data: walletBalances } = useWalletBalances();

  const [depositModalOpen, setDepositModalOpen] = useState(false);
  const [successModalOpen, setSuccessModalOpen] = useState(false);
  const [invoiceModalOpen, setInvoiceModalOpen] = useState(false);
  const [videoModalOpen, setVideoModalOpen] = useState(false);
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [lightboxImg, setLightboxImg] = useState("");
  const [videoUrl, setVideoUrl] = useState("");
  const [docPreviewOpen, setDocPreviewOpen] = useState(false);
  const [selectedDocument, setSelectedDocument] = useState<{
    url: string;
    title: string;
    kind: "pdf" | "image" | "other";
  } | null>(null);
  const [depositPaid, setDepositPaid] = useState(false);
  const [fullPaid, setFullPaid] = useState(false);
  const [depositPaidAt, setDepositPaidAt] = useState<number | null>(null);
  const [timeLeft, setTimeLeft] = useState("");
  const [payFull, setPayFull] = useState(false);
  const [showTopUpModal, setShowTopUpModal] = useState(false);
  const [topUpNoticeOpen, setTopUpNoticeOpen] = useState(false);
  const [shareOpen, setShareOpen] = useState(false);

  const isOwner = Boolean(data?.is_owner);

  const getHorseTypeLabel = (raw: any): string => {
    let key = String(raw || "").trim();

    if (!key) return "—";

    // Sometimes the API sends the full translation key
    // e.g. "ADD_LISTING.STEP4.type_options.foal_female"
    if (key.includes(".")) {
      const parts = key.split(".");
      key = parts[parts.length - 1] || key;
    }

    if (key === "male") return tStep4("type_options.male");
    if (key === "castrated") return tStep4("type_options.castrated");
    if (key === "breeding_female")
      return tStep4("type_options.horse_breeding_female");
    if (key === "non_breeding_female")
      return tStep4("type_options.horse_non_breeding_female");
    if (key === "foal_male") return tStep4("type_options.foal_male");
    if (key === "foal_female") return tStep4("type_options.foal_female");

    // Fallback: try to map unknown values to a type_options key
    try {
      return tStep4(`type_options.${key}` as any);
    } catch {
      return key;
    }
  };

  const wallet = toMoneyNumber(walletBalances?.available_balance, 0);
  const fullPrice = toMoneyNumber(data?.price, 0);
  const depositAmount = toMoneyNumber(data?.deposit, 0);

  const isCamelOffer = data?.animal_type === "camel";

  const invoice = data?.invoice_details;
  const invoiceBaseAmount = toMoneyNumber(invoice?.base_amount ?? fullPrice, 0);
  const invoiceCommissionAmount = toMoneyNumber(invoice?.commission_amount, 0);
  const invoiceCommissionPct = toMoneyNumber(invoice?.commission_percentage, 0);
  const invoiceTaxAmount = toMoneyNumber(invoice?.tax_amount, 0);
  const invoiceTaxPct = toMoneyNumber(invoice?.tax_percentage, 0);
  const invoiceTotalAmount = toMoneyNumber(
    invoice?.total_amount,
    invoiceBaseAmount + invoiceCommissionAmount + invoiceTaxAmount,
  );

  const [commissionPctFromConfig, setCommissionPctFromConfig] = useState<
    number | null
  >(null);

  useEffect(() => {
    const pctNum = parseMoneyValue(invoiceCommissionPct);
    if (pctNum !== undefined && pctNum > 0) return;
    if (isCamelOffer) return;
    if (!API_URL) return;

    let cancelled = false;

    axios
      .get(`${API_URL}/user/config/reference-data`, {
        params: {
          animal_type: "horse",
          fees_setting: 1,
        },
        headers: {
          Accept: "application/json",
        },
      })
      .then((res) => {
        if (cancelled) return;
        const pct = parseMoneyValue(
          res?.data?.data?.fees_setting?.buyer_commission_percentage,
        );
        if (pct !== undefined) setCommissionPctFromConfig(pct);
      })
      .catch(() => {
        // ignore
      });

    return () => {
      cancelled = true;
    };
  }, [invoiceCommissionPct, isCamelOffer]);

  const effectiveCommissionPct = (() => {
    const pctNum = parseMoneyValue(invoiceCommissionPct);
    if (pctNum !== undefined && pctNum > 0) return pctNum;
    const cfgNum =
      commissionPctFromConfig != null
        ? parseMoneyValue(commissionPctFromConfig)
        : undefined;
    if (cfgNum !== undefined && cfgNum > 0) return cfgNum;
    return 5;
  })();

  const requiredNow = payFull ? fullPrice : depositAmount;
  const invoiceRemainingAmount = Math.max(0, invoiceTotalAmount - requiredNow);
  const topUpShortfall = Math.max(0, requiredNow - wallet);

  const horse = data?.horse || {};
  const images = data?.media_files?.additional_images?.length
    ? data.media_files.additional_images.map((i: any) => i.url)
    : [data?.media_files?.main_image?.url].filter(Boolean);

  const status = data?.status;
  const isSold = status === "sold";
  const location = [data?.state, data?.country].filter(Boolean).join(", ");

  const offerMapLat = parseCoord(data?.lat);
  const offerMapLng = parseCoord(data?.lng);
  const showOfferMap =
    offerMapLat != null &&
    offerMapLng != null &&
    isValidLatLng(offerMapLat, offerMapLng);

  const rawVideos = data?.videos ?? data?.video_links ?? [];
  const videos = Array.isArray(rawVideos)
    ? rawVideos
        .map((v: any, index: number) => {
          const originalUrl = typeof v === "string" ? v : v?.url;
          if (!originalUrl) return null;

          const videoId = getYoutubeId(originalUrl);

          const thumbnail = videoId
            ? `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`
            : data?.media_files?.main_image?.url ||
              "https://endpoint-dev.diriw.com/storage/images/default/default.webp";

          const embedUrl = videoId
            ? `https://www.youtube.com/embed/${videoId}?autoplay=1`
            : originalUrl;

          return {
            id: index + 1,
            thumbnail,
            url: embedUrl,
          };
        })
        .filter(
          (item): item is { id: number; thumbnail: string; url: string } =>
            Boolean(item),
        )
    : [];

  // Include direct video file if present
  const directVideoUrl = extractUrl(data?.media_files?.video);
  if (directVideoUrl && !videos.some((v) => v.url === directVideoUrl)) {
    videos.push({
      id: videos.length + 1,
      thumbnail:
        data?.media_files?.main_image?.url ||
        "https://endpoint-dev.diriw.com/storage/images/default/default.webp",
      url: directVideoUrl,
    });
  }

  // Handle returning from external payment success/failure
  usePaymentSuccess();
  usePaymentFailure();
  usePaymentCancelled();

  useEffect(() => {
    if (!depositPaidAt || fullPaid) return;
    const update = () => {
      const remain = Math.max(
        0,
        3 * 24 * 60 * 60 * 1000 - (Date.now() - depositPaidAt),
      );
      if (remain === 0) {
        setTimeLeft("انتهت المهلة");
        return;
      }
      const d = Math.floor(remain / (24 * 60 * 60 * 1000));
      const h = Math.floor((remain % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
      const m = Math.floor((remain % (60 * 60 * 1000)) / (60 * 1000));
      setTimeLeft(`${d} يوم و ${h} ساعة و ${m} دقيقة`);
    };
    update();
    const interval = setInterval(update, 60000);
    return () => clearInterval(interval);
  }, [depositPaidAt, fullPaid]);

  const openVideo = (url: string) => {
    setVideoUrl(url);
    setVideoModalOpen(true);
  };

  const openLightbox = (img: string) => {
    setLightboxImg(img);
    setLightboxOpen(true);
  };

  const openDocumentPreview = (url: string, title: string) => {
    if (!url) return;
    setSelectedDocument({ url, title, kind: getDocKind(url) });
    setDocPreviewOpen(true);
  };

  const formatPrice = (p: number) => p?.toLocaleString("en-US");

  const formatBirthDate = (dateStr?: string) => {
    if (!dateStr) return "";
    const d = new Date(dateStr);
    if (isNaN(d.getTime())) return dateStr;
    const day = String(d.getDate()).padStart(2, "0");
    const month = String(d.getMonth() + 1).padStart(2, "0");
    const year = d.getFullYear();
    return `${day}-${month}-${year}`;
  };

  const getAgeFromBirthDate = (dateStr?: string) => {
    if (!dateStr) return "";
    const birth = new Date(dateStr);
    if (isNaN(birth.getTime())) return "";
    const now = new Date();
    let years = now.getFullYear() - birth.getFullYear();
    const m = now.getMonth() - birth.getMonth();
    if (m < 0 || (m === 0 && now.getDate() < birth.getDate())) {
      years--;
    }
    if (years < 0) return "";
    return `${years} سنة`;
  };

  const buyOfferPaymentParams = {
    payment_purpose: "buy_offer",
    offer_id: data?.id ? String(data.id) : undefined,
    payment_type: payFull ? "full" : "deposit",
  };

  const handlePaymentSuccess = () => {
    setDepositModalOpen(false);
    setSuccessModalOpen(true);
    if (payFull) {
      setFullPaid(true);
      setDepositPaid(false);
      setDepositPaidAt(null);
    } else {
      setDepositPaid(true);
      setFullPaid(false);
      setDepositPaidAt(Date.now());
    }
  };

  type DetailRow = { key: string; label: string; value: ReactNode };

  const horsePrimaryDetails: DetailRow[] = [];
  if (horse?.name) {
    horsePrimaryDetails.push({
      key: "name",
      label: t("name"),
      value: horse.name,
    });
  }
  if (horse?.type) {
    horsePrimaryDetails.push({
      key: "type",
      label: t("type"),
      value: getHorseTypeLabel(horse.type),
    });
  }
  if (horse?.breed) {
    horsePrimaryDetails.push({
      key: "breed",
      label: t("breed"),
      value: horse.breed,
    });
  }
  if (horse?.date_of_birth) {
    horsePrimaryDetails.push({
      key: "dateOfBirth",
      label: t("dateOfBirth"),
      value: formatBirthDate(horse.date_of_birth),
    });
    horsePrimaryDetails.push({
      key: "age",
      label: t("age"),
      value: getAgeFromBirthDate(horse.date_of_birth),
    });
  }
  if (horse?.gender) {
    horsePrimaryDetails.push({
      key: "gender",
      label: t("gender"),
      value:
        horse.gender === "male"
          ? t("male")
          : horse.gender === "female"
            ? t("female")
            : horse.gender,
    });
  }
  if (horse?.father_name) {
    horsePrimaryDetails.push({
      key: "fatherName",
      label: t("fatherName"),
      value: horse.father_name,
    });
  }

  const horseSecondaryDetails: DetailRow[] = [];
  if (horse?.height) {
    horseSecondaryDetails.push({
      key: "height",
      label: t("height"),
      value: `${horse.height} سم`,
    });
  }
  if (horse?.animal_color) {
    horseSecondaryDetails.push({
      key: "color",
      label: t("color"),
      value: horse.animal_color,
    });
  }
  if (horse?.animal_usage) {
    horseSecondaryDetails.push({
      key: "usage",
      label: t("usage"),
      value: horse.animal_usage,
    });
  }
  if (horse?.mother_name) {
    horseSecondaryDetails.push({
      key: "motherName",
      label: t("motherName"),
      value: horse.mother_name,
    });
  }
  if (horse?.mother_father_name) {
    horseSecondaryDetails.push({
      key: "motherFatherName",
      label: t("motherFatherName"),
      value: horse.mother_father_name,
    });
  }
  const offerVax = horse ? getVaccinationStatusForDisplay(horse) : null;
  if (offerVax) {
    horseSecondaryDetails.push({
      key: "vaccination_status",
      label: tVax("label"),
      value: vaccinationStatusValueLabel(offerVax, tVax),
    });
  }

  const horseRowsPerColumn = Math.max(
    horsePrimaryDetails.length,
    horseSecondaryDetails.length,
  );

  const paddedHorsePrimaryDetails = [
    ...horsePrimaryDetails,
    ...Array.from(
      { length: Math.max(0, horseRowsPerColumn - horsePrimaryDetails.length) },
      (_, index) => ({
        key: `primary-empty-${index}`,
        label: "",
        value: "",
      }),
    ),
  ];

  const paddedHorseSecondaryDetails = [
    ...horseSecondaryDetails,
    ...Array.from(
      {
        length: Math.max(0, horseRowsPerColumn - horseSecondaryDetails.length),
      },
      (_, index) => ({
        key: `secondary-empty-${index}`,
        label: "",
        value: "",
      }),
    ),
  ];

  const dir = (lang || "").toLowerCase().startsWith("ar") ? "rtl" : "ltr";
  const pageTitle =
    data?.title || horse?.name || (lang === "ar" ? "عرض خيل" : "Horse listing");
  const shareUrl =
    typeof window !== "undefined"
      ? window.location.href
      : `/${lang}/horses/${encodeURIComponent(String(data?.id ?? ""))}`;
  const auctionStatusLabel = (() => {
    if (!status) return undefined;
    if (isSold) return t("sold");
    try {
      return tAuctionCard(`auction_state.${status}` as any);
    } catch {
      return status;
    }
  })();

  const LISTING_STATUS_KEYS = new Set([
    "active",
    "available",
    "pending",
    "rejected",
    "draft",
  ]);
  const listingStatusChipLabel =
    !status || typeof status !== "string"
      ? ""
      : isSold
        ? t("sold")
        : LISTING_STATUS_KEYS.has(status)
          ? t(`listing_status.${status}` as "listing_status.active")
          : (auctionStatusLabel ?? status);

  const statusChipClass = isSold
    ? "bg-red-100 text-red-700 border border-red-200"
    : status === "available"
      ? "bg-green-100 text-green-700 border border-green-200"
      : "bg-gray-100 text-gray-700 border border-gray-200";

  const mainSections: DetailsSection[] = [
    {
      id: "media",
      content: (
        <MediaSection
          images={images}
          animalUsage={horse?.animal_usage}
          isGroup={Boolean(data?.is_group)}
          isCamelOffer={isCamelOffer}
          onOpenLightbox={openLightbox}
        />
      ),
    },
  ];

  const descriptionCreatedAt = formatOfferCreatedAt(data?.created_at, lang);

  const offerCountry = (data as any)?.country;
  const offerState = (data as any)?.state;
  const descriptionLocationLine = [offerCountry, offerState]
    .filter((x) => x != null && String(x).trim() !== "")
    .map((x) => String(x).trim())
    .join(" • ");

  const createdBy = (data as any)?.created_by;
  const sellerRes = (data as any)?.seller;
  const sellerDisplayName =
    createdBy?.stable_name ||
    createdBy?.name ||
    sellerRes?.stable_name ||
    sellerRes?.name ||
    "";
  const sellerPhoneRaw = createdBy?.phone ?? sellerRes?.phone ?? null;
  const sellerPhone =
    sellerPhoneRaw != null && String(sellerPhoneRaw).trim() !== ""
      ? String(sellerPhoneRaw).trim()
      : null;
  const sellerTelHref = sellerPhone
    ? `tel:${sellerPhone.replace(/[^\d+]/g, "")}`
    : null;

  const hasSellerLocationSection =
    Boolean(descriptionLocationLine) ||
    Boolean(sellerDisplayName) ||
    Boolean(sellerPhone);

  if (
    data?.description ||
    descriptionCreatedAt ||
    hasSellerLocationSection ||
    showOfferMap
  ) {
    const hasTopContent =
      Boolean(data?.description) || Boolean(descriptionCreatedAt);
    const hasContentBeforeMap =
      hasTopContent || hasSellerLocationSection;
    mainSections.push({
      id: "description",
      content: (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)]"
        >
          <h3 className="text-lg font-bold text-[#0F5132] mb-3">
            {t("description")}
          </h3>
          {data?.description ? (
            <p className="text-slate-700 leading-7">{data.description}</p>
          ) : null}
          {descriptionCreatedAt ? (
            <div
              className={
                data?.description
                  ? "mt-4 pt-4 border-t border-slate-100"
                  : "mt-0"
              }
            >
              <div className="text-sm text-slate-500 mb-1">
                {t("listing_created_at_label")}
              </div>
              <div className="font-semibold text-slate-800">
                {descriptionCreatedAt}
              </div>
            </div>
          ) : null}
          {hasSellerLocationSection ? (
            <div
              className={`grid md:grid-cols-2 gap-4 text-sm text-slate-700 ${
                hasTopContent
                  ? "mt-4 pt-4 border-t border-slate-100"
                  : "mt-0"
              }`}
            >
              <div className="p-3 rounded-lg bg-gray-50">
                <div className="text-slate-500 mb-1 flex items-center gap-1.5">
                  <MapPin className="w-4 h-4 text-[#0F5132] shrink-0" />
                  <span>{t("description_location_label")}</span>
                </div>
                <div className="font-bold">
                  {descriptionLocationLine || "—"}
                </div>
              </div>
              <div className="p-3 rounded-lg bg-gray-50">
                <div className="text-slate-500 mb-1 flex items-center gap-1.5">
                  <UserRound className="w-4 h-4 text-[#0F5132] shrink-0" />
                  <span>{t("description_seller_label")}</span>
                </div>
                <div className="font-bold">
                  {sellerDisplayName || "—"}
                </div>
                {sellerPhone && sellerTelHref ? (
                  <div className="mt-2 pt-2 border-t border-slate-200/80">
                    <div className="text-slate-500 mb-1 flex items-center gap-1.5 text-xs">
                      <Phone className="w-3.5 h-3.5 text-[#0F5132] shrink-0" />
                      <span>{t("seller_phone_label")}</span>
                    </div>
                    <a
                      href={sellerTelHref}
                      className="font-semibold text-[#0F5132] hover:underline break-all"
                      dir="ltr"
                    >
                      {sellerPhone}
                    </a>
                  </div>
                ) : null}
              </div>
            </div>
          ) : null}
          {showOfferMap ? (
            <div
              className={
                hasContentBeforeMap
                  ? "mt-4 pt-4 border-t border-slate-100"
                  : "mt-0"
              }
            >
              <div className="text-sm text-slate-500 mb-2 flex items-center gap-1.5">
                <MapPin className="w-4 h-4 text-[#0F5132] shrink-0" />
                <span>{t("map_label")}</span>
              </div>
              <LocationMapView
                lat={offerMapLat}
                lng={offerMapLng}
                height={220}
              />
            </div>
          ) : null}
        </motion.div>
      ),
    });
  }

  if (isCamelOffer && data?.camel) {
    mainSections.push({
      id: "camel-details",
      content: <CamelDetailsSection item={data} />,
    });
  }

  if (horseRowsPerColumn > 0) {
    mainSections.push({
      id: "horse-info",
      content: (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)]"
        >
          <h3 className="text-lg font-bold text-[#0F5132] mb-3">
            {t("horseInfo")}
          </h3>
          <div className="grid md:grid-cols-2 gap-4">
            <div className="w-full text-sm overflow-hidden bg-slate-50/30  divide-y">
              {paddedHorsePrimaryDetails.map((detail) => {
                const isEmpty = !detail.label && !detail.value;
                return (
                  <div
                    key={detail.key}
                    className="grid grid-cols-[minmax(120px,42%)_1fr] min-h-[52px]"
                    aria-hidden={isEmpty}
                  >
                    <div className="p-3 text-slate-500">
                      {detail.label || "\u00A0"}
                    </div>
                    <div className="p-3 font-bold text-slate-900">
                      {detail.value || "\u00A0"}
                    </div>
                  </div>
                );
              })}
            </div>

            <div className="w-full text-sm overflow-hidden bg-slate-50/30  divide-y">
              {paddedHorseSecondaryDetails.map((detail) => {
                const isEmpty = !detail.label && !detail.value;
                return (
                  <div
                    key={detail.key}
                    className="grid grid-cols-[minmax(120px,42%)_1fr] min-h-[52px]"
                    aria-hidden={isEmpty}
                  >
                    <div className="p-3 text-slate-500">
                      {detail.label || "\u00A0"}
                    </div>
                    <div className="p-3 font-bold text-slate-900">
                      {detail.value || "\u00A0"}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </motion.div>
      ),
    });
  }

  mainSections.push(
    {
      id: "documents",
      content: (
        <DocumentsSection
          data={data}
          onOpenDocumentPreview={openDocumentPreview}
        />
      ),
    },
    {
      id: "videos",
      content: (
        <VideosSection
          title={t("videos")}
          playLabel={t("play")}
          videos={videos}
          onOpenVideo={openVideo}
        />
      ),
    },
  );

  const sidebar: ReactNode = (
    <div className="space-y-6">
      <motion.div
        initial={{ opacity: 0, x: 20 }}
        animate={{ opacity: 1, x: 0 }}
        className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)]"
      >
        <div className="flex items-center justify-between mb-2">
          <h1 className="text-xl font-bold">{data?.title || t("noTitle")}</h1>
        </div>

        <div className="text-sm text-slate-600 bg-slate-50 rounded-xl border border-slate-200 px-3 py-2">
          {t("breed")}: <b>{horse?.breed || "—"}</b> • {t("age")}:{" "}
          <b>{getAgeFromBirthDate(horse?.date_of_birth) || "—"}</b> •{" "}
          <b>{formatBirthDate(horse?.date_of_birth) || "—"}</b>
        </div>

        <div className="mt-4 flex flex-wrap items-center gap-3">
          <button
            type="button"
            className="px-3 py-2 rounded-lg bg-slate-100 text-sm hover:bg-slate-200 transition shrink-0"
            onClick={() => setShareOpen(true)}
          >
            {tAuctionSidebar("share")}
          </button>
          {status ? (
            <span
              className={`inline-flex items-center px-3 py-1.5 rounded-lg text-xs font-bold shrink-0 ${statusChipClass}`}
            >
              {listingStatusChipLabel}
            </span>
          ) : null}
        </div>

        <div className="mt-4 grid-cols-2 gap-3 hidden sm:grid">
          <div className="p-3 rounded-xl bg-gradient-to-br from-slate-50 to-slate-100/50 border border-slate-100">
            <div className="text-slate-600 text-sm">{t("price")}</div>
            <div className="text-2xl font-extrabold text-[#0F5132] flex items-center gap-1">
              {formatPrice(data?.price || 0)}
              <Image src={SAR_ICON} width={20} height={20} alt="ريال" />
            </div>
          </div>
          <div className="p-3 rounded-xl bg-gradient-to-br from-slate-50 to-slate-100/50 border border-slate-100">
            <div className="text-slate-600 text-sm">{t("deposit")}</div>
            <div className="text-2xl font-extrabold text-[#0F5132] flex items-center gap-1">
              {formatPrice(data?.deposit || 0)}
              <Image src={SAR_ICON} width={20} height={20} alt="ريال" />
            </div>
          </div>
        </div>

        <div className="hidden sm:block">
          {isOwner ? (
            <div className="mt-4 p-3 rounded-xl bg-slate-50 border border-slate-200 text-sm text-slate-700">
              لا يمكنك شراء هذا العرض لأنك المالك الحالي له.
            </div>
          ) : isSold ? (
            <div className="mt-4 p-3 rounded-xl bg-red-50 border border-red-200">
              <div className="font-bold text-red-800 mb-1">{t("sold")}</div>
              <div className="text-sm text-red-900">
                {lang === "ar"
                  ? "تم بيع هذا العرض ولا يمكن شراؤه الآن."
                  : "This listing has been sold and is no longer available."}
              </div>
            </div>
          ) : fullPaid ? (
            <div className="mt-4 p-3 rounded-xl bg-emerald-50 border border-emerald-200">
              <div className="font-bold text-emerald-800 mb-1">
                تم دفع قيمة العرض كاملة.
              </div>
              <div className="text-sm text-emerald-900">
                سيتم التواصل معك لاستكمال إجراءات نقل الملكية.
              </div>
            </div>
          ) : !depositPaid ? (
            <DynamicButton
              onClick={() => {
                if (!session || !session.access_token) {
                  toast.warning(tToast("login_required_purchase"));
                  setLoginModal(true);
                  return;
                }
                setDepositModalOpen(true);
              }}
              className="mt-5 w-full px-4 py-3 rounded-xl bg-[#0F5132] text-white hover:bg-[#0F5132]/90"
            >
              {t("payDeposit")}
            </DynamicButton>
          ) : (
            <div className="mt-4 p-3 rounded-xl bg-emerald-50 border border-emerald-200">
              <div className="font-bold text-emerald-800 mb-1">
                {t("depositPaid")}
              </div>
              <div className="text-sm text-emerald-900">
                {t("remaining")}{" "}
                <span className="font-extrabold">{timeLeft}</span>
              </div>
            </div>
          )}
        </div>
      </motion.div>

      {!isCamelOffer && (
        <motion.div
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ delay: 0.05 }}
          className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)]"
        >
          <h3 className="text-lg font-bold text-[#0F5132] mb-2">
            {t("terms_of_sale.title")}
          </h3>
          <ul className="space-y-2 text-sm text-slate-700">
            <li className="p-3 rounded-xl border">
              {t("terms_of_sale.payment_method")}
            </li>
            <li className="p-3 rounded-xl border">
              {t("deposit_modal.platform_commission", {
                pct: effectiveCommissionPct,
              })}
            </li>
            <li className="p-3 rounded-xl border">
              {t("terms_of_sale.completion_deadline")}
            </li>
            <li className="p-3 rounded-xl border">
              {t("terms_of_sale.buyer_costs")}
            </li>
            <li className="p-3 rounded-xl border">
              {t("terms_of_sale.no_refund")}
            </li>
          </ul>
        </motion.div>
      )}

      {(() => {
        const offerId = (data as any)?.id;
        if (offerId == null || String(offerId).trim() === "") return null;
        const raw =
          (data as any)?.owner_review_summary ??
          (data as any)?.seller_review_summary;
        const summary = raw
          ? {
              avg: Number(raw.avg ?? 0),
              count: Number(raw.count ?? 0),
            }
          : null;
        return (
          <SellerReviewsSection
            offerableId={String(offerId)}
            offerableType="offers"
            sellerLabel={
              (data as any)?.seller?.name ?? (data as any)?.created_by?.name
            }
            summary={summary}
          />
        );
      })()}
    </div>
  );

  return (
    <>
      {/* Mobile Bottom Action Bar */}
      {!isOwner && !fullPaid && !isSold && (
        <MobileActionBar>
          <div className="flex items-center gap-2">
            <MobileActionBarPrice
              label={t("price")}
              price={formatPrice(data?.price || 0)}
            />
            <MobileActionBarPrice
              label={t("deposit")}
              price={formatPrice(data?.deposit || 0)}
            />
            <div className="flex-1" />
            {!depositPaid ? (
              <MobileActionBarButton
                onClick={() => {
                  if (!session || !session.access_token) {
                    toast.warning(tToast("login_required_purchase"));
                    setLoginModal(true);
                    return;
                  }
                  setDepositModalOpen(true);
                }}
              >
                {t("payDeposit")}
              </MobileActionBarButton>
            ) : (
              <div className="text-xs text-emerald-700 font-bold px-2">
                {t("depositPaid")}
              </div>
            )}
          </div>
        </MobileActionBar>
      )}

      <DetailsCustom
        dir={dir}
        title={pageTitle}
        itemNumberLabel={t("adNumber")}
        itemNumber={data?.unique_id}
        auctionTypeLabel={
          isCamelOffer
            ? tFilters("animal_type.camel")
            : tFilters("animal_type.horse")
        }
        auctionStateLabel={auctionStatusLabel}
        auctionStateClassName={status ? statusChipClass : undefined}
        location={location || undefined}
        mainSections={mainSections}
        sidebar={sidebar}
      />

      <BaseModal
        isOpen={depositModalOpen}
        onOpenChange={setDepositModalOpen}
        title={t("confirmDeposit")}
        contentClassName="w-[min(100vw,480px)] rounded-2xl text-primary"
      >
        <div className="space-y-4 text-sm">
          <p className="text-slate-700 leading-7">
            {t.rich("deposit_modal.description", {
              b: (chunks) => <span className="font-bold">{chunks}</span>,
            })}
          </p>

          <div className="flex items-start gap-2 bg-slate-50 border border-dashed border-slate-200 rounded-xl p-3">
            <input
              id="pay-full-checkbox"
              type="checkbox"
              checked={payFull}
              onChange={(e) => setPayFull(e.target.checked)}
              className="mt-1 w-4 h-4 accent-[#0F5132]"
            />
            <label
              htmlFor="pay-full-checkbox"
              className="cursor-pointer select-none"
            >
              {t.rich("deposit_modal.pay_full_checkbox", {
                b: (chunks) => <span className="font-bold">{chunks}</span>,
              })}
            </label>
          </div>

          <div className="border rounded-2xl bg-slate-50 p-3 space-y-2 text-xs text-slate-800">
            <div className="flex items-center justify-between">
              <span>{t("deposit_modal.required_now")}</span>
              <span className="font-bold">
                <Money value={requiredNow} />
              </span>
            </div>
            <div className="flex items-center justify-between">
              <span>
                {t("deposit_modal.platform_commission", {
                  pct: Number.isFinite(invoiceCommissionPct)
                    ? invoiceCommissionPct
                    : 0,
                })}
              </span>
              <span className="font-bold">
                <Money value={invoiceCommissionAmount} />
              </span>
            </div>
            <div className="flex items-center justify-between">
              <span>
                {t("deposit_modal.commission_tax", {
                  pct: Number.isFinite(invoiceTaxPct) ? invoiceTaxPct : 0,
                })}
              </span>
              <span className="font-bold">
                <Money value={invoiceTaxAmount} />
              </span>
            </div>
            <div className="border-t border-dashed border-slate-300 my-1" />
            <div className="flex items-center justify-between text-sm font-bold">
              <span>{t("deposit_modal.total_due")}</span>
              <span>
                <Money value={invoiceTotalAmount} />
              </span>
            </div>
            <div className="flex items-center justify-between text-sm font-bold">
              <span>{t("deposit_modal.paid_now")}</span>
              <span>
                <Money value={requiredNow} />
              </span>
            </div>
            <div className="flex items-center justify-between text-sm font-bold">
              <span>{t("deposit_modal.remaining")}</span>
              <span>
                <Money value={invoiceRemainingAmount} />
              </span>
            </div>
          </div>

          {payFull && (
            <div className="text-[11px] bg-amber-50 border border-amber-200 rounded-xl p-2 text-amber-800">
              {t("deposit_modal.pay_full_notice")}
            </div>
          )}

          <PaymentMethodSelector
            amount={requiredNow}
            paymentParams={buyOfferPaymentParams}
            onSuccess={handlePaymentSuccess}
            showSummary={false}
          />
        </div>
      </BaseModal>

      {/* مودال النجاح */}
      <BaseModal
        isOpen={successModalOpen}
        onOpenChange={setSuccessModalOpen}
        title={t("successPay")}
        contentClassName="w-[min(92vw,420px)] text-center"
      >
        <p className="text-slate-700 text-sm">
          {payFull
            ? t("success_modal.full_payment_text")
            : t("success_modal.deposit_payment_text")}
        </p>
        <div className="mt-4 flex items-center justify-center gap-3">
          <button
            className="px-4 py-2 rounded-lg text-sm border border-[#0f5132] text-[#0f5132] bg-white"
            onClick={() => {
              setSuccessModalOpen(false);
              setInvoiceModalOpen(true);
            }}
          >
            {t("success_modal.view_invoice")}
          </button>
          <button
            className="px-4 py-2 rounded-lg text-sm bg-[#0f5132] text-white"
            onClick={() => setSuccessModalOpen(false)}
          >
            {t("success_modal.close")}
          </button>
        </div>
      </BaseModal>

      {/* مودال الفاتورة */}
      <BaseModal
        isOpen={invoiceModalOpen}
        onOpenChange={setInvoiceModalOpen}
        title="فاتورة عملية الدفع"
        contentClassName="w-[min(100vw,520px)] text-primary"
      >
        <div className="space-y-4 text-sm bg-white" id="invoice-section">
          <div className="flex items-center justify-between">
            <div>
              <div className="flex items-center gap-2">
                <img src="/logo.png" alt="Mazadat" className="w-8 h-8" />
                <div className="font-extrabold text-base">Mazadat</div>
              </div>
              <div className="text-xs text-slate-500">فاتورة شراء عرض خيل</div>
            </div>
            <div className="text-right text-xs text-slate-600">
              <div>التاريخ: {new Date().toLocaleDateString()}</div>
              <div>الوقت: {new Date().toLocaleTimeString()}</div>
            </div>
          </div>

          <div className="border rounded-xl p-3 bg-slate-50 text-xs text-slate-700 space-y-1">
            <div className="flex justify-between">
              <span>رقم العرض</span>
              <span className="font-bold">{data?.unique_id || "-"}</span>
            </div>
            <div className="flex justify-between">
              <span>اسم العرض</span>
              <span className="font-bold truncate max-w-55">
                {data?.title || "عرض خيل"}
              </span>
            </div>
            <div className="flex justify-between">
              <span>نوع الدفع</span>
              <span className="font-bold">
                {payFull ? "دفع كامل" : "دفع عربون"}
              </span>
            </div>
            <div className="flex justify-between">
              <span>وسيلة الدفع</span>
              <span className="font-bold">-</span>
            </div>
          </div>

          <div className="border rounded-xl p-3 bg-white text-xs text-slate-800 space-y-2">
            <div className="flex justify-between">
              <span>سعر العرض الكلي</span>
              <span className="font-bold">
                <Money value={invoiceBaseAmount} />
              </span>
            </div>
            <div className="flex justify-between">
              <span>المبلغ المدفوع الآن</span>
              <span className="font-bold">
                <Money value={requiredNow} />
              </span>
            </div>
            <div className="flex justify-between">
              <span>المبلغ المتبقي</span>
              <span className="font-bold">
                <Money value={invoiceRemainingAmount} />
              </span>
            </div>
            <div className="flex justify-between">
              <span>
                عمولة عطايا (
                {Number.isFinite(invoiceCommissionPct)
                  ? invoiceCommissionPct
                  : 0}
                %)
              </span>
              <span className="font-bold">
                <Money value={invoiceCommissionAmount} />
              </span>
            </div>
            <div className="flex justify-between">
              <span>
                ضريبة العمولة (
                {Number.isFinite(invoiceTaxPct) ? invoiceTaxPct : 0}%)
              </span>
              <span className="font-bold">
                <Money value={invoiceTaxAmount} />
              </span>
            </div>
            <div className="border-t border-dashed my-1" />
            <div className="flex justify-between text-sm font-extrabold">
              <span>الإجمالي الكلي المستحق</span>
              <span>
                <Money value={invoiceTotalAmount} />
              </span>
            </div>
          </div>

          <div className="flex items-center justify-between text-[11px] text-slate-500">
            <span>
              هذه الفاتورة صالحة لاستكمال إجراءات الشراء داخل المنصة فقط.
            </span>
            <span>رقم مرجعي: {data?.id || "-"}</span>
          </div>

          <div className="flex justify-end gap-2 pt-2">
            <button
              className="px-3 py-2 rounded-lg text-xs border border-slate-300 text-slate-700 bg-white"
              onClick={() => setInvoiceModalOpen(false)}
            >
              إغلاق
            </button>
            {/*  <button
              className="px-3 py-2 rounded-lg text-xs bg-[#0f5132] text-white"
              onClick={handlePrintInvoice}
            >
              تحميل كـ PDF
            </button> */}
          </div>
        </div>
      </BaseModal>

      {/* مودال الرصيد غير كافٍ للمحفظة */}
      <TopUpModal
        isOpen={showTopUpModal}
        onOpenChange={(open) => {
          setShowTopUpModal(open);
          if (open) setDepositModalOpen(false);
        }}
        defaultAmount={topUpShortfall > 0 ? topUpShortfall : undefined}
        onSuccess={() => {
          setShowTopUpModal(false);
          setDepositModalOpen(false);
          setSuccessModalOpen(false);
          setInvoiceModalOpen(false);
          setTopUpNoticeOpen(true);
        }}
      />

      <BaseModal
        isOpen={topUpNoticeOpen}
        onOpenChange={setTopUpNoticeOpen}
        placement="center"
        title="تنبيه"
        contentClassName="w-[min(92vw,420px)] text-center"
      >
        <div className="space-y-4">
          <div className="text-sm text-slate-700 leading-relaxed">
            تم إرسال طلب شحن المحفظة بنجاح.
            <br />
            يرجى انتظار موافقة الأدمن على طلبك، ثم ارجع وأعد شراء العرض.
          </div>
          <button
            className="w-full px-4 py-2 rounded-lg text-sm bg-[#0f5132] text-white"
            onClick={() => setTopUpNoticeOpen(false)}
          >
            إغلاق
          </button>
        </div>
      </BaseModal>

      <BaseModal
        isOpen={videoModalOpen}
        onOpenChange={setVideoModalOpen}
        title={t("watchVideo")}
        contentClassName="w-[min(95vw,980px)] p-1"
      >
        <div className="aspect-video rounded-b-2xl overflow-hidden">
          {videoUrl.includes("youtube.com") || videoUrl.includes("youtu.be") ? (
            <iframe
              src={videoUrl}
              className="w-full h-full"
              allow="autoplay; encrypted-media"
              allowFullScreen
              title="YouTube video"
            />
          ) : (
            <video
              src={videoUrl}
              controls
              autoPlay
              className="w-full h-full"
              title="Direct video"
            />
          )}
        </div>
      </BaseModal>

      {/* مودال الصور */}
      <BaseModal
        isOpen={lightboxOpen}
        onOpenChange={setLightboxOpen}
        size="4xl"
        contentClassName="p-0 bg-transparent"
      >
        <div className="relative flex flex-col items-center bg-white rounded-2xl p-4">
          <img
            src={lightboxImg}
            alt="عرض الصورة"
            className="max-h-[70vh] rounded-xl object-contain"
          />
        </div>
      </BaseModal>

      <BaseModal
        isOpen={docPreviewOpen}
        onOpenChange={(open) => {
          setDocPreviewOpen(open);
          if (!open) setSelectedDocument(null);
        }}
        title={selectedDocument?.title || t("documents")}
        contentClassName="w-[min(95vw,980px)] max-h-[70%]"
      >
        <div className="space-y-3">
          {selectedDocument ? (
            <div className="flex items-center justify-end gap-2">
              <a
                href={selectedDocument.url}
                target="_blank"
                rel="noreferrer"
                className="px-3 py-2 rounded-lg text-xs border border-slate-300 text-slate-700 bg-white"
              >
                {t("open")}
              </a>
              <a
                href={selectedDocument.url}
                download
                className="px-3 py-2 rounded-lg text-xs border border-slate-300 text-slate-700 bg-white"
              >
                {t("download")}
              </a>
            </div>
          ) : null}

          <div className="border rounded-xl overflow-hidden bg-gray-50">
            {selectedDocument?.kind === "image" ? (
              <img
                src={selectedDocument.url}
                alt={selectedDocument.title}
                className="w-full h-auto max-h-[70vh] object-contain bg-white"
              />
            ) : selectedDocument?.kind === "pdf" ? (
              <div className="p-3 bg-white">
                <PdfViewer
                  fileUrl={selectedDocument.url}
                  fileName={`${selectedDocument.title}.pdf`}
                />
              </div>
            ) : (
              <div className="p-8 text-center text-gray-600">
                {t("preview_not_supported")}
              </div>
            )}
          </div>
        </div>
      </BaseModal>

      <ShareModal
        isOpen={shareOpen}
        onClose={() => setShareOpen(false)}
        title={String(data?.title ?? pageTitle)}
        url={shareUrl}
        description={String(data?.description ?? "")}
      />
    </>
  );
}
