"use client";

import DynamicButton from "@/components/button";
import { useEffect, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import {
  AuctionStatus,
  AuctionType as SocketAuctionType,
} from "@/lib/socket/types";
import { getMinIncrement } from "@/lib/auction/biddingRules";
import ShareModal from "@/components/ShareModal";
import { useToggleFavorite } from "@/lib/clientQueries";
import { useSession } from "@/auth/session-provider";
import { useSetAtom } from "jotai";
import { loginModalAtom } from "@/components/state/loginAtom";
import { useAppToast } from "@/app/[lang]/providers";
import { Heart } from "lucide-react";
import axios from "axios";
import AuctionUnifiedTimer from "@/components/count/AuctionUnifiedTimer";
import AuctionResultCard from "./AuctionResultCard";
import {
  getAuctionOfferDeadline,
  getAuctionWinnerName,
  resolveAuctionResultKind,
} from "./auctionResultUtils";
import type { AuctionItem } from "../types";
import { getAuctionStatusLabel } from "../AuctionClient";
import { badgeClass } from "./AuctionMeta";
import { formatPaddleDisplay } from "@/lib/utils";
import { API_BASE_URL } from "@/lib/axios";

const SAR_ICON = "/Riyal.svg";
const API_URL = API_BASE_URL;

export default function SidebarSection({
  item,
  onBidClick,
  postBidInfoOpen,
  hideBidButton,
  deadlineText,
  canBuyPaddle,
  paddlePrice,
  onBuyPaddleClick,
  buyingPaddle,
  isOwner,
  isDashboard,
  onOwnerWithdraw,
  onOwnerEnterMarket,
  showOwnerEnterMarket,
  liveBidders,
  currentBidOverride,
  auctionType,
  auctionStatus,
  highestBidder,
  endTimeMs,
  closeAtMs,
  reserveTriggered,
  closeReason,
  canSendOffer,
  onSendOfferClick,
  hidePricePanel,
  hidePaddlePurchaseCard,
  /** When set (e.g. group room id), "previous offers" dashboard link uses this instead of `item.id`. */
  purchaseOffersAuctionId,
  /** Annual single + group room: show next to «تقديم عرض» when user has a paddle. */
  paddleNumberBesideOffer,
}: {
  item: AuctionItem;
  onBidClick: () => void;
  postBidInfoOpen?: boolean;
  hideBidButton?: boolean;
  /** Hides the starting/final price highlight box (e.g. annual single item page). */
  hidePricePanel?: boolean;
  /** Hides the standalone paddle fee card (annual single uses modal + group strip instead). */
  hidePaddlePurchaseCard?: boolean;
  deadlineText?: string;
  canBuyPaddle?: boolean;
  paddlePrice?: string | number;
  onBuyPaddleClick?: () => void;
  buyingPaddle?: boolean;
  isOwner?: boolean;
  isDashboard?: boolean;
  onOwnerWithdraw?: () => void;
  onOwnerEnterMarket?: () => void;
  showOwnerEnterMarket?: boolean;
  liveBidders?: { name: string; paddle: string | number; amount: number }[];
  currentBidOverride?: number;
  auctionType?: SocketAuctionType;
  auctionStatus?: AuctionStatus;
  highestBidder?: {
    id: string;
    name: string;
    paddleNumber?: string | number | null;
  } | null;
  endTimeMs?: number | null;
  closeAtMs?: number | null;
  reserveTriggered?: boolean;
  closeReason?: string | null;
  canSendOffer?: boolean;
  onSendOfferClick?: () => void;
  purchaseOffersAuctionId?: string | null;
  paddleNumberBesideOffer?: string | null;
}) {
  const t = useTranslations("SINGLE_AUCTION.SIDEBAR");
  const tAuction = useTranslations("AUCTION");
  const session = useSession();
  const setLoginModal = useSetAtom(loginModalAtom);
  const toast = useAppToast();
  const toggleFavoriteMutation = useToggleFavorite();

  const [shareOpen, setShareOpen] = useState(false);
  const shareUrl =
    typeof window !== "undefined"
      ? window.location.href
      : `/auctions/${encodeURIComponent(String(item?.id ?? ""))}`;

  const fmt = (n: number) => {
    if (isNaN(n)) return "—";
    return n.toLocaleString("en-EG");
  };

  const commissionPctRawFromItem =
    item?.fees_setting?.buyer_commission_percentage ??
    item?.buyer_commission_percentage ??
    item?.buyer_commission ??
    item?.commission_percentage ??
    item?.commissionPercentage ??
    null;

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

  useEffect(() => {
    if (commissionPctRawFromItem != null) return;

    const animalType: "horse" | "camel" | null = item?.horse
      ? "horse"
      : item?.camel
        ? "camel"
        : item?.animal_type === "horse"
          ? "horse"
          : item?.animal_type === "camel"
            ? "camel"
            : null;

    if (!animalType) return;
    if (!API_URL) return;

    let cancelled = false;

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

    return () => {
      cancelled = true;
    };
  }, [commissionPctRawFromItem, item]);

  const commissionPctNum = Number(
    commissionPctRawFromItem ?? commissionPctFromConfig ?? 5,
  );
  const commissionPct = Number.isFinite(commissionPctNum)
    ? commissionPctNum
    : 5;

  const effectiveStatus: AuctionStatus =
    auctionStatus || (item?.auction_state as AuctionStatus) || "upcoming";

  const owner = item?.created_by?.stable_name || item?.created_by?.name || "";
  const shouldHideOwnerInfo = !owner;

  const isGroupAuction = Boolean(item?.is_group);
  const ownerCountry = item?.created_by?.country as string | undefined;
  const ownerState = item?.created_by?.state as string | undefined;
  const shouldShowOwnerLocation =
    !isGroupAuction &&
    !shouldHideOwnerInfo &&
    Boolean(ownerCountry || ownerState);

  const openingPrice = Number(item?.starting_price || 0);
  const marketEntryPrice = Number(item?.market_entry_price || 0);

  // Auction dates - API uses auction_start_time / auction_end_time
  const auctionStartDate =
    item?.auction_start_time ||
    item?.auction_start_datetime ||
    item?.auction_start_date ||
    item?.start_date ||
    item?.started_at ||
    null;
  const auctionEndDate =
    item?.auction_end_time ||
    item?.auction_end_datetime ||
    item?.auction_end_date ||
    item?.end_date ||
    item?.ended_at ||
    null;

  const locale = useLocale();
  const isArUi = locale === "ar";

  // Helper: parse various date string formats into timestamp (ms)
  const parseDateToMs = (dateStr: string | null): number | null => {
    if (!dateStr) return null;
    try {
      let normalized = String(dateStr).trim();
      const m = normalized.match(
        /^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})(?::(\d{2}))?$/,
      );
      if (m) {
        normalized = `${m[1]}T${m[2]}:${m[3] ?? "00"}`;
      }
      const d = new Date(normalized);
      const ms = d.getTime();
      if (isNaN(ms)) return null;
      return ms;
    } catch {
      return null;
    }
  };

  const startMs = parseDateToMs(auctionStartDate);
  const endMs = parseDateToMs(auctionEndDate);

  // نوع المزاد لتطبيق منطق 24 ساعة للمزادات المباشرة عند غياب وقت النهاية
  const rawAuctionType = String(
    auctionType || item?.auction_type || "",
  ).toLowerCase();
  const isLiveAuction = rawAuctionType.includes("live");

  const timerMeta = (() => {
    const now = Date.now();

    if (
      effectiveStatus === "ended" ||
      effectiveStatus === "withdrawn" ||
      effectiveStatus === "closed"
    ) {
      return { target: null as number | null, label: null as string | null };
    }

    if (reserveTriggered && closeAtMs && closeAtMs > now) {
      return {
        target: closeAtMs,
        label: tAuction("live_timer_label"),
      };
    }

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

    const effectiveEndMs =
      endTimeMs ??
      endMs ??
      (isLiveAuction && startMs ? startMs + 24 * 60 * 60 * 1000 : null);

    if (
      effectiveStatus === "active" &&
      effectiveEndMs &&
      effectiveEndMs > now
    ) {
      return {
        target: effectiveEndMs,
        label: isLiveAuction
          ? tAuction("live_timer_label")
          : tAuction("electronic_timer_label"),
      };
    }

    if (endMs && endMs > now) {
      return {
        target: endMs,
        label: tAuction("electronic_timer_label"),
      };
    }

    return { target: null as number | null, label: null as string | null };
  })();

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return "—";
    try {
      // Normalize "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" to ISO format
      let normalized = String(dateStr).trim();
      const m = normalized.match(
        /^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})(?::(\d{2}))?$/,
      );
      if (m) {
        normalized = `${m[1]}T${m[2]}:${m[3] ?? "00"}`;
      }
      const d = new Date(normalized);
      if (isNaN(d.getTime())) return dateStr;
      return d.toLocaleDateString(isArUi ? "ar-SA-u-nu-latn" : "en-SA", {
        year: "numeric",
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch {
      return dateStr;
    }
  };

  const formatDateParts = (dateStr: string | null) => {
    if (!dateStr) return { date: "—", time: "" };
    try {
      let normalized = String(dateStr).trim();
      const m = normalized.match(
        /^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})(?::(\d{2}))?$/,
      );
      if (m) {
        normalized = `${m[1]}T${m[2]}:${m[3] ?? "00"}`;
      }
      const d = new Date(normalized);
      if (isNaN(d.getTime())) return { date: String(dateStr), time: "" };

      const localeTag = isArUi ? "ar-SA-u-nu-latn" : "en-SA";
      const date = new Intl.DateTimeFormat(localeTag, {
        year: "numeric",
        month: "short",
        day: "numeric",
      }).format(d);
      const time = new Intl.DateTimeFormat(localeTag, {
        hour: "2-digit",
        minute: "2-digit",
      }).format(d);
      return { date, time };
    } catch {
      return { date: String(dateStr), time: "" };
    }
  };
  const rawBid =
    typeof currentBidOverride === "number"
      ? currentBidOverride
      : Number(
          item?.current_bid ?? item?.current_price ?? item?.highest_bid ?? 0,
        );
  // If no bids yet (rawBid is 0), show starting_price (openingPrice) instead
  const currentBid = rawBid > 0 ? rawBid : openingPrice;
  const minIncrement = getMinIncrement(currentBid, marketEntryPrice);
  const submittedOfferAmount = (() => {
    const info = (item as any)?.info_final_bid as
      | { final_bid_amount?: unknown; lowest_offer_value?: unknown }
      | undefined;
    const finalBid = Number(
      info?.final_bid_amount ?? item?.final_bid_amount ?? 0,
    );
    const lowestOffer = Number(info?.lowest_offer_value ?? 0);
    const paddlePrice = Number((item as any)?.paddle_price ?? 0);

    // Prefer non-zero final bid, then lowest offer, then paddle price.
    if (Number.isFinite(finalBid) && finalBid > 0) return finalBid;
    if (Number.isFinite(lowestOffer) && lowestOffer > 0) return lowestOffer;
    if (Number.isFinite(paddlePrice) && paddlePrice > 0) return paddlePrice;
    return 0;
  })();

  const displayPaddleNumber = formatPaddleDisplay(item?.paddle_number);
  const resolvedWinnerName =
    highestBidder?.name || getAuctionWinnerName(item, highestBidder);
  const resolvedWinnerPaddle =
    highestBidder?.paddleNumber ??
    item?.winner_paddle_number ??
    item?.highest_bidder_paddle_number ??
    null;

  const liveLeadingPaddleRaw = liveBidders?.[0]?.paddle;
  const liveLeadingPaddle =
    liveLeadingPaddleRaw != null &&
    liveLeadingPaddleRaw !== "" &&
    liveLeadingPaddleRaw !== 0
      ? liveLeadingPaddleRaw
      : null;
  const highestPaddleRaw = highestBidder?.paddleNumber;
  const highestPaddleOk =
    highestPaddleRaw != null &&
    String(highestPaddleRaw).trim() !== "" &&
    highestPaddleRaw !== 0;
  /** Socket `bid:created` keeps highestBidder in sync; list head is fallback if paddle missing on party. */
  const participatingPaddleDisplay = highestPaddleOk
    ? highestPaddleRaw
    : liveLeadingPaddle;

  const groupRoomFinalBidRaw = (
    item as { info_final_bid?: { final_bid_amount?: unknown } }
  )?.info_final_bid?.final_bid_amount;
  const groupRoomFinalBidNum = Number(groupRoomFinalBidRaw);
  const useGroupRoomFinalBid =
    Boolean(purchaseOffersAuctionId) &&
    effectiveStatus !== "upcoming" &&
    effectiveStatus !== "active" &&
    groupRoomFinalBidRaw != null &&
    String(groupRoomFinalBidRaw).trim() !== "" &&
    Number.isFinite(groupRoomFinalBidNum);

  const resultItem: AuctionItem = {
    ...item,
    auction_state: effectiveStatus,
    status:
      resolvedWinnerName &&
      effectiveStatus !== "active" &&
      effectiveStatus !== "upcoming"
        ? "sold"
        : item?.status,
    winner_name: resolvedWinnerName ?? item?.winner_name,
    highest_bidder_name: resolvedWinnerName ?? item?.highest_bidder_name,
    winner_paddle_number: resolvedWinnerPaddle ?? item?.winner_paddle_number,
    highest_bidder_paddle_number:
      resolvedWinnerPaddle ?? item?.highest_bidder_paddle_number,
    final_bid_amount:
      useGroupRoomFinalBid
        ? groupRoomFinalBidNum
        : effectiveStatus !== "upcoming" && currentBid > 0
          ? currentBid
          : item?.final_bid_amount,
    final_price:
      effectiveStatus !== "upcoming" && currentBid > 0
        ? currentBid
        : item?.final_price,
  };
  const resultBuyerName = getAuctionWinnerName(resultItem, highestBidder);
  const resultKind = resolveAuctionResultKind({
    item: resultItem,
    auctionStatus: effectiveStatus,
    closeReason,
    buyerName: resultBuyerName,
  });
  const shouldShowAuctionResult =
    effectiveStatus !== "active" && effectiveStatus !== "upcoming";
  /** Annual / group-room sidebar passes `purchaseOffersAuctionId`; show نتيجة المزاد instead of blocking on `is_group`. */
  const allowAuctionResultCard =
    !isGroupAuction || Boolean(purchaseOffersAuctionId);

  const showResultCard =
    allowAuctionResultCard &&
    shouldShowAuctionResult &&
    (resultKind !== null ||
      Boolean(resultItem?.can_send_offer) ||
      Boolean(resultItem?.can_buy_paddle) ||
      Boolean(canSendOffer) ||
      Boolean(canBuyPaddle));

  const hideLiveBiddersForSoldResult =
    showResultCard && resultKind === "sold";
  const offerDeadline = getAuctionOfferDeadline(item);
  const previousOffersHref = `/${locale}/dashboard?tab=purchase-offers-buyer&auction_id=${encodeURIComponent(
    String(purchaseOffersAuctionId ?? item?.id ?? ""),
  )}&animal_type=${encodeURIComponent(String(item?.animal_type ?? ""))}`;
  const showPreviousOffersLink =
    resultKind === "unsold" &&
    !canSendOffer &&
    !isOwner &&
    !canBuyPaddle &&
    Boolean(session);
  const offerSubmissionBlocked = Boolean(
    effectiveStatus === "active" || effectiveStatus === "upcoming",
  );
  const paddlePriceNumber = Number(paddlePrice ?? (item as any)?.paddle_price ?? 0);
  const buyPaddleCtaLabel =
    Number.isFinite(paddlePriceNumber) && paddlePriceNumber > 0
      ? t("buy_paddle_with_price", {
          value: fmt(paddlePriceNumber),
          currency: t("currency_label"),
        })
      : t("buy_paddle");
  const primaryActionLabel = canBuyPaddle
    ? t("bid_now")
    : effectiveStatus === "active"
      ? t("bid_now")
      : isArUi
        ? "تقديم عرض"
        : "Send offer";
  const showPaddlePurchaseCard =
    !hidePaddlePurchaseCard &&
    !displayPaddleNumber &&
    Boolean(canBuyPaddle && onBuyPaddleClick && !isOwner);
  const utilityCardHasTopSpacing = Boolean(
    (isDashboard && isOwner) || postBidInfoOpen,
  );

  const [isFavorite, setIsFavorite] = useState<boolean>(() => {
    const v = item?.is_favorite ?? item?.isFavorite;
    return Boolean(v);
  });
  const [favAnimating, setFavAnimating] = useState(false);

  const toggleFavorite = async () => {
    const token = session?.access_token;
    if (!token) {
      toast.warning(tAuction("not_active"));
      setLoginModal(true);
      return;
    }

    const next = !isFavorite;
    setIsFavorite(next);
    setFavAnimating(true);
    setTimeout(() => setFavAnimating(false), 400);

    if (next) {
      toast.success(tAuction("favorite_added"));
    } else {
      toast.info(tAuction("favorite_removed"));
    }

    try {
      await toggleFavoriteMutation.mutateAsync({
        id: String(item?.id ?? ""),
        type: "auction",
      });
    } catch {
      setIsFavorite(!next);
    }
  };

  const utilityCard = (
    <>
      {isDashboard && isOwner && (
        <div className="p-3 rounded-md bg-slate-50 border border-slate-200">
          <div className="text-slate-600 text-sm mb-2">
            {t("owner_actions_title")}
          </div>
          <div className="flex flex-wrap gap-2">
            {!!showOwnerEnterMarket && (
              <button
                type="button"
                onClick={onOwnerEnterMarket}
                className="px-3 py-2 rounded-md border bg-white text-sm"
              >
                {t("owner_actions.enter_market")}
              </button>
            )}
            {item?.auction_state !== "unsold" &&
              item.status !== "withdrawn" && (
                <button
                  type="button"
                  onClick={onOwnerWithdraw}
                  className="px-3 py-2 rounded-md border bg-white text-sm"
                >
                  {t("owner_actions.withdraw")}
                </button>
              )}
          </div>
        </div>
      )}

      {postBidInfoOpen && (
        <div
          className={`${isDashboard && isOwner ? "mt-4" : ""} p-3 rounded-md bg-emerald-50 border border-emerald-200`}
        >
          <div className="font-bold text-emerald-800 mb-1">
            {t("bid_recorded_title")}
          </div>
          <div className="text-sm text-emerald-900">
            {t.rich("bid_recorded_text", {
              time: () => (
                <span className="font-extrabold">{deadlineText}</span>
              ),
            })}
          </div>
        </div>
      )}

      <div
        className={`flex items-center gap-3 ${
          utilityCardHasTopSpacing ? "mt-4" : ""
        }`}
      >
        <button
          type="button"
          className="px-3 py-2 rounded-lg bg-slate-100 text-sm hover:bg-slate-200 transition"
          onClick={() => setShareOpen(true)}
        >
          {t("share")}
        </button>
        <button
          type="button"
          className={`group flex items-center gap-2 px-4 py-2.5 rounded-md text-sm font-medium cursor-pointer transition-all duration-300 ${
            isFavorite
              ? "bg-red-50 text-red-600 border border-red-200 hover:bg-red-100 shadow-sm shadow-red-100"
              : "bg-slate-100 text-slate-700 border border-slate-200 hover:bg-slate-200 hover:border-slate-300"
          } ${favAnimating ? "scale-110" : "scale-100"}`}
          onClick={toggleFavorite}
          style={{ transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)" }}
        >
          <Heart
            className={`w-4 h-4 transition-all duration-300 ${
              isFavorite
                ? "fill-red-500 text-red-500"
                : "text-slate-400 group-hover:text-red-400"
            } ${favAnimating ? "animate-ping-once" : ""}`}
            style={{
              animation: favAnimating ? "heartBeat 0.4s ease-in-out" : "none",
            }}
          />
          <span>{t("favorite")}</span>
        </button>
      </div>
    </>
  );

  return (
    <aside className="space-y-6 lg:sticky lg:top-6">
      {showResultCard ? (
        <AuctionResultCard
          item={resultItem}
          auctionStatus={effectiveStatus}
          currentPrice={currentBid}
          highestBidder={highestBidder}
          closeReason={closeReason}
          canBuyPaddle={canBuyPaddle}
          paddlePrice={paddlePrice}
          buyingPaddle={buyingPaddle}
          onBuyPaddleClick={onBuyPaddleClick}
          canSendOffer={canSendOffer}
          onSendOfferClick={onSendOfferClick}
          isLoggedIn={Boolean(session)}
          onLoginClick={() => setLoginModal(true)}
          offerDeadline={offerDeadline}
          showPreviousOffersLink={showPreviousOffersLink}
          previousOffersHref={previousOffersHref}
          paddleNumberBesideOffer={paddleNumberBesideOffer}
        />
      ) : (
        <div className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)]">
          {/* Current price only (represents starting/current price) - visible on all devices */}
          <div>
            <div className="flex items-center justify-between border-b  mb-3 border-slate-200 pb-3">
              <h3 className="text-base font-bold">
                {isArUi ? "حالة المزاد" : "Auction status"}
              </h3>
              <span
                className={`px-3 text-sm py-1 rounded-full font-semibold ${badgeClass(
                  item?.auction_state ?? "",
                )}`}
              >
                {getAuctionStatusLabel(item?.auction_state ?? "", locale)}
              </span>
            </div>
            {/* Bid/Buy Paddle Actions -
              - Warning for owner (isOwner) visible on all sizes
              - Actual bid/buy buttons hidden on mobile (md and up only) */}
            {!hideBidButton && (
              <div className="space-y-3">
                {isOwner ? null : (
                  <div className=" w-full md:block space-y-3">
                    {canBuyPaddle ? (
                      <DynamicButton
                        onClick={onBuyPaddleClick}
                        fullWidth
                        isDisabled={buyingPaddle}
                        className="w-full px-4 py-3 rounded-md bg-gradient-to-r from-[#0F5132] to-emerald-600 text-white font-bold hover:from-[#0F5132]/90 hover:to-emerald-600/90 disabled:opacity-60m  disabled:cursor-not-allowed shadow-lg shadow-emerald-500/20 transition-all"
                      >
                        {primaryActionLabel}
                      </DynamicButton>
                    ) : effectiveStatus === "active" ||
                      !offerSubmissionBlocked ? (
                      <DynamicButton
                        fullWidth
                        onClick={onBidClick}
                        className="w-full px-4 py-4 rounded-md bg-gradient-to-r from-[#0F5132] to-emerald-600 text-white font-bold text-base hover:from-[#0F5132]/90 hover:to-emerald-600/90 shadow-lg shadow-emerald-500/20 transition-all"
                      >
                        {primaryActionLabel}
                      </DynamicButton>
                    ) : null}
                  </div>
                )}
              </div>
            )}
            {/* Auction Dates */}
            {(item.auction_start_time || item.auction_end_time) &&
            String(item.auction_state) !== "ended" &&
            String(item.auction_state) !== "active" ? (
              <div className="mb-3 rounded-2xl border border-slate-200 bg-white/70 p-3">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                  {item.auction_start_time && (
                    <div className="rounded-2xl border border-slate-200 bg-slate-50/70 px-3 py-2.5">
                      <div className="inline-flex rounded-full bg-white px-2.5 py-1 text-[11px] font-extrabold text-slate-600 border border-slate-200">
                        {t("start_date")}
                      </div>
                      <div className="mt-1.5 text-sm font-black text-slate-900">
                        {formatDateParts(item.auction_start_time).date}
                      </div>
                      {formatDateParts(item.auction_start_time).time ? (
                        <div className="mt-0.5 text-xs font-bold text-slate-500">
                          {formatDateParts(item.auction_start_time).time}
                        </div>
                      ) : null}
                    </div>
                  )}
                  {item.auction_end_time && (
                    <div className="rounded-2xl border border-slate-200 bg-slate-50/70 px-3 py-2.5">
                      <div className="inline-flex rounded-full bg-white px-2.5 py-1 text-[11px] font-extrabold text-slate-600 border border-slate-200">
                        {t("end_date")}
                      </div>
                      <div className="mt-1.5 text-sm font-black text-slate-900">
                        {formatDateParts(item.auction_end_time).date}
                      </div>
                      {formatDateParts(item.auction_end_time).time ? (
                        <div className="mt-0.5 text-xs font-bold text-slate-500">
                          {formatDateParts(item.auction_end_time).time}
                        </div>
                      ) : null}
                    </div>
                  )}
                </div>
              </div>
            ) : null}
            {!hidePricePanel ? (
              <div className="p-3 rounded-md bg-gradient-to-br from-slate-50 to-slate-100/50 border border-slate-100 mb-3">
                {effectiveStatus === "upcoming" ? (
                  <div className="text-sm font-bold text-slate-500">
                    {t("starting_price")}
                  </div>
                ) : (
                  <div className="text-sm font-bold text-slate-500">
                    {t("final_bid_amount")}
                  </div>
                )}
                <div className="mt-3 flex items-end justify-center gap-2 text-[#0F5132]">
                  <span className="text-3xl text-primary sm:text-4xl font-black tracking-tight">
                    {fmt(currentBid)}
                  </span>
                  <img
                    src={SAR_ICON}
                    className="w-5 h-5 mb-3"
                    alt={isArUi ? "ريال" : "SAR"}
                  />
                </div>
              </div>
            ) : null}

            {participatingPaddleDisplay != null ? (
              <div className="mb-3 rounded-md bg-gradient-to-br from-slate-50 to-slate-100/50 border border-slate-100 p-3">
                <div className="text-sm font-bold text-slate-500">
                  {isArUi ? "رقم المضرب المشارك" : "Participating paddle number"}
                </div>
                <div className="mt-2 flex items-end justify-center gap-2 text-[#0F5132]">
                  <span className="text-3xl text-primary sm:text-4xl font-black tracking-tight">
                    {String(participatingPaddleDisplay)}
                  </span>
                  <span className="text-sm font-extrabold text-slate-500">
                    {isArUi ? "مضرب" : "Paddle"}
                  </span>
                </div>
              </div>
            ) : null}

            {isOwner && (
              <>
                <div className="mb-2 p-2.5 rounded-md bg-emerald-50 border border-emerald-100 text-xs font-medium text-emerald-800">
                  {isArUi
                    ? "أنت صاحب هذا المزاد"
                    : "You are the owner of this auction"}
                </div>
              </>
            )}

            {timerMeta.target && timerMeta.label ? (
              <div className="mb-3 rounded-md border border-slate-100 bg-slate-50/70 p-2.5">
                <AuctionUnifiedTimer
                  targetDate={timerMeta.target}
                  label={timerMeta.label}
                  variant="surface"
                />
              </div>
            ) : auctionStatus === "ended" ? (
              <div className="mb-3 rounded-md border border-slate-100 bg-slate-50/70 p-2.5">
                <div className="text-center text-sm font-bold text-slate-700">
                  {isArUi ? "انتهى المزاد" : "Auction ended"}
                </div>
              </div>
            ) : null}
          </div>
          <div className="mt-3">{utilityCard}</div>
        </div>
      )}

      {showResultCard ? (
        <div className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)]">
          {utilityCard}
        </div>
      ) : null}

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

      {displayPaddleNumber ? (
        <div className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_10px_24px_rgba(15,81,50,0.07)]">
          <h3 className="font-bold text-[#0F5132] mb-2">
            {isArUi ? "رقم مضربك" : "Your paddle number"}
          </h3>
          <div className="mt-3 flex items-end justify-center gap-2 text-[#0F5132]">
            <span className="text-3xl text-primary sm:text-4xl font-black tracking-tight">
              {displayPaddleNumber}
            </span>
          </div>
        </div>
      ) : showPaddlePurchaseCard ? (
        <div className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_10px_24px_rgba(15,81,50,0.07)]">
          <h3 className="font-bold text-[#0F5132] mb-1">
            {t("paddle_fee_card_title")}
          </h3>
          <p className="text-xs text-slate-500 mb-4 leading-relaxed">
            {t("paddle_purchase_card_hint")}
          </p>
          <div className="mb-4 flex items-end justify-center gap-2 text-[#0F5132]">
            {Number.isFinite(paddlePriceNumber) && paddlePriceNumber > 0 ? (
              <>
                <span className="text-3xl text-primary sm:text-4xl font-black tracking-tight">
                  {fmt(paddlePriceNumber)}
                </span>
                <img
                  src={SAR_ICON}
                  className="w-5 h-5 mb-3"
                  alt={isArUi ? "ريال" : "SAR"}
                />
              </>
            ) : (
              <span className="text-lg font-bold text-slate-400">—</span>
            )}
          </div>
          <DynamicButton
            onClick={onBuyPaddleClick}
            fullWidth
            isDisabled={buyingPaddle}
            className="w-full px-4 py-3 rounded-md bg-gradient-to-r from-[#0F5132] to-emerald-600 text-white font-bold hover:from-[#0F5132]/90 hover:to-emerald-600/90 disabled:opacity-60 disabled:cursor-not-allowed shadow-lg shadow-emerald-500/20 transition-all"
          >
            {buyPaddleCtaLabel}
          </DynamicButton>
        </div>
      ) : null}

      {!hideLiveBiddersForSoldResult ? (
        <div className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_10px_24px_rgba(15,81,50,0.07)]">
          <h3 className="font-bold text-[#0F5132] mb-4">
            {t("live_bidders_title")}
          </h3>
          <div className="space-y-2 text-sm text-slate-700 ">
            {(liveBidders && liveBidders.length > 0 ? liveBidders : [])
              .slice(0, 6)
              .map((b, idx) => (
                <div
                  key={idx}
                  className="flex items-center justify-between px-3 py-2 rounded-md bg-slate-50"
                >
                  <span className="truncate">{b.name}</span>
                  <span className="inline-flex items-center gap-1 rounded-full bg-slate-100 px-3 py-1 text-xs font-black text-slate-800 border border-slate-200">
                    {isArUi ? "مضرب" : "Paddle"} {b.paddle}
                  </span>

                  <span className="font-semibold text-[#0F5132] inline-flex items-center gap-1">
                    <span>{fmt(Number(b.amount))}</span>
                    <img src={SAR_ICON} className="w-4 h-4 mb-2" alt="SAR" />
                  </span>
                </div>
              ))}
            {(!liveBidders || liveBidders.length === 0) && (
              <div className="text-xs text-slate-500">
                {tAuction("no_bids_yet")}
              </div>
            )}
          </div>
        </div>
      ) : null}
      <div className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_10px_24px_rgba(15,81,50,0.07)]">
        <h3 className="font-bold text-[#0F5132] mb-2">
          {t("conditions_title")}
        </h3>
        <ul className="space-y-2 text-sm text-slate-700">
          <li className="p-3 rounded-md border">
            {t("condition_min_increment", { value: fmt(minIncrement) })}
          </li>
          <li className="p-3 rounded-md border">
            {t.rich("condition_commission", {
              value: commissionPct,
              b: (chunks) => <b>{chunks}</b>,
            })}
          </li>
          <li className="p-3 rounded-md border">
            {t.rich("condition_deadline", {
              b: (chunks) => <b>{chunks}</b>,
            })}
          </li>
          <li className="p-3 rounded-md border">{t("condition_rules")}</li>
        </ul>
        <div className="mt-3 p-3 rounded-md bg-slate-50 border border-slate-200 text-sm text-slate-700 leading-7">
          {isArUi ? (
            <>
              بالمتابعة أنت توافق على{" "}
              <Link
                href={`/${locale}/privacy`}
                className="text-[#0F5132] font-semibold underline underline-offset-2"
              >
                سياسة الخصوصية
              </Link>{" "}
              و{" "}
              <Link
                href={`/${locale}/term-conditions`}
                className="text-[#0F5132] font-semibold underline underline-offset-2"
              >
                الشروط والأحكام
              </Link>
              .
            </>
          ) : (
            <>
              By continuing, you agree to the{" "}
              <Link
                href={`/${locale}/privacy`}
                className="text-[#0F5132] font-semibold underline underline-offset-2"
              >
                Privacy Policy
              </Link>{" "}
              and{" "}
              <Link
                href={`/${locale}/term-conditions`}
                className="text-[#0F5132] font-semibold underline underline-offset-2"
              >
                Terms & Conditions
              </Link>
              .
            </>
          )}
        </div>
      </div>

      <div className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_10px_24px_rgba(15,81,50,0.07)]">
        <h3 className="font-bold text-[#0F5132] mb-2">
          {t("owner_info_title")}
        </h3>
        <div className="text-sm text-slate-700">
          <div className="flex items-center justify-between">
            <div>
              {shouldHideOwnerInfo ? (
                <div className="text-xs text-slate-600 leading-relaxed">
                  {t("owner_hidden_hint")}
                </div>
              ) : (
                <>
                  <div className="font-bold">{owner}</div>
                  <div className="text-slate-600">{t("owner_verified")}</div>
                  {shouldShowOwnerLocation && (
                    <div className="text-slate-600 text-xs mt-1">
                      {t("owner_location_label")}: {ownerCountry || "—"}
                      {ownerState ? `، ${ownerState}` : ""}
                    </div>
                  )}
                </>
              )}
            </div>
            {/*  <a
              className="px-3 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 transition"
              href="#"
            >
              زيارة المتجر
            </a> */}
          </div>
        </div>
      </div>
    </aside>
  );
}
