"use client";

import { useTranslations, useLocale } from "next-intl";
import { useNumberFormatter } from "@/app/[lang]/providers";
import DynamicButton from "@/components/button";
import type { GroupAuction, AuctionGroupRoom } from "@/actions/group-auctions";
import { useState, useMemo, useEffect, useRef } from "react";
import { getAnnualQuickDeltas } from "@/lib/auction/biddingRules";
import Image from "next/image";
import Link from "next/link";
import { useGeneralSettings } from "@/lib/clientQueries";
import { formatPaddleDisplay } from "@/lib/utils";

interface AnimalDetails {
  name?: string;
  father_name?: string;
  mother_name?: string;
  age?: string | number;
  breed?: string;
  color?: string;
  owner?: string;
}

interface CurrentAuctionCardProps {
  groupAuction: GroupAuction;
  currentRoom: AuctionGroupRoom | null;
  currentPrice: number;
  timeRemaining: string;
  animalType: "horse" | "camel";
  onBidClick: (amount: number) => void;
  onBuyPaddle: () => void;
  hasPaddle?: boolean;
  hasAvailablePaddle?: boolean;
  userPaddleNumber?: string | null;
  isActive: boolean;
  marketEntryPrice?: number | null;
  isInMarketPhase?: boolean;
  animalDetails?: AnimalDetails | null;
  highestBidderPaddle?: string | null;
  isVipBidder?: boolean;
  sessionLoading?: boolean;
  /** When true, show owned paddle number + type; otherwise show normal/premium prices */
  shouldShowOwnedPaddle?: boolean;
  effectivePaddleNumber?: string | null;
  effectivePaddleType?: string | null;
  paddlePrices?: {
    normalPrice: number;
    premiumPrice: number;
    premiumUseTimes: number;
  };
  /**
   * Camel live: exact count of singles for the active auction_group (from group details API).
   * When null/undefined, falls back to `currentRoom.single_auctions` length or `single_auctions_count`.
   */
  liveAuctionGroupSinglesCount?: number | null;
  /**
   * Camel yearly auctions: multiplier applied by the parent on every entered
   * bid increment (per-camel value × camel count). Used here only to render
   * the helper text and the live preview of the total. Defaults to `1`,
   * which is the value horse auctions and unknown-count camel rooms pass.
   */
  bidMultiplier?: number;
}

const HARAJ_SOUND_SRC = "/sounds/haraj.mpeg";

