"use client";

import { ReactNode, useMemo, useState, useTransition } from "react";
import { motion } from "framer-motion";
import ShareModal from "@/components/ShareModal";
import { Locale, useLocale, useTranslations } from "next-intl";
import { siteConfig } from "@/config/site.config";
import Money from "@/components/ui/Money";
import AuctionUnifiedTimer from "@/components/count/AuctionUnifiedTimer";
import MobileActionBar, {
  MobileActionBarButton,
  MobileActionBarPrice,
} from "@/components/ui/MobileActionBar";
import { Check, ChevronDown, Gavel, MapPin, Share2, Send } from "lucide-react";
import { useSession } from "@/auth/session-provider";
import { useAppToast } from "@/app/[lang]/providers";
import { useAvailablePaddlesForAuction } from "@/lib/clientQueries";
import YearlyPaddleModal from "@/components/paddles/YearlyPaddleModal";
import { getPrefetchedGroupAuctionTerms } from "@/lib/groupAuctionShowTerms";
import type { GroupAuction } from "@/actions/group-auctions";
import Image from "next/image";
import { useParams } from "next/navigation";
import { usePathname, useRouter } from "@/i18n/navigation";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

import DetailsCustom, {
  type DetailsSection,
} from "@/components/details-custom";

// Reuse same section components as the auction detail page
import MediaSection from "@/(pages)/autionClient/parts/Media";
import InfoSection from "@/(pages)/autionClient/parts/Info";
import CamelDetailsSection from "@/(pages)/autionClient/parts/CamelDetails";
import DocumentsSection from "@/(pages)/autionClient/parts/Documents";
import VideosSection from "@/(pages)/autionClient/parts/Video";
import { OfferModal } from "@/components/annaulMazad/live-rooms-table/LiveRoomsTableModals";
import {
  getVaccinationStatusForDisplay,
  vaccinationStatusValueLabel,
} from "@/lib/animalVaccinationStatus";

type MediaFile = { id?: number | null; url?: string | null } | null;

type SingleAuctionItem = {
  id?: string | number;
  unique_id?: string | null;
  group_order?: any;
  auction_type?: string | null;
  title?: string | null;
  description?: string | null;
  status?: string | null;
  auction_state?: string | null;
  auction_start_time?: string | null;
  auction_start_datetime?: string | null;
  auction_start_date?: string | null;
  auction_end_time?: string | null;
  auction_end_datetime?: string | null;
  auction_end_date?: string | null;
  state?: string | null;
  country?: string | null;
  starting_price?: string | number | null;
  market_entry_price?: string | number | null;
  media_files?: {
    main_image?: MediaFile;
    additional_images?: Array<{
      id?: number | null;
      url?: string | null;
    }> | null;
    medical_exam_certificate?: MediaFile | string | null;
    info_certificate?: MediaFile | string | null;
    owner_document?: MediaFile | string | null;
    video?: MediaFile | string | null;
  } | null;
  horse?: {
    id?: string;
    animal_color?: string | null;
    animal_usage?: string | null;
    name?: string | null;
    father_name?: string | null;
    mother_name?: string | null;
    mother_father_name?: string | null;
    gender?: string | null;
    date_of_birth?: string | null;
    breed?: string | null;
    height?: string | null;
    type?: string | null;
    /** @deprecated rollout */
    is_pregnant?: boolean | null;
    vaccination_status?: string | null;
  } | null;
  camel?: {
    id?: string;
    animal_color?: string | null;
    animal_age?: string | number | Record<string, unknown> | null;
    animal_age_id?: string | number | null;
    name?: string | null;
    father_name?: string | null;
    mother_name?: string | null;
    mother_father_name?: string | null;
    gender?: string | null;
    date_of_birth?: string | null;
    breed?: string | null;
    height?: string | null;
    type?: string | null;
    /** @deprecated rollout */
    is_pregnant?: boolean | null;
    vaccination_status?: string | null;
  } | null;
  owner?: {
    name?: string | null;
    phone?: string | null;
    city?: string | null;
  } | null;
};