export default function CurrentAuctionCard({
  groupAuction,
  currentRoom,
  currentPrice,
  timeRemaining,
  animalType,
  onBidClick,
  onBuyPaddle,
  hasPaddle = false,
  hasAvailablePaddle = false,
  userPaddleNumber = null,
  isActive,
  marketEntryPrice = null,
  isInMarketPhase = false,
  animalDetails = null,
  highestBidderPaddle = null,
  isVipBidder = false,
  sessionLoading = false,
  shouldShowOwnedPaddle = false,
  effectivePaddleNumber = null,
  effectivePaddleType = null,
  paddlePrices,
  liveAuctionGroupSinglesCount = null,
  bidMultiplier = 1,
}: CurrentAuctionCardProps) {
  const formatPaddleType = (type: string | null | undefined) => {
    if (!type) return "—";
    const v = String(type).toLowerCase();
    if (v.includes("premium"))
      return locale.startsWith("ar") ? "مميز" : "Premium";
    if (v.includes("normal"))
      return locale.startsWith("ar") ? "عادي" : "Normal";
    return type;
  };
  const t = useTranslations("YEARLY_AUCTION_LIVE");
  const locale = useLocale();
  const { toLatinDigits } = useNumberFormatter();
  const { data: settings } = useGeneralSettings();

  const settingUrl = (value: any): string | undefined => {
    if (!value) return undefined;
    if (typeof value === "string") return value;
    if (typeof value === "object" && typeof value.url === "string")
      return value.url;
    return undefined;
  };

  const platformFallbackImage =
    animalType === "camel"
      ? settingUrl((settings as any)?.platform_1_image) || "/images/banner.avif"
      : settingUrl((settings as any)?.platform_2_image) ||
        "/images/unnamed.jpg";

  const [customAmount, setCustomAmount] = useState<number>(0);
  const harajAudioRef = useRef<HTMLAudioElement | null>(null);
  const prevMarketTotalRef = useRef<number | null>(null);
  const roomTimerKeyRef = useRef<string>("");

  const hasBidAccess = Boolean(hasAvailablePaddle || userPaddleNumber);
  const canPlaceBid = hasBidAccess && isActive;
  const shouldShowBuyPaddle = !hasBidAccess && !sessionLoading;

  const getLocalizedText = (text: string | null | undefined) => {
    if (!text) return text;
    try {
      const parsed = JSON.parse(text);
      return parsed[locale] || parsed["en"] || text;
    } catch {
      return text;
    }
  };
  const handleQuickBidClick = (amount: number) => {
    setCustomAmount(amount);
  };

  const handleBidNow = () => {
    if (!canPlaceBid || customAmount <= 0) return;
    onBidClick(customAmount);
    setCustomAmount(0);
  };

  const quickBidOptions = useMemo(() => {
    return getAnnualQuickDeltas(currentPrice);
  }, [currentPrice]);

  // Per-camel bidding helpers. We only surface the multiplier UI when:
  //  - the room is a camel yearly auction (parent always sends 1 for horse), and
  //  - we have a real count > 1 (a single camel would be a no-op multiplication).
  const safeBidMultiplier =
    Number.isFinite(bidMultiplier) && bidMultiplier > 0
      ? Math.floor(bidMultiplier)
      : 1;
  const showPerCamelHints = animalType === "camel" && safeBidMultiplier > 1;
  const previewTotalDelta = customAmount > 0 ? customAmount * safeBidMultiplier : 0;

  const SAR_ICON = "/Riyal.svg";

  const roomNumber = currentRoom?.day_order || "—";
  const roomName = currentRoom ? getLocalizedText(currentRoom.name) : null;
  const animalLabel =
    animalType === "horse" ? t("horse_label") : t("camel_label");
  const roomImage = currentRoom?.main_image?.url || platformFallbackImage;
  const firstSingleAuctionId = currentRoom?.first_single_auction_id;

  const displayedCamelSingleAuctionsCount = useMemo(() => {
    if (animalType !== "camel") return null;
    if (
      liveAuctionGroupSinglesCount != null &&
      Number.isFinite(liveAuctionGroupSinglesCount)
    ) {
      return liveAuctionGroupSinglesCount;
    }
    const embedded = currentRoom?.single_auctions;
    if (Array.isArray(embedded)) return embedded.length;
    const raw = currentRoom?.single_auctions_count;
    const n = typeof raw === "number" ? raw : Number(String(raw).trim());
    return Number.isFinite(n) ? n : null;
  }, [
    animalType,
    liveAuctionGroupSinglesCount,
    currentRoom?.single_auctions,
    currentRoom?.single_auctions_count,
  ]);

  const getTimerDisplay = (timeStr: string, inMarket: boolean) => {
    if (!timeStr)
      return {
        phase: 0,
        phaseSeconds: 0,
        phaseLabel: "",
        bgColor: "",
        textColor: "",
      };

    const [minutes, seconds] = timeStr.split(":").map(Number);
    const totalSeconds = minutes * 60 + seconds;
    if (inMarket) {
      // مزاد phases: 15 seconds per phase (مزاد1, مزاد2, مزاد3)
      // Phase 3: Last 15 seconds (1-15) - RED
      if (totalSeconds <= 15) {
        return {
          phase: 3,
          phaseSeconds: totalSeconds,
          phaseLabel: "مزاد3",
          bgColor: "bg-red-500 animate-pulse",
          textColor: "text-white",
        };
      }
      // Phase 2: 16-30 seconds - YELLOW
      else if (totalSeconds <= 30) {
        return {
          phase: 2,
          phaseSeconds: totalSeconds - 15,
          phaseLabel: "مزاد2",
          bgColor: "bg-amber-400 animate-pulse",
          textColor: "text-amber-900",
        };
      }
      // Phase 1: 31-45 seconds - YELLOW
      else if (totalSeconds <= 45) {
        return {
          phase: 1,
          phaseSeconds: totalSeconds - 30,
          phaseLabel: "مزاد1",
          bgColor: "bg-amber-400 animate-pulse",
          textColor: "text-amber-900",
        };
      }
      // More than 45 seconds - show regular timer
      return {
        phase: 0,
        phaseSeconds: totalSeconds,
        phaseLabel: "",
        bgColor: "bg-transparent",
        textColor: "text-[#0F5132]",
      };
    } else {
      // Pre-market phase: No مزاد phase labels, use color based on time
      // Red: <= 30 seconds (00:30 and below)
      if (totalSeconds <= 30) {
        return {
          phase: 3,
          phaseSeconds: totalSeconds,
          phaseLabel: "",
          bgColor: "bg-red-500 animate-pulse",
          textColor: "text-white",
        };
      }
      // Yellow: 31-119 seconds (00:31 to 01:59)
      else if (totalSeconds < 120) {
        return {
          phase: 2,
          phaseSeconds: totalSeconds,
          phaseLabel: "",
          bgColor: "bg-amber-400 animate-pulse",
          textColor: "text-amber-900",
        };
      }
      // Green: >= 120 seconds (02:00 and above)
      else {
        return {
          phase: 1,
          phaseSeconds: totalSeconds,
          phaseLabel: "",
          bgColor: "bg-green-500",
          textColor: "text-white",
        };
      }
    }
  };

  const { phase, phaseSeconds, phaseLabel, bgColor, textColor } =
    getTimerDisplay(timeRemaining, isInMarketPhase);

  useEffect(() => {
    const roomKey = `${currentRoom?.first_single_auction_id ?? ""}:${currentRoom?.day_order ?? ""}`;
    if (roomTimerKeyRef.current !== roomKey) {
      roomTimerKeyRef.current = roomKey;
      prevMarketTotalRef.current = null;
    }

    if (!isInMarketPhase || !timeRemaining?.trim()) {
      prevMarketTotalRef.current = null;
      return;
    }

    const parts = timeRemaining.split(":");
    if (parts.length < 2) return;
    const minutes = Number(parts[0]);
    const seconds = Number(parts[1]);
    if (Number.isNaN(minutes) || Number.isNaN(seconds)) return;
    const totalSeconds = minutes * 60 + seconds;

    const prev = prevMarketTotalRef.current;
    prevMarketTotalRef.current = totalSeconds;

    if (prev === null) return;

    const enteredMazadPhase1 = prev > 45 && totalSeconds <= 45;
    const enteredMazadPhase2 =
      prev > 30 && totalSeconds <= 30 && totalSeconds > 15;
    const enteredMazadPhase3 = prev > 15 && totalSeconds <= 15;

    if (
      !enteredMazadPhase1 &&
      !enteredMazadPhase2 &&
      !enteredMazadPhase3
    )
      return;

    const audio =
      harajAudioRef.current ??
      (harajAudioRef.current = new Audio(HARAJ_SOUND_SRC));
    audio.currentTime = 0;
    void audio.play().catch(() => {});
  }, [
    isInMarketPhase,
    timeRemaining,
    currentRoom?.first_single_auction_id,
    currentRoom?.day_order,
  ]);

  return (
    <>
      {/* Mobile Bottom Bar - Fixed at bottom */}
      <div className="fixed bottom-0 left-0 right-0 z-50 bg-white border-t border-gray-200 shadow-[0_-4px_20px_rgba(0,0,0,0.1)] p-3 sm:hidden safe-area-bottom">
        <div className="flex items-center gap-3">
          {/* Price + quick bids container */}
          <div className="flex flex-col flex-2 gap-2 min-w-0">
            <div className="bg-gray-100 rounded-2xl px-4 py-2">
              <div className="flex items-center justify-between gap-2 mb-0.5">
                <p className="text-[11px] text-gray-500">
                  {t("current_price_label")}
                </p>
                {showPerCamelHints ? (
                  <span className="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-1.5 py-0.5 text-[10px] font-bold text-emerald-700 border border-emerald-200 shrink-0">
                    <span aria-hidden>🐪</span>
                    <span>×{toLatinDigits(String(safeBidMultiplier))}</span>
                  </span>
                ) : null}
              </div>
              <div className="flex items-end gap-1.5">
                <span className="text-2xl font-extrabold text-[#1B7A50] tabular-nums">
                  {toLatinDigits(currentPrice.toLocaleString())}
                </span>
                <Image
                  src={SAR_ICON}
                  width={20}
                  height={20}
                  alt=""
                  className="opacity-75 shrink-0 mb-0.5"
                />
              </div>
              {showPerCamelHints && previewTotalDelta > 0 ? (
                <p className="mt-1 text-[10px] text-emerald-700 tabular-nums">
                  {t("per_camel_bid_total_short", {
                    amount: toLatinDigits(customAmount.toLocaleString()),
                    count: toLatinDigits(String(safeBidMultiplier)),
                    total: toLatinDigits(previewTotalDelta.toLocaleString()),
                  })}
                </p>
              ) : null}
            </div>
            <div className="flex items-center gap-1.5 overflow-x-auto hide-scrollbar">
              {quickBidOptions.slice(0, 3).map((amount) => (
                <button
                  key={amount}
                  type="button"
                  onClick={() => {
                    if (!canPlaceBid) return;
                    handleQuickBidClick(amount);
                  }}
                  disabled={!canPlaceBid}
                  className={`shrink-0 px-3 py-1.5 rounded-lg text-[11px] font-bold border transition-all disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-1 ${
                    customAmount === amount
                      ? "bg-[#1B7A50] text-white border-[#1B7A50] [&_img]:brightness-0 [&_img]:invert"
                      : "bg-white border-gray-200 text-gray-700 active:bg-[#1B7A50] active:text-white active:border-[#1B7A50] active:[&_img]:brightness-0 active:[&_img]:invert"
                  }`}
                >
                  <span className="tabular-nums">
                    +{toLatinDigits(amount.toLocaleString())}
                  </span>
                  <Image
                    src={SAR_ICON}
                    width={12}
                    height={12}
                    alt=""
                    className="opacity-80 shrink-0 pointer-events-none"
                  />
                </button>
              ))}
            </div>
          </div>

          {/* Bid or buy button - takes roughly one third */}
          <div className="flex-1 min-w-[30%]">
            {hasBidAccess ? (
              <DynamicButton
                onClick={handleBidNow}
                isDisabled={!canPlaceBid || customAmount <= 0}
                className="w-full px-4 py-2.5 text-sm"
              >
                {t("bid_now_short")}
              </DynamicButton>
            ) : shouldShowBuyPaddle ? (
              <DynamicButton
                onClick={onBuyPaddle}
                className="w-full px-4 py-2.5 text-sm"
              >
                {t("buy_paddle")}
              </DynamicButton>
            ) : null}
          </div>
        </div>

        {/* Timer indicator */}
        {timeRemaining && (
          <div
            className={`mt-2 flex items-center justify-center gap-2 ${
              isInMarketPhase && phaseLabel ? bgColor : "bg-amber-200/70"
            } ${isInMarketPhase && phaseLabel ? textColor : "text-amber-900"} rounded-lg py-1.5`}
          >
            {isInMarketPhase && phaseLabel ? (
              <>
                <span className={`text-sm font-bold ${textColor}`}>
                  {phaseLabel}
                </span>
                <span className={`text-sm font-bold ${textColor}`}>
                  {`0:${phaseSeconds.toString().padStart(2, "0")}`}
                </span>
              </>
            ) : (
              <span className={`text-sm font-bold ${textColor}`}>
                {timeRemaining}
              </span>
            )}
          </div>
        )}
      </div>

      {/* Spacer so fixed bottom bar doesn't cover content on small screens */}
      <div className="sm:hidden h-20" aria-hidden="true" />

      {/* Add padding to main content to account for bottom bar on mobile */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-4 pb-6 sm:pb-0">
        <div className="flex flex-col gap-4  lg:col-span-7 ">
          <section className="bg-white text-start rounded-[22px] shadow-[0_2px_8px_rgba(15,23,42,0.06)] border border-gray-200 overflow-hidden">
            <div className="p-5">
              <div className="text-xl  text-start  font-extrabold text-[#0F7A4A]">
                {animalType === "horse"
                  ? t("horse_on_platform")
                  : t("camel_on_platform")}
              </div>
              <div className="flex items-start justify-start gap-4">
                <div className="shrink-0 w-16 h-16 sm:w-20 sm:h-20 rounded-full border border-gray-300 bg-gray-50 flex items-center justify-center text-3xl sm:text-4xl font-black text-gray-900 leading-none">
                  {toLatinDigits(String(roomNumber))}
                </div>
                <div className={`flex-1 min-w-0 `}>
                  <h3 className="mt-1 font-black text-3xl text-gray-900 truncate">
                    {animalDetails?.name || roomName || animalLabel}
                  </h3>

                  {animalType === "camel" ? (
                    <>
                      <div className="mt-1 text-base sm:text-lg font-semibold text-gray-800">
                        <span className="text-black">
                          {t("camel_count_label")}:
                        </span>{" "}
                        {displayedCamelSingleAuctionsCount != null
                          ? toLatinDigits(
                              String(displayedCamelSingleAuctionsCount),
                            )
                          : "—"}
                      </div>
                      <div className="mt-1 text-base sm:text-lg font-semibold text-gray-800">
                        <span className="text-black">{t("breed_label")}:</span>{" "}
                        {animalDetails?.breed || "—"}
                      </div>
                    </>
                  ) : (
                    <>
                      <div className="mt-2 text-sm sm:text-lg font-semibold text-gray-800">
                        <span className="text-black  font-normal">
                          {t("father_label")}:
                        </span>{" "}
                        {animalDetails?.father_name || "—"}
                        <span className="text-gray-300 px-2">•</span>
                        <span className="text-black font-normal">
                          {t("mother_label")}:
                        </span>{" "}
                        {animalDetails?.mother_name || "—"}
                      </div>
                      <div className="mt-1 text-base sm:text-lg font-semibold text-gray-800">
                        <span className="text-black">{t("breed_label")}:</span>{" "}
                        {animalDetails?.breed || "—"}
                      </div>
                      {animalDetails?.owner ? (
                        <div className="mt-2 inline-flex items-center rounded-xl bg-gray-100 px-3 py-1.5 text-base font-semibold text-gray-800">
                          <span className="text-black">
                            {t("owner_label")}:
                          </span>{" "}
                          {animalDetails.owner}
                        </div>
                      ) : null}
                    </>
                  )}

                  {animalType === "camel" && currentRoom?.id ? (
                    <div className="mt-3">
                      <Link
                        target="_blank"
                        href={`/${locale}/annual-auctions/${groupAuction.id}/group/${currentRoom.id}`}
                        className="inline-flex items-center justify-center h-10 px-5 text-sm font-semibold text-[#1B7A50] border border-[#1B7A50] rounded-xl hover:bg-[#1B7A50]/5 transition-colors"
                      >
                        {t("view_camel_details")}
                      </Link>
                    </div>
                  ) : firstSingleAuctionId ? (
                    <div className="mt-3">
                      <Link
                        target="_blank"
                        href={`/${locale}/annual-item/${firstSingleAuctionId}`}
                        className="inline-flex items-center justify-center h-10 px-5 text-sm font-semibold text-[#1B7A50] border border-[#1B7A50] rounded-xl hover:bg-[#1B7A50]/5 transition-colors"
                      >
                        {t("view_horse_details")}
                      </Link>
                    </div>
                  ) : null}
                </div>
              </div>
            </div>
          </section>
          <div className="border rounded-[22px] shadow-[0_2px_8px_rgba(15,23,42,0.06)] p-4 border-gray-300 bg-white p-4">
            <div className="flex items-center justify-between gap-2 mb-2">
              <div className="text-xs text-gray-500">
                {t("quick_bid_amounts")}
              </div>
              {showPerCamelHints ? (
                <span className="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-[11px] font-bold text-emerald-700 border border-emerald-200">
                  <span aria-hidden>🐪</span>
                  <span>
                    {t("per_camel_bid_label")} ×{" "}
                    {toLatinDigits(String(safeBidMultiplier))}
                  </span>
                </span>
              ) : null}
            </div>

            <div className=" e text-start ">
              <div className="flex flex-col items-center gap-2">
                <div className="flex flex-wrap items-center gap-2 ml-auto">
                  {quickBidOptions.map((amount) => (
                    <button
                      key={amount}
                      type="button"
                      onClick={() => handleQuickBidClick(amount)}
                      disabled={!canPlaceBid}
                      className={`h-8 px-3 sm:px-4 rounded-xl text-xs font-semibold transition-all border inline-flex items-center justify-center gap-1.5 ${
                        customAmount === amount
                          ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                          : "bg-gray-100 text-gray-700 border-gray-200 hover:border-[#1B7A50] disabled:hover:border-gray-200"
                      }`}
                    >
                      <span className="tabular-nums">
                        {toLatinDigits(amount.toLocaleString())}
                      </span>
                      <Image
                        src={SAR_ICON}
                        width={14}
                        height={14}
                        alt=""
                        className={`shrink-0 opacity-90 ${customAmount === amount ? "brightness-0 invert" : ""}`}
                      />
                    </button>
                  ))}
                </div>
                <div className="flex w-full items-center gap-2">
                  <div className="flex flex-1 min-w-[200px] sm:min-w-[260px] h-10 items-center gap-2 px-3 border border-gray-200 rounded-xl bg-white focus-within:ring-1 focus-within:ring-[#1B7A50]">
                    <input
                      type="number"
                      min="1"
                      value={customAmount || ""}
                      onChange={(e) =>
                        setCustomAmount(Number(e.target.value || 0))
                      }
                      placeholder={
                        showPerCamelHints
                          ? t("enter_custom_amount_per_camel")
                          : t("enter_custom_amount")
                      }
                      disabled={!canPlaceBid}
                      className="flex-1 min-w-0 h-full border-0 bg-transparent text-sm text-start focus:outline-none placeholder:text-gray-400 disabled:opacity-50"
                      onKeyDown={(e) => {
                        if (
                          e.key === "Enter" &&
                          customAmount > 0 &&
                          canPlaceBid
                        ) {
                          handleBidNow();
                        }
                      }}
                    />
                    <Image
                      src={SAR_ICON}
                      width={18}
                      height={18}
                      alt=""
                      className="shrink-0 opacity-75 pointer-events-none"
                    />
                  </div>
                  {hasBidAccess ? (
                    <DynamicButton
                      onClick={handleBidNow}
                      isDisabled={!canPlaceBid || customAmount <= 0}
                      className="shrink-0 h-10 px-6 text-sm font-semibold"
                    >
                      {t("bid_now_short")}
                    </DynamicButton>
                  ) : shouldShowBuyPaddle ? (
                    <DynamicButton
                      onClick={onBuyPaddle}
                      className="shrink-0 h-10 px-6 text-sm font-semibold"
                    >
                      {t("buy_paddle")}
                    </DynamicButton>
                  ) : null}
                </div>
                {showPerCamelHints ? (
                  <div className="w-full text-xs text-gray-600 leading-relaxed">
                    <p className="font-semibold text-emerald-700">
                      {t("per_camel_bid_hint")}
                    </p>
                    {previewTotalDelta > 0 ? (
                      <p
                        className="mt-0.5 tabular-nums"
                        aria-live="polite"
                      >
                        {t("per_camel_bid_total", {
                          amount: toLatinDigits(customAmount.toLocaleString()),
                          count: toLatinDigits(String(safeBidMultiplier)),
                          total: toLatinDigits(
                            previewTotalDelta.toLocaleString(),
                          ),
                        })}
                      </p>
                    ) : null}
                  </div>
                ) : null}
              </div>

              {/* <div className=" flex items-center justify-between gap-3 flex-wrap">
                  <span className="text-xs text-gray-400">{t("bid_notice")}</span>
                  {(shouldShowOwnedPaddle &&
                    (effectivePaddleNumber || effectivePaddleType)) ||
                  (paddlePrices && !shouldShowOwnedPaddle) ? (
                    <div className="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3">
                      {shouldShowOwnedPaddle ? (
                        <>
                          <div className="flex items-center gap-2">
                            <p className="text-sm font-extrabold ">
                              {effectivePaddleNumber
                                ? formatPaddleDisplay(effectivePaddleNumber)
                                : "—"}
                            </p>
                            <p className="text-xs">{t("paddle_number_label")}</p>
                          </div>
                          <div className="flex items-center gap-2">
                            <p className="text-sm font-extrabold ">
                              {formatPaddleType(effectivePaddleType)}
                            </p>
                            <p className="text-xs">{t("paddle_type_label")}</p>
                          </div>
                        </>
                      ) : (
                        <>
                          <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
                            <p className="text-sm text-slate-500 mb-1">
                              {t("normal_paddle_price")}
                            </p>
                            <p className="text-lg font-extrabold text-slate-900">
                              {t("currency")}{" "}
                              {toLatinDigits(
                                paddlePrices!.normalPrice.toFixed(2),
                              )}
                            </p>
                          </div>
                          <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
                            <p className="text-sm text-slate-500 mb-1">
                              {t("premium_paddle_price")}
                            </p>
                            <p className="text-lg font-extrabold text-slate-900">
                              {t("currency")}{" "}
                              {toLatinDigits(
                                paddlePrices!.premiumPrice.toFixed(2),
                              )}
                            </p>
                            <p className="text-xs text-slate-500 mt-1">
                              {t("premium_use_times")}:{" "}
                              {toLatinDigits(
                                String(paddlePrices!.premiumUseTimes),
                              )}
                            </p>
                          </div>
                        </>
                      )}
                    </div>
                  ) : null}
                </div> */}

              {/* Paddle info or prices (same as sidebar in YearlyAuctionLiveClient) */}
            </div>
          </div>
        </div>
        <section className="bg-white h-min rounded-[22px] shadow-[0_2px_8px_rgba(15,23,42,0.06)] border border-gray-200 p-4 sm:p-5 lg:col-span-5">
          <div className="flex items-center justify-between gap-3">
            <div className={`flex-1 min-w-0 `}>
              <div className="text-lg sm:text-xl font-extrabold text-gray-900">
                {t("highest_bid_label")}
              </div>
            </div>

            <div
              className={`rounded-2xl px-4 py-2 min-w-[108px] text-center shrink-0 ${
                isInMarketPhase && phaseLabel ? bgColor : "bg-[#F2DF8D]"
              } ${isInMarketPhase && phaseLabel ? textColor : ""}`}
            >
              {isInMarketPhase ? (
                <>
                  <div
                    className={`text-xs sm:text-sm font-bold leading-tight mb-1 ${
                      phaseLabel ? textColor : "text-[#B3261E]"
                    }`}
                  >
                    {phaseLabel || t("haraj_label")}
                  </div>
                  <span
                    className={`text-2xl sm:text-3xl font-black tabular-nums leading-none block ${
                      phaseLabel ? textColor : "text-[#B3261E]"
                    }`}
                  >
                    {phaseLabel
                      ? `0:${phaseSeconds.toString().padStart(2, "0")}`
                      : toLatinDigits(timeRemaining || "0:00")}
                  </span>
                </>
              ) : (
                <span className="text-2xl sm:text-3xl font-black text-[#B3261E] tabular-nums leading-none">
                  {toLatinDigits(timeRemaining || "0:00")}
                </span>
              )}
            </div>
          </div>

          <div className="mt-4 rounded-2xl bg-gray-100 p-4">
            <div className={`text-sm font-bold text-gray-900 `}>
              {t("current_price_label")}
            </div>
            <div className={`mt-3 flex items-end gap-2 `}>
              <span className="text-4xl sm:text-5xl font-black text-[#1B7A50] tabular-nums leading-none">
                {toLatinDigits(currentPrice.toLocaleString())}
              </span>
              <Image
                src={SAR_ICON}
                width={30}
                height={30}
                alt="SAR"
                className="opacity-70 mb-2"
              />
            </div>
          </div>

          <div className="mt-4 rounded-2xl bg-gray-100 p-4">
            <div className={`text-sm font-bold text-gray-900 `}>
              {t("bidder_paddle_label")}
            </div>
            <div
              className={`mt-2 text-4xl sm:text-5xl font-black text-gray-900 leading-none `}
            >
              {formatPaddleDisplay(highestBidderPaddle) || "—"}
            </div>
          </div>
        </section>
      </div>
    </>
  );
}