function formatAgeFromDob(
  dob: string | null | undefined,
  t: (key: string, values?: any) => string,
): string {
  if (!dob) return "—";
  const d = new Date(dob);
  if (Number.isNaN(d.getTime())) return "—";

  const now = new Date();
  let months =
    (now.getFullYear() - d.getFullYear()) * 12 +
    (now.getMonth() - d.getMonth());
  if (now.getDate() < d.getDate()) months -= 1;
  if (months < 0) months = 0;

  const years = Math.floor(months / 12);
  const remMonths = months % 12;
  if (years === 0 && remMonths === 0) return t("age.less_than_month");
  if (years === 0) return t("age.months", { count: remMonths });
  if (remMonths === 0) return t("age.years", { count: years });
  return t("age.years_and_months", { years, months: remMonths });
}

function parseAuctionDateMs(raw: unknown): number | null {
  if (!raw) return null;
  if (raw instanceof Date) {
    const ms = raw.getTime();
    return Number.isFinite(ms) ? ms : null;
  }

  const value = String(raw).trim();
  if (!value) return null;

  if (/^\d+$/.test(value)) {
    const n = Number(value);
    if (!Number.isFinite(n)) return null;
    return value.length <= 10 ? n * 1000 : n;
  }

  const normalized = value.includes("T") ? value : value.replace(" ", "T");
  const ms = new Date(normalized).getTime();
  return Number.isFinite(ms) ? ms : null;
}

type AuctionGroupLike = {
  id?: string;
  starting_price?: string | number | null;
  market_entry_price?: string | number | null;
  winning_bid?: { amount?: string | number } | null;
  can_buy_paddle?: boolean | null;
  can_send_offer?: boolean | null;
  status?: string | null;
  group_auction_id?: string | null;
};

export default function AnnualItemDetailsClient({
  item,
  auctionGroup = null,
  groupAuction = null,
  groupAuctionId = null,
  auctionGroupId: auctionGroupIdProp = null,
}: {
  item: SingleAuctionItem;
  auctionGroup?: AuctionGroupLike | null;
  groupAuction?: {
    normal_paddle_price?: string | number;
    auction_terms?: string | null;
  } | null;
  groupAuctionId?: string | null;
  auctionGroupId?: string | null;
}) {
  type DetailRow = { key: string; label: string; value: ReactNode };
  const router = useRouter();
  const pathname = usePathname();
  const params = useParams();
  const [, startTransition] = useTransition();
  const locale = useLocale();
  const isRtl = (locale || "").toLowerCase().startsWith("ar");
  const t = useTranslations("ANNUAL_ITEM_DETAILS");
  const tHorseDetails = useTranslations("HORSES_DETAILS");
  const tVax = useTranslations("ANIMAL_VACCINATION_STATUS");
  const tStep4 = useTranslations("ADD_LISTING.STEP4");
  const tToast = useTranslations("TOAST");

  const [shareModalOpen, setShareModalOpen] = useState(false);
  const [paddleModalOpen, setPaddleModalOpen] = useState(false);
  const [paddleJustPurchased, setPaddleJustPurchased] = useState(false);
  const [offerModalOpen, setOfferModalOpen] = useState(false);
  const [offerAmount, setOfferAmount] = useState("");
  const [sendingOffer, setSendingOffer] = useState(false);
  const [offerSent, setOfferSent] = useState(false);

  const toast = useAppToast();
  const session = useSession();
  const isHorseWithAuctionGroup = !!item?.horse && !!auctionGroup;
  const effectiveGroupId =
    groupAuctionId || (auctionGroup as any)?.group_auction_id;
  const effectiveAuctionGroupId =
    auctionGroupIdProp || (auctionGroup as any)?.id;
  const canBuyPaddle =
    isHorseWithAuctionGroup &&
    !paddleJustPurchased &&
    !!(auctionGroup as any)?.can_buy_paddle;
  const canSendOffer =
    isHorseWithAuctionGroup &&
    (paddleJustPurchased || !!(auctionGroup as any)?.can_send_offer);
  const minOfferAmount =
    Number(
      (auctionGroup as any)?.winning_bid?.amount ??
        (auctionGroup as any)?.market_entry_price ??
        0,
    ) || 0;

  const { data: availablePaddles = [] } = useAvailablePaddlesForAuction(
    canBuyPaddle ? effectiveAuctionGroupId : undefined,
    "annual",
  );

  const auctionPrices = {
    normalPrice: Number((groupAuction as any)?.normal_paddle_price ?? 0) || 100,
    premiumPrice: 0,
    premiumUseTimes: 0,
  };

  const startingPrice = isHorseWithAuctionGroup
    ? ((auctionGroup as any)?.starting_price ?? item?.starting_price)
    : item?.starting_price;
  const marketEntryPrice = isHorseWithAuctionGroup
    ? ((auctionGroup as any)?.market_entry_price ?? item?.market_entry_price)
    : item?.market_entry_price;

  const handleSubmitOffer = async () => {
    const amount = Number(offerAmount);
    if (!Number.isFinite(amount) || amount <= 0) {
      toast.error(tToast("enter_valid_offer_amount"));
      return;
    }
    if (minOfferAmount > 0 && amount <= minOfferAmount) {
      toast.error(
        tToast("offer_must_exceed_min", {
          min: minOfferAmount.toLocaleString(),
        }),
      );
      return;
    }
    const apiBase =
      (typeof process !== "undefined" && process.env.NEXT_PUBLIC_BASE_URL) ||
      "https://dev-endpoint.ataya.sa/api";
    setSendingOffer(true);
    try {
      const headers: Record<string, string> = {
        "Content-Type": "application/json",
        Accept: "application/json",
        "Accept-Language": locale || "ar",
        ...(session?.access_token
          ? { Authorization: `Bearer ${session.access_token}` }
          : {}),
      };
      const res = await fetch(
        `${apiBase}/dashboard/user/auction-purchase-offers`,
        {
          method: "POST",
          headers,
          credentials: "omit",
          body: JSON.stringify({
            auction_type: "group",
            auction_id: effectiveAuctionGroupId,
            full_amount: amount,
          }),
        },
      );
      const json = await res.json().catch(() => ({}));
      if (res.ok && json?.success !== false) {
        toast.success(tToast("offer_sent_success"));
        setOfferSent(true);
        setOfferModalOpen(false);
        setOfferAmount("");
      } else {
        const msg = json?.message || tToast("offer_send_failed");
        toast.error(String(msg));
      }
    } catch {
      toast.error(tToast("generic_try_again"));
    } finally {
      setSendingOffer(false);
    }
  };

  const shareUrl =
    typeof window !== "undefined"
      ? window.location.href
      : `${siteConfig.url}/${locale}/annual-item/${item?.id}`;

  const animal = item?.horse || item?.camel || null;
  const animalLabel = item?.horse ? t("animal.horse") : t("animal.camel");
  const title = (animal?.name || item?.title || "—").toString();
  const displayId = (item?.group_order || item?.unique_id || "—").toString();
  const description = (item?.description || "—").toString();

  const metaAge = formatAgeFromDob(animal?.date_of_birth || null, t);
  const metaBreed = animal?.breed ? animal.breed : "—";
  const statusRaw = String(item?.status || "").toLowerCase();
  const auctionStateRaw = String(item?.auction_state || "").toLowerCase();
  const auctionTypeRaw = String(item?.auction_type || "").toLowerCase();
  const auctionLocation = [item?.country, item?.state]
    .filter(Boolean)
    .join(" - ");

  const auctionTypeLabel =
    auctionTypeRaw === "electronic"
      ? locale === "ar"
        ? "مزاد إلكتروني"
        : "Electronic Auction"
      : auctionTypeRaw === "live"
        ? locale === "ar"
          ? "مزاد مباشر"
          : "Live Auction"
        : auctionTypeRaw === "annual"
          ? locale === "ar"
            ? "مزاد سنوي"
            : "Annual Auction"
          : locale === "ar"
            ? "مزاد"
            : "Auction";

  const statusLabel =
    statusRaw === "approved"
      ? t("status.approved")
      : statusRaw === "rejected"
        ? t("status.rejected")
        : statusRaw === "sold"
          ? t("status.sold")
          : statusRaw === "unsold"
            ? t("status.unsold")
            : statusRaw === "pending"
              ? t("status.pending")
              : statusRaw === "withdrawn" || statusRaw === "pulled"
                ? t("status.withdrawn")
                : item?.status || "—";

  const statusClass =
    statusRaw === "approved"
      ? "bg-emerald-100 text-emerald-800 border border-emerald-200"
      : statusRaw === "rejected"
        ? "bg-red-100 text-red-800 border border-red-200"
        : statusRaw === "sold"
          ? "bg-emerald-500 text-white border-emerald-600"
          : statusRaw === "unsold"
            ? "bg-red-500 text-white border-red-600"
            : statusRaw === "pending"
              ? "bg-amber-500 text-white border-amber-600"
              : statusRaw === "withdrawn" || statusRaw === "pulled"
                ? "bg-sky-600 text-white border-sky-700"
                : "bg-slate-100 text-slate-700 border border-slate-200";

  const timerMeta = useMemo(() => {
    const now = Date.now();
    const startMs = parseAuctionDateMs(
      item?.auction_start_time ||
        item?.auction_start_datetime ||
        item?.auction_start_date,
    );
    const endMs = parseAuctionDateMs(
      item?.auction_end_time ||
        item?.auction_end_datetime ||
        item?.auction_end_date,
    );

    if (auctionStateRaw === "upcoming" && startMs && startMs > now) {
      return {
        target: startMs,
        label:
          locale === "ar" ? "العد التنازلي لبدء المزاد" : "Auction starts in",
      };
    }

    if (
      (auctionStateRaw === "live" || auctionStateRaw === "active") &&
      endMs &&
      endMs > now
    ) {
      return {
        target: endMs,
        label:
          locale === "ar" ? "العد التنازلي لانتهاء المزاد" : "Auction ends in",
      };
    }

    return { target: null as number | null, label: null as string | null };
  }, [
    auctionStateRaw,
    item?.auction_end_date,
    item?.auction_end_datetime,
    item?.auction_end_time,
    item?.auction_start_date,
    item?.auction_start_datetime,
    item?.auction_start_time,
    locale,
  ]);

  const getAnimalTypeLabel = (typeValue: unknown): string => {
    const type = String(typeValue || "").trim();
    if (!type) return "—";

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

  const languageOptions: Array<{
    value: Locale;
    label: string;
    short: string;
    flag: string;
    flagAlt: string;
  }> = [
    {
      value: "ar",
      label: "العربية",
      short: "AR",
      flag: "/sa-flag.svg",
      flagAlt: "Saudi Arabia",
    },
    {
      value: "en",
      label: "English",
      short: "EN",
      flag: "/uk-flag.svg",
      flagAlt: "United Kingdom",
    },
  ];

  const activeLanguage =
    languageOptions.find((option) => option.value === locale) ||
    languageOptions[1];

  const handleLanguageChange = (nextLocale: Locale) => {
    if (nextLocale === locale) return;
    startTransition(() => {
      // @ts-expect-error current route params always match the current pathname
      router.replace({ pathname, params }, { locale: nextLocale });
    });
  };

  const horsePrimaryDetails = useMemo<DetailRow[]>(() => {
    const rows: DetailRow[] = [];
    if (item?.horse?.name) {
      rows.push({
        key: "name",
        label: tHorseDetails("name"),
        value: item.horse.name,
      });
    }
    if (item?.horse?.breed) {
      rows.push({
        key: "breed",
        label: tHorseDetails("breed"),
        value: item.horse.breed,
      });
    }
    if (item?.horse?.gender) {
      rows.push({
        key: "gender",
        label: tHorseDetails("gender"),
        value:
          String(item.horse.gender) === "male"
            ? tHorseDetails("male")
            : String(item.horse.gender) === "female"
              ? tHorseDetails("female")
              : String(item.horse.gender),
      });
    }
    if (item?.horse?.date_of_birth) {
      rows.push({
        key: "date_of_birth",
        label: tHorseDetails("dateOfBirth"),
        value: String(item.horse.date_of_birth),
      });
    }
    if (item?.horse?.type) {
      rows.push({
        key: "type",
        label: tHorseDetails("type"),
        value: getAnimalTypeLabel(item.horse.type),
      });
    }
    return rows;
  }, [item?.horse, tHorseDetails]);

  const horseSecondaryDetails = useMemo<DetailRow[]>(() => {
    const rows: DetailRow[] = [];
    if (item?.horse?.height) {
      rows.push({
        key: "height",
        label: tHorseDetails("height"),
        value: `${item.horse.height} ${t("cm")}`,
      });
    }
    if (item?.horse?.animal_color) {
      rows.push({
        key: "animal_color",
        label: tHorseDetails("color"),
        value: item.horse.animal_color,
      });
    }
    if (item?.horse?.animal_usage) {
      rows.push({
        key: "animal_usage",
        label: tHorseDetails("usage"),
        value: item.horse.animal_usage,
      });
    }
    const vax = item?.horse
      ? getVaccinationStatusForDisplay(item.horse)
      : null;
    if (vax) {
      rows.push({
        key: "vaccination_status",
        label: tVax("label"),
        value: vaccinationStatusValueLabel(vax, tVax),
      });
    }
    return rows;
  }, [item?.horse, tHorseDetails, tVax]);

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

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

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

  const mainSections: DetailsSection[] = useMemo(() => {
    const sections: DetailsSection[] = [
      { id: "media", content: <MediaSection item={item as any} /> },
      { id: "info", content: <InfoSection item={item as any} /> },
    ];

    if (item?.camel) {
      sections.push({
        id: "camel-details",
        content: <CamelDetailsSection item={item as any} />,
      });
    }

    if (item?.horse) {
      sections.push({
        id: "horse-details",
        content: (
          <div className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)]">
            <div className="text-lg font-bold text-[#0F5132] mb-3">
              {tHorseDetails("horseInfo")}
            </div>
            <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,40%)_1fr] min-h-[52px]"
                      aria-hidden={isEmpty}
                    >
                      <div className="p-3 text-slate-500">
                        {detail.label || "\u00A0"}
                      </div>
                      <div className="p-3 font-bold">
                        {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,40%)_1fr] min-h-[52px]"
                      aria-hidden={isEmpty}
                    >
                      <div className="p-3 text-slate-500">
                        {detail.label || "\u00A0"}
                      </div>
                      <div className="p-3 font-bold">
                        {detail.value || "\u00A0"}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        ),
      });
    }

    sections.push(
      { id: "documents", content: <DocumentsSection item={item as any} /> },
      { id: "videos", content: <VideosSection item={item as any} /> },
    );

    return sections;
  }, [
    DocumentsSection,
    MediaSection,
    VideosSection,
    InfoSection,
    CamelDetailsSection,
    item,
    paddedHorsePrimaryDetails,
    paddedHorseSecondaryDetails,
    tHorseDetails,
  ]);

  const sidebar = (
    <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">
        <h2 className="text-lg font-extrabold text-[#0f5132]">
          {t("sidebar.title", { animal: animalLabel })}
        </h2>
      </div>

      <div className="text-sm text-slate-600 bg-slate-50 rounded-xl border border-slate-200 px-3 py-2">
        {t("breed_label")}: <b>{metaBreed}</b> • {t("age_label")}:{" "}
        <b>{metaAge}</b>
      </div>

      <div className="mt-3 flex flex-wrap gap-2">
        <span
          className={`px-3 py-1 rounded-lg text-xs font-bold ${statusClass}`}
        >
          {statusLabel}
        </span>
      </div>

      {!item?.camel && (startingPrice || marketEntryPrice) && (
        <div className="mt-4 space-y-2">
          {startingPrice && (
            <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-500 text-xs font-medium">
                {t("starting_price")}
              </div>
              <div className="text-2xl font-black text-[#0F5132] flex items-center gap-1 mt-1">
                <Money value={Number(startingPrice)} />
              </div>
            </div>
          )}
          {marketEntryPrice && (
            <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-500 text-xs font-medium">
                {t("market_entry_price")}
              </div>
              <div className="text-xl font-black text-[#0F5132] flex items-center gap-1 mt-1">
                <Money value={Number(marketEntryPrice)} />
              </div>
            </div>
          )}
        </div>
      )}

      {timerMeta.target && timerMeta.label ? (
        <div className="mt-4">
          <AuctionUnifiedTimer
            targetDate={timerMeta.target}
            label={timerMeta.label}
            variant="surface"
            className="!border-[#d9e6df] !bg-[#f8fcf9]"
          />
        </div>
      ) : null}

      {isHorseWithAuctionGroup &&
        (canBuyPaddle || canSendOffer || offerSent) && (
          <div className="mt-4 flex flex-col gap-2">
            {canBuyPaddle && (
              <button
                type="button"
                onClick={() => setPaddleModalOpen(true)}
                className="w-full px-4 py-2.5 rounded-xl text-sm font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors"
              >
                {isRtl ? "شراء مضرب" : "Buy Paddle"}
              </button>
            )}
            {!canBuyPaddle && canSendOffer && !offerSent && (
              <button
                type="button"
                onClick={() => {
                  if (!session?.access_token) {
                    toast.warning(tToast("login_required"));
                    return;
                  }
                  setOfferModalOpen(true);
                }}
                className="w-full px-4 py-2.5 rounded-xl text-sm font-bold bg-amber-500 text-white hover:bg-amber-600 transition-colors inline-flex items-center justify-center gap-2"
              >
                <Send size={16} />
                {isRtl ? "تقديم عرض" : "Send Offer"}
              </button>
            )}
            {offerSent && (
              <a
                href={`/${locale}/dashboard?tab=purchase-offers-buyer&auction_id=${effectiveAuctionGroupId}&animal_type=horse`}
                className="w-full px-4 py-2.5 rounded-xl text-sm font-bold bg-slate-700 text-white hover:bg-slate-800 transition-colors text-center"
              >
                {isRtl ? "عرض العروض السابقة" : "View Previous Offers"}
              </a>
            )}
          </div>
        )}

      <div className="mt-4 hidden sm:flex items-center gap-3">
        <button
          type="button"
          className="flex-1 px-4 py-3 rounded-xl bg-gradient-to-r from-[#0F5132] to-emerald-600 text-white hover:from-[#0F5132]/90 hover:to-emerald-600/90 font-bold text-sm shadow-lg shadow-emerald-500/20 transition-all"
          onClick={() => setShareModalOpen(true)}
        >
          {t("share_button")}
        </button>
      </div>
    </motion.div>
  );

  return (
    <>
      <DetailsCustom
        dir={isRtl ? "rtl" : "ltr"}
        title={title}
        itemNumberLabel={t("item_number")}
        itemNumber={displayId}
        auctionTypeLabel={auctionTypeLabel}
        auctionStateLabel={undefined}
        auctionStateClassName={undefined}
        location={
          auctionLocation ? (
            <span className="inline-flex items-center gap-2 text-sm text-white/90">
              <MapPin className="w-4 h-4" />
              <span>{auctionLocation}</span>
            </span>
          ) : undefined
        }
        headerExtra={
          item?.unique_id ? (
            <div className="inline-flex items-center gap-2 text-sm text-white/90">
              <Gavel className="w-4 h-4" />
              <span>
                {locale === "ar" ? "رقم المزاد" : "Auction ID"}:{" "}
                {item.unique_id}
              </span>
            </div>
          ) : undefined
        }
        mainSections={mainSections}
        sidebar={sidebar}
      />

      {/* Mobile Bottom Bar */}
      <MobileActionBar>
        <div className="flex items-center gap-3 w-full">
          {!item?.camel && startingPrice && (
            <MobileActionBarPrice
              label={t("starting_price")}
              price={Number(startingPrice).toLocaleString()}
              className="w-full"
            />
          )}
          <MobileActionBarButton
            onClick={() => setShareModalOpen(true)}
            variant="primary"
            fullWidth
          >
            <span className="flex items-center justify-center gap-2">
              <Share2 className="w-4 h-4" />
              {t("share_button")}
            </span>
          </MobileActionBarButton>
        </div>
        {timerMeta.target && timerMeta.label ? (
          <AuctionUnifiedTimer
            targetDate={timerMeta.target}
            label={timerMeta.label}
            variant="surface"
            compact
          />
        ) : null}
      </MobileActionBar>

      {/* Paddle Modal (horse + auction group) */}
      {effectiveGroupId && effectiveAuctionGroupId && (
        <YearlyPaddleModal
          open={paddleModalOpen}
          onClose={() => setPaddleModalOpen(false)}
          groupAuctionId={effectiveGroupId}
          yearlyAuctionId={effectiveAuctionGroupId}
          yearlyAuctionType="single"
          prices={auctionPrices}
          availablePaddles={availablePaddles}
          prefetchedAuctionTerms={getPrefetchedGroupAuctionTerms(
            groupAuction as GroupAuction | null,
          )}
          normalOnly
          onJoined={() => {
            setPaddleModalOpen(false);
            setPaddleJustPurchased(true);
          }}
        />
      )}

      <OfferModal
        isOpen={offerModalOpen}
        onOpenChange={(open) => {
          setOfferModalOpen(open);
          if (!open) setOfferAmount("");
        }}
        isRtl={isRtl}
        title={isRtl ? "تقديم عرض شراء" : "Submit Purchase Offer"}
        description={
          isRtl
            ? "أدخل قيمة عرض الشراء ليتم إرسالها للمراجعة والمقارنة مع الحد الأدنى المطلوب."
            : "Enter your purchase offer amount to submit it for review and compare it against the required minimum."
        }
        offerDeadlineLabel={null}
        offerAmountLabel={isRtl ? "مبلغ العرض" : "Offer Amount"}
        offerAmountPlaceholder={
          isRtl
            ? `أدخل مبلغًا أكبر من ${minOfferAmount.toLocaleString()}`
            : `Enter amount greater than ${minOfferAmount.toLocaleString()}`
        }
        offerAmount={offerAmount}
        onOfferAmountChange={setOfferAmount}
        minOfferPrice={minOfferAmount}
        cancelLabel={isRtl ? "إلغاء" : "Cancel"}
        confirmLabel={isRtl ? "إرسال العرض" : "Send Offer"}
        sendingOffer={sendingOffer}
        onCancel={() => {
          setOfferModalOpen(false);
          setOfferAmount("");
        }}
        onConfirm={handleSubmitOffer}
      />

      {/* Share Modal */}
      <ShareModal
        isOpen={shareModalOpen}
        onClose={() => setShareModalOpen(false)}
        title={title}
        url={shareUrl}
        description={description !== "—" ? description : undefined}
      />

      {/* Bottom padding for mobile action bar */}
      <div className="h-20 sm:hidden" />
    </>
  );
}
