"use client";

import { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import { useLocale, useTranslations } from "next-intl";
import { useSetAtom } from "jotai";
import { motion } from "framer-motion";
import {
  CheckCircle2,
  ArrowLeft,
  ArrowRight,
  Send,
  ExternalLink,
} from "lucide-react";
import RiyalIcon from "@/components/ui/RiyalIcon";
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 { OfferModal } from "@/components/annaulMazad/live-rooms-table/LiveRoomsTableModals";
import { loginModalAtom } from "@/components/state/loginAtom";
import { createPurchaseOffer } from "@/actions/purchase-offers";
import type {
  GroupAuction,
  AuctionGroupDetails,
} from "@/actions/group-auctions";

type SingleAuctionItem = {
  id?: string | number;
  unique_id?: string | null;
  title?: string;
  horse_name?: string;
  status?: string;
  can_send_offer?: boolean;
  animal?: {
    name?: string | null;
    father_name?: string | null;
    mother_name?: string | null;
    date_of_birth?: string | null;
    breed?: string | null;
    usage?: string | null;
    animal_usage?: string | null;
  } | null;
  horse?: {
    name?: string | null;
    father_name?: string | null;
    mother_name?: string | null;
    date_of_birth?: string | null;
    breed?: string | null;
    animal_usage?: string | null;
  } | null;
  camel?: {
    name?: string | null;
    father_name?: string | null;
    mother_name?: string | null;
    date_of_birth?: string | null;
    breed?: string | null;
    animal_usage?: string | null;
  } | null;
  main_image?: { url?: string };
  media_files?: { main_image?: { url?: string } };
  main_image_url?: string;
  winner_user?: { id?: string; name?: string } | null;
  winner_name?: string | null;
  winning_bid?: { amount?: string | number } | null;
  animal_usage?: string | null;
};

interface GroupDetailClientProps {
  auction: GroupAuction | null;
  groupDetails: AuctionGroupDetails | null;
  groupAuctionId: string;
  auctionGroupId: string;
  initialItems?: unknown[];
}

/** API may send Arabic labels; toLowerCase() does not normalize Arabic. */
function isUnsoldStatusString(raw: string): boolean {
  const t = raw.trim();
  if (!t) return false;
  const l = t.toLowerCase();
  if (l === "unsold" || l === "not_sold" || l === "not sold") return true;
  if (t === "لم يتم البيع" || t === "غير مباع") return true;
  if (/لم[\s\u200c]*يتم[\s\u200c]*البيع/i.test(t)) return true;
  if (/غير[\s\u200c]*مباع/i.test(t)) return true;
  return false;
}

function normalizePaddleLabel(v: unknown): string {
  if (v == null) return "";
  const s = String(v).trim();
  return s;
}

/** POST body shape varies; prefer any paddle id the API returns. */
function extractPaddleFromPurchaseOfferResponse(result: unknown): string | null {
  const r = result as Record<string, unknown> | null;
  if (r && typeof r === "object") {
    const root = normalizePaddleLabel(
      r.paddle_number ?? r.paddleNumber ?? r.paddle_unique_id ?? r.paddleUniqueId,
    );
    if (root) return root;
  }
  const d = r?.data as Record<string, unknown> | null | undefined;
  if (!d || typeof d !== "object") return null;
  const o = d as Record<string, unknown>;
  const candidates = [
    o.paddle_number,
    o.paddleNumber,
    o.paddle_unique_id,
    o.paddleUniqueId,
    o.buyer_paddle_number,
    (o.buyer as Record<string, unknown> | undefined)?.paddle_number,
    (o.auction as Record<string, unknown> | undefined)?.paddle_number,
  ];
  for (const c of candidates) {
    const label = normalizePaddleLabel(c);
    if (label) return label;
  }
  return null;
}

function parseSingleAuctionsResponse(json: any): SingleAuctionItem[] {
  const raw = json?.data;
  let items: unknown[] = [];
  if (Array.isArray(raw)) {
    items = raw;
  } else if (raw && typeof raw === "object") {
    items = Array.isArray(raw.data)
      ? raw.data
      : Array.isArray(raw.items)
        ? raw.items
        : [];
  }
  if (items.length === 0 && Array.isArray(json?.items)) {
    items = json.items;
  }
  if (items.length === 0 && Array.isArray((json as any)?.single_auctions)) {
    items = (json as any).single_auctions;
  }
  if (items.length === 0 && Array.isArray(json)) {
    items = json;
  }
  return (items || []) as SingleAuctionItem[];
}

function getAnimalFromItem(item: SingleAuctionItem) {
  return item?.animal ?? item?.camel ?? item?.horse ?? null;
}

function getUsageFromItem(
  item: SingleAuctionItem,
  locale: string,
  getLocalizedText: (t?: string | null) => string,
): string | null {
  const raw =
    item?.animal_usage ??
    (item as any)?.horse?.animal_usage ??
    (item as any)?.camel?.animal_usage ??
    (item as any)?.camel_group?.animal_usage ??
    item?.animal?.animal_usage ??
    (item as any)?.animal?.usage ??
    null;
  if (!raw) return null;
  if (typeof raw === "string") {
    if (raw.startsWith("{") || raw.startsWith("[")) {
      const parsed = getLocalizedText(raw);
      return parsed || null;
    }
    return raw;
  }
  if (typeof raw === "object" && raw !== null) {
    const name = (raw as any)?.name;
    if (typeof name === "string") return name;
    if (name && typeof name === "object") {
      const loc =
        (name as any)[locale] ?? (name as any)?.ar ?? (name as any)?.en;
      return typeof loc === "string" ? loc : null;
    }
  }
  return null;
}

export default function GroupDetailClient({
  auction,
  groupDetails,
  groupAuctionId,
  auctionGroupId,
  initialItems: initialItemsProp = [],
}: GroupDetailClientProps) {
  const router = useRouter();
  const params = useParams<{ lang?: string }>();
  const locale = useLocale();
  const isRtl = locale.startsWith("ar");
  const t = useTranslations("GROUP_DETAIL_PAGE");
  const tStatus = useTranslations("INNER_AUCTIONS_TABLE");
  const tToast = useTranslations("TOAST");
  const session = useSession();

  const initial = Array.isArray(initialItemsProp)
    ? (initialItemsProp as SingleAuctionItem[])
    : [];
  const [items, setItems] = useState<SingleAuctionItem[]>(initial);
  const [loading, setLoading] = useState(initial.length === 0);
  const setLoginModal = useSetAtom(loginModalAtom);
  // Paddle modal
  const [paddleModalOpen, setPaddleModalOpen] = useState(false);
  // Track if user just purchased a paddle (overrides server flags locally)
  const [paddleJustPurchased, setPaddleJustPurchased] = useState(false);
  // Offer modal
  const [offerModalOpen, setOfferModalOpen] = useState(false);
  const [offerAmount, setOfferAmount] = useState("");
  const [sendingOffer, setSendingOffer] = useState(false);
  const [offerSent, setOfferSent] = useState(false);
  /** Until router.refresh() repopulates groupDetails.paddle_number */
  const [offerSubmittedPaddle, setOfferSubmittedPaddle] = useState<
    string | null
  >(null);

  const toast = useAppToast();

  const animalType = (auction as any)?.animal_type ?? "camel";
  const isHorseFallbackGroup =
    String(animalType).toLowerCase() === "horse" &&
    groupAuctionId === auctionGroupId;

  const trimmedGroupStatus = String(
    (groupDetails as any)?.status ?? "",
  ).trim();
  const groupUnsold = isUnsoldStatusString(trimmedGroupStatus);
  const hasGroupPaddle =
    (groupDetails as any)?.paddle_number != null &&
    String((groupDetails as any)?.paddle_number).trim() !== "";
  const isGroupOwner = Boolean(
    (groupDetails as any)?.is_owner ?? (auction as any)?.is_owner,
  );

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

  const canBuyPaddleApi = Boolean((groupDetails as any)?.can_buy_paddle);
  const canSendOfferApi = Boolean((groupDetails as any)?.can_send_offer);

  /** Same as annual results table (RoomsTableCard): offer submitted + paddle from API. */
  const serverOfferSubmittedChip =
    groupUnsold &&
    hasGroupPaddle &&
    !canBuyPaddleApi &&
    !canSendOfferApi;

  const paddleLabelForSubmittedOffer =
    normalizePaddleLabel((groupDetails as any)?.paddle_number) ||
    offerSubmittedPaddle ||
    "";

  const showOfferSubmittedUI =
    Boolean(session) &&
    groupUnsold &&
    !isGroupOwner &&
    (serverOfferSubmittedChip || offerSent);

  /** Match results page: allow buy when API says so or auction lists a paddle price. */
  const canBuyPaddleEffective =
    !paddleJustPurchased &&
    !isGroupOwner &&
    groupUnsold &&
    !hasGroupPaddle &&
    (canBuyPaddleApi || auctionPrices.normalPrice > 0);

  const { data: availablePaddles = [] } = useAvailablePaddlesForAuction(
    canBuyPaddleEffective
      ? isHorseFallbackGroup
        ? groupAuctionId
        : auctionGroupId
      : undefined,
    "annual",
  );

  const minOfferAmount =
    groupUnsold
      ? Number((groupDetails as any)?.info_final_bid?.lowest_offer_value ?? 0) ||
      0
      : Number(
        (groupDetails as any)?.winning_bid?.amount ??
        (groupDetails as any)?.market_entry_price ??
        0,
      ) || 0;

  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;
    }
    setSendingOffer(true);
    try {
      const result = await createPurchaseOffer({
        auction_type: "group",
        auction_id: auctionGroupId,
        full_amount: amount,
      });
      if (result.success) {
        const paddleFromRes =
          extractPaddleFromPurchaseOfferResponse(result);
        if (paddleFromRes) setOfferSubmittedPaddle(paddleFromRes);
        toast.success(
          result.message || tToast("offer_sent_success"),
        );
        setOfferSent(true);
        setOfferModalOpen(false);
        setOfferAmount("");
        setPaddleJustPurchased(false);
        router.refresh();
      } else {
        toast.error(
          result.message || tToast("offer_send_failed"),
        );
      }
    } catch {
      toast.error(tToast("generic_try_again"));
    } finally {
      setSendingOffer(false);
    }
  };

  const API_BASE =
    (typeof process !== "undefined" && process.env.NEXT_PUBLIC_BASE_URL) ||
    "https://dev-endpoint.ataya.sa/api";

  const lang = (params?.lang as string) || "ar";

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

  useEffect(() => {
    const fetchItems = async () => {
      if (initial.length > 0) {
        setLoading(false);
        return;
      }
      setLoading(true);

      const nested =
        (groupDetails as any)?.single_auctions ?? (groupDetails as any)?.items;
      if (Array.isArray(nested) && nested.length > 0) {
        setItems(nested as SingleAuctionItem[]);
        setLoading(false);
        return;
      }

      try {
        const res = await fetch(
          `/api/group-single-auctions?groupId=${encodeURIComponent(groupAuctionId)}&auction_group_id=${encodeURIComponent(auctionGroupId)}`,
          {
            credentials: "include",
            cache: "no-store",
            headers: {
              Accept: "application/json",
              "Accept-Language": locale || "ar",
            },
          },
        );
        const json = await res.json().catch(() => ({}));
        const parsed = parseSingleAuctionsResponse(json);
        if (parsed.length > 0) {
          setItems(parsed);
          setLoading(false);
          return;
        }
      } catch {
        // fallback
      }

      try {
        const headers: Record<string, string> = {
          Accept: "application/json",
          ...(session?.access_token
            ? { Authorization: `Bearer ${session.access_token}` }
            : {}),
        };
        const res = await fetch(
          `${API_BASE}/user/group-auctions/${groupAuctionId}/single-auctions?auction_group_id=${encodeURIComponent(auctionGroupId)}`,
          { method: "GET", headers, credentials: "omit", cache: "no-store" },
        );
        const json = await res.json().catch(() => ({}));
        setItems(parseSingleAuctionsResponse(json));
      } catch {
        setItems([]);
      } finally {
        setLoading(false);
      }
    };
    fetchItems();
  }, [
    groupAuctionId,
    auctionGroupId,
    session?.access_token,
    API_BASE,
    groupDetails,
  ]);

  const serverPaddleNorm = normalizePaddleLabel(
    (groupDetails as any)?.paddle_number,
  );
  useEffect(() => {
    if (serverPaddleNorm) setOfferSubmittedPaddle(null);
  }, [serverPaddleNorm]);

  useEffect(() => {
    if (serverOfferSubmittedChip) setOfferSent(false);
  }, [serverOfferSubmittedChip]);

  const handleViewSingleAuction = (item: SingleAuctionItem) => {
    const id = item?.id ?? "";
    if (!id) return;
    window.open(
      `/${lang}/annual-item/${String(id)}`,
      "_blank",
      "noopener,noreferrer",
    );
  };

  const resolveStatus = (raw: string | null | undefined) => {
    const trimmed = (raw || "").toString().trim();
    if (!trimmed) return { key: "", label: "" };
    const key = trimmed.toLowerCase();
    if (key === "skipped" || trimmed === "تم التخطي")
      return { key: "skipped", label: tStatus("status.skipped") };
    if (isUnsoldStatusString(trimmed))
      return { key: "unsold", label: tStatus("status.unsold") };
    if (
      key === "sold" ||
      trimmed === "مباع" ||
      trimmed === "تم البيع" ||
      key === "مباع"
    )
      return { key: "sold", label: tStatus("status.sold") };
    if (key === "withdrawn" || trimmed === "منسحب" || trimmed === "مسحوب")
      return { key: "withdrawn", label: tStatus("status.withdrawn") };
    if (key === "accepted")
      return { key: "accepted", label: tStatus("status.accepted") };
    if (key === "pending" || key === "pendind")
      return { key: "pending", label: tStatus("status.pending") };
    if (key === "live") return { key: "live", label: tStatus("status.live") };
    return { key, label: raw || key || "—" };
  };

  const statusBadgeClass = (key: string) => {
    const map: Record<string, string> = {
      sold: "bg-emerald-500 text-white",
      accepted: "bg-emerald-500 text-white",
      live: "bg-emerald-500 text-white",
      pending: "bg-amber-500 text-white",
      upcoming: "bg-amber-500 text-white",
      unsold: "bg-red-500 text-white",
      skipped: "bg-violet-600 text-white",
      withdrawn: "bg-sky-600 text-white",
      pulled: "bg-sky-600 text-white",
    };
    return map[key] || "bg-slate-200 text-slate-800";
  };

  const groupName = getLocalizedText(groupDetails?.name ?? "");
  const groupNumberDisplay =
    (groupDetails as any)?.unique_id ??
    (groupDetails?.day_order != null ? `G-${groupDetails.day_order}` : "—");
  const camelCount = groupDetails?.single_auctions_count ?? items.length ?? "—";
  const groupStatus = resolveStatus(groupDetails?.status);
  const isSold = groupStatus.key === "sold";
  const isSkipped = groupStatus.key === "skipped";
  const isUnsold = groupStatus.key === "unsold";

  const winnerName =
    (groupDetails as any)?.winner_user?.name ??
    (groupDetails as any)?.winner_name ??
    (groupDetails as any)?.winner?.name ??
    (groupDetails as any)?.highest_bidder?.name ??
    (groupDetails as any)?.highest_bidder_name ??
    null;

  const lowestOfferForUnsold = (groupDetails as any)?.info_final_bid
    ?.lowest_offer_value;
  const lastPriceRaw =
    isUnsold &&
      !isSkipped &&
      lowestOfferForUnsold != null &&
      String(lowestOfferForUnsold).trim() !== ""
      ? lowestOfferForUnsold
      : ((groupDetails as any)?.winning_bid?.amount ??
        (groupDetails as any)?.highest_bid?.amount ??
        (groupDetails as any)?.last_price ??
        (groupDetails as any)?.current_bid ??
        (groupDetails as any)?.highest_bid ??
        (groupDetails as any)?.starting_price ??
        (groupDetails as any)?.market_entry_price ??
        null);
  const lastPriceNum = Number(lastPriceRaw);
  const lastPriceDisplay =
    lastPriceRaw != null &&
      String(lastPriceRaw).trim() !== "" &&
      Number.isFinite(lastPriceNum) &&
      lastPriceNum > 0
      ? lastPriceNum
      : null;

  const ownerName =
    (groupDetails as any)?.owner_name ??
    (groupDetails as any)?.owner?.name ??
    "—";

  const purchaseDateLocale = isRtl ? "ar-SA-u-nu-latn" : "en-GB";

  const purchaseDate = (() => {
    const raw =
      (groupDetails as AuctionGroupDetails | null)?.purchasing_date ??
      (groupDetails as any)?.sold_at ??
      (groupDetails as any)?.updated_at ??
      null;
    if (raw == null || String(raw).trim() === "") return "—";
    const s = String(raw).trim();
    const ymd = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
    if (ymd) {
      const y = Number(ymd[1]);
      const mo = Number(ymd[2]) - 1;
      const day = Number(ymd[3]);
      const d = new Date(y, mo, day);
      if (!Number.isNaN(d.getTime())) {
        return d.toLocaleDateString(purchaseDateLocale, {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
        });
      }
    }
    try {
      const d = new Date(s);
      if (Number.isNaN(d.getTime())) return "—";
      return d.toLocaleDateString(purchaseDateLocale, {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
      });
    } catch {
      return "—";
    }
  })();

  const BackArrow = isRtl ? ArrowRight : ArrowLeft;

  return (
    <div className="bg-[#f7f6f2] min-h-screen" dir={isRtl ? "rtl" : "ltr"}>
      <div className="max-w-6xl mx-auto px-4 sm:px-6 py-6 space-y-8">
        <button
          type="button"
          onClick={() => router.back()}
          className="inline-flex items-center gap-2 text-sm text-slate-600 hover:text-slate-900 transition-colors cursor-pointer"
        >
          <BackArrow size={16} />
          {t("back")}
        </button>

        {/* Group Info Card - camel_group_sold_banner_fixed.html design */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
          className="bg-white rounded-lg border border-[#ececec] shadow-[0_10px_28px_rgba(0,0,0,0.06)] overflow-visible"
        >
          <div className="px-[18px] pt-4 pb-3 flex flex-wrap items-center gap-3 w-full">
            <h3 className="text-lg font-extrabold text-slate-900 shrink-0">
              {t("group_info")}
            </h3>

            <div className="flex flex-1 min-w-[min(100%,280px)] justify-center items-center gap-2 sm:gap-2.5 flex-wrap">
              {isUnsold && !isSkipped && !isGroupOwner ? (
                <>
                  {!session && !showOfferSubmittedUI ? (
                    <div className="inline-flex items-center gap-2 flex-wrap justify-center">
                      <button
                        type="button"
                        onClick={() => setLoginModal(true)}
                        className="inline-flex items-center gap-1.5 px-4 py-2 rounded-full text-xs sm:text-sm font-extrabold whitespace-nowrap border-2 border-[#0F5132] bg-white text-[#0F5132] hover:bg-emerald-50 transition-colors cursor-pointer shadow-sm"
                      >
                        <Send size={14} />
                        {isRtl ? "تقديم عرض" : "Send Offer"}
                      </button>
                      {hasGroupPaddle ? (
                        <span className="text-xs sm:text-sm font-bold text-slate-600 whitespace-nowrap">
                          {isRtl
                            ? `رقم مضربك هو : ${normalizePaddleLabel((groupDetails as any)?.paddle_number)}`
                            : `Your paddle number: ${normalizePaddleLabel((groupDetails as any)?.paddle_number)}`}
                        </span>
                      ) : null}
                    </div>
                  ) : null}
                  {session && !showOfferSubmittedUI && canBuyPaddleEffective ? (
                    <button
                      type="button"
                      onClick={() => setPaddleModalOpen(true)}
                      className="inline-flex items-center gap-1.5 px-4 py-2 rounded-full text-xs sm:text-sm font-extrabold whitespace-nowrap bg-blue-600 text-white hover:bg-blue-700 transition-colors cursor-pointer shadow-sm"
                    >
                      {isRtl ? "شراء مضرب" : "Buy Paddle"}
                    </button>
                  ) : null}
                  {session &&
                    !showOfferSubmittedUI &&
                    !canBuyPaddleEffective ? (
                    <div className="inline-flex items-center gap-2 flex-wrap justify-center">
                      <button
                        type="button"
                        onClick={() => setOfferModalOpen(true)}
                        className="inline-flex items-center gap-1.5 px-4 py-2 rounded-full text-xs sm:text-sm font-extrabold whitespace-nowrap border-2 border-[#0F5132] bg-white text-[#0F5132] hover:bg-emerald-50 transition-colors cursor-pointer shadow-sm"
                      >
                        <Send size={14} />
                        {isRtl ? "تقديم عرض" : "Send Offer"}
                      </button>
                      {hasGroupPaddle ? (
                        <span className="text-xs sm:text-sm font-bold text-slate-600 whitespace-nowrap">
                          {isRtl
                            ? `رقم مضربك هو : ${normalizePaddleLabel((groupDetails as any)?.paddle_number)}`
                            : `Your paddle number: ${normalizePaddleLabel((groupDetails as any)?.paddle_number)}`}
                        </span>
                      ) : null}
                    </div>
                  ) : null}
                  {showOfferSubmittedUI ? (
                    <>
                      <span
                        className="inline-flex items-center rounded-full whitespace-nowrap border border-blue-200 bg-blue-100 px-2.5 py-1.5 text-[11px] sm:text-xs font-bold text-blue-700"
                        role="status"
                      >
                        {isRtl
                          ? `تم تقديم عرض، رقم مضربك هو ${paddleLabelForSubmittedOffer || "—"}`
                          : `Offer submitted. Your paddle number is ${paddleLabelForSubmittedOffer || "—"}`}
                      </span>
                      <a
                        href={`/${lang}/dashboard?tab=purchase-offers-buyer&auction_id=${auctionGroupId}&animal_type=${animalType}`}
                        className="inline-flex items-center gap-1.5 px-4 py-2 rounded-full text-xs sm:text-sm font-extrabold whitespace-nowrap bg-slate-700 text-white hover:bg-slate-800 transition-colors cursor-pointer"
                      >
                        <ExternalLink size={14} />
                        {isRtl ? "عرض العروض السابقة" : "View Previous Offers"}
                      </a>
                    </>
                  ) : null}
                </>
              ) : null}
            </div>

            <div className="flex items-center gap-2 sm:gap-2.5 flex-wrap shrink-0 ms-auto">
              <span
                className={`inline-flex items-center gap-2 px-3 py-2 rounded-full text-xs font-extrabold whitespace-nowrap ${isSold
                    ? "bg-[rgba(22,138,58,0.1)] border border-[rgba(22,138,58,0.18)] text-[#0f7a31]"
                    : isSkipped
                      ? "bg-violet-100 border border-violet-200 text-violet-900"
                      : isUnsold
                        ? "bg-orange-100 border border-orange-200 text-orange-800"
                        : "bg-slate-100 border border-slate-200 text-slate-700"
                  }`}
              >
                {isSold && <CheckCircle2 size={14} />}
                {groupStatus.label}
              </span>

              {isSold ? (
                <span
                  className="inline-flex items-center justify-center px-4 py-2 sm:px-5 sm:py-2.5 rounded-full text-sm sm:text-base font-extrabold whitespace-nowrap bg-gradient-to-br from-[#168a3a] to-[#0f5132] text-white shadow-[0_8px_24px_rgba(15,81,50,0.28)] border border-white/20 ring-2 ring-[#168a3a]/25"
                  role="status"
                >
                  {t("congrats_buyer")}
                </span>
              ) : null}
            </div>
          </div>

          <div className="h-px bg-[#ececec] mx-[18px]" />

          <div className="p-4 lg:p-5 pb-5">
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2.5">
              <GroupCell
                label={t("group_number")}
                value={String(groupNumberDisplay)}
                mono
              />
              <GroupCell label={t("group_name")} value={groupName || "—"} />
              <GroupCell
                label={t("camel_count")}
                value={String(camelCount)}
                mono
              />
              {isSold ? (
                <GroupCell
                  label={t("buyer_name")}
                  value={winnerName || "—"}
                  cellClassName="min-h-[76px] sm:min-h-[92px] py-3 sm:py-3.5"
                  valueClassName="!text-2xl sm:!text-3xl text-[#0f5132] leading-snug break-words"
                />
              ) : (
                <GroupCell
                  label={t("last_price")}
                  value={
                    lastPriceDisplay != null ? (
                      <span className="inline-flex items-end gap-1.5">
                        <span>
                          {lastPriceDisplay.toLocaleString(
                            isRtl ? "ar-SA-u-nu-latn" : "en-US",
                          )}
                        </span>
                        <RiyalIcon
                          className="w-6 h-6 sm:w-7 sm:h-7 mb-0.5 shrink-0 opacity-90"
                          aria-hidden
                        />
                      </span>
                    ) : (
                      "—"
                    )
                  }
                  cellClassName="min-h-[76px] sm:min-h-[92px] py-3 sm:py-3.5"
                  valueClassName="!text-2xl sm:!text-3xl text-[#0f5132] leading-snug"
                />
              )}
              <GroupCell label={t("seller_name")} value={ownerName} />
              <GroupCell label={t("sale_status")} value={groupStatus.label} />
              <GroupCell label={t("purchase_date")} value={purchaseDate} mono />
            </div>
          </div>
        </motion.div>

        {/* Camels in Group Table */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.15 }}
          className="bg-white rounded-2xl shadow-md border border-slate-100 overflow-hidden"
        >
          <div className="px-6 py-4 border-b border-slate-100">
            <h3 className="text-lg font-extrabold text-slate-900">
              {t("camels_in_group")}
            </h3>
          </div>

          {loading ? (
            <div className="py-12 text-center text-sm text-slate-500">
              {tStatus("loading")}
            </div>
          ) : items.length === 0 ? (
            <div className="py-12 text-center text-sm text-slate-500">
              {tStatus("room_items_empty")}
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm min-w-[800px]">
                <thead>
                  <tr className="bg-slate-50 text-xs text-slate-500">
                    <th className="p-3 text-center font-semibold border-b border-slate-100 w-14">
                      {t("th_number")}
                    </th>
                    <th className="p-3 text-start font-semibold border-b border-slate-100">
                      {t("th_name")}
                    </th>
                    <th className="p-3 text-center font-semibold border-b border-slate-100 w-24">
                      {t("th_category")}
                    </th>
                    <th className="p-3 text-center font-semibold border-b border-slate-100 w-28">
                      {t("th_winner")}
                    </th>
                    <th className="p-3 text-center font-semibold border-b border-slate-100 w-24">
                      {tStatus("th_status")}
                    </th>
                    <th className="p-3 text-center font-semibold border-b border-slate-100 w-32">
                      {tStatus("th_view_details")}
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {items.map((item, idx) => {
                    const animal = getAnimalFromItem(item);
                    const imgUrl =
                      item?.main_image?.url ||
                      item?.media_files?.main_image?.url ||
                      item?.main_image_url ||
                      "/logo.png";
                    const animalName =
                      (animal?.name || "").toString().trim() ||
                      (item?.horse_name || "").toString().trim() ||
                      (item?.unique_id || "").toString().trim() ||
                      (item?.title || "").toString().trim() ||
                      "—";
                    const fatherName = animal?.father_name;
                    const motherName = animal?.mother_name;
                    const breed = animal?.breed;
                    const dob = animal?.date_of_birth;
                    const category = getUsageFromItem(
                      item,
                      locale || "ar",
                      getLocalizedText,
                    );
                    const itemStatus = resolveStatus(item?.status);
                    const isWithdrawnOrUnsold = [
                      "withdrawn",
                      "unsold",
                      "pulled",
                      "skipped",
                    ].includes(itemStatus.key);

                    const displayWinner = !isWithdrawnOrUnsold
                      ? (winnerName ??
                        (item as any)?.winner_user?.name ??
                        (item as any)?.winner_name ??
                        null)
                      : null;

                    return (
                      <tr
                        key={String(item.id ?? idx)}
                        className="hover:bg-slate-50/50 transition-colors"
                      >
                        <td className="p-3 text-center font-extrabold text-slate-900">
                          {idx + 1}
                        </td>
                        <td className="p-3">
                          <div className="flex items-center gap-3">
                            <div className="w-14 h-14 rounded-full overflow-hidden bg-slate-100 shrink-0 flex items-center justify-center">
                              <img
                                src={imgUrl}
                                alt={animalName}
                                className="w-full h-full object-cover"
                              />
                            </div>
                            <div className="flex flex-col gap-0.5 min-w-0">
                              <div className="text-sm font-extrabold text-slate-900">
                                {animalName}
                              </div>
                              {fatherName && (
                                <div className="text-[11px] text-slate-500">
                                  {t("father")}: {fatherName}
                                </div>
                              )}
                              {motherName && (
                                <div className="text-[11px] text-slate-500">
                                  {t("mother")}: {motherName}
                                </div>
                              )}
                              {breed && (
                                <div className="text-[11px] text-slate-500">
                                  {t("th_breed")}: {breed}
                                </div>
                              )}
                              {dob && (
                                <div className="text-[11px] text-slate-500">
                                  {t("birth_date")}: {dob}
                                </div>
                              )}
                            </div>
                          </div>
                        </td>
                        <td className="p-3 text-center text-sm">
                          {category ? (
                            <span className="font-bold text-slate-900">
                              {typeof category === "string" &&
                                (category.startsWith("{") ||
                                  category.startsWith("["))
                                ? getLocalizedText(category)
                                : String(category)}
                            </span>
                          ) : (
                            "—"
                          )}
                        </td>
                        <td className="p-3 text-center text-sm text-slate-700">
                          {displayWinner ?? "—"}
                        </td>
                        <td className="p-3 text-center">
                          <span
                            className={`inline-flex items-center whitespace-nowrap px-2 py-1 rounded-full text-xs font-bold ${statusBadgeClass(itemStatus.key)}`}
                          >
                            {itemStatus.label}
                          </span>
                        </td>
                        <td className="p-3 text-center">
                          <button
                            type="button"
                            className="px-3 py-1.5 rounded-full text-xs font-semibold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors cursor-pointer"
                            onClick={() => handleViewSingleAuction(item)}
                          >
                            {tStatus("button_view")}
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </motion.div>
      </div>

      {/* Paddle Purchase Modal – normal only (for auction_group) */}
      <YearlyPaddleModal
        open={paddleModalOpen}
        onClose={() => setPaddleModalOpen(false)}
        groupAuctionId={groupAuctionId}
        yearlyAuctionId={isHorseFallbackGroup ? groupAuctionId : auctionGroupId}
        yearlyAuctionType={isHorseFallbackGroup ? "group" : "single"}
        prices={auctionPrices}
        availablePaddles={availablePaddles}
        prefetchedAuctionTerms={getPrefetchedGroupAuctionTerms(auction)}
        normalOnly
        onJoined={() => {
          setPaddleModalOpen(false);
          setPaddleJustPurchased(true);
          router.refresh();
          if (session) {
            setOfferModalOpen(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 and it will be submitted for review after validating the minimum required amount."
        }
        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}
      />
    </div>
  );
}

function GroupCell({
  label,
  value,
  mono,
  valueClassName,
  cellClassName,
}: {
  label: string;
  value: React.ReactNode;
  mono?: boolean;
  valueClassName?: string;
  cellClassName?: string;
}) {
  return (
    <div
      className={`bg-[#f6f6f6] border  rounded-md border-black/5  p-2.5 sm:p-3 min-h-[54px] flex flex-col justify-center gap-1 min-w-0 ${cellClassName ?? ""}`}
    >
      <span className="text-slate-500 font-extrabold text-xs whitespace-nowrap">
        {label}
      </span>
      <div
        className={`font-extrabold text-xl text-slate-900 min-w-0 flex items-center gap-1 ${mono ? "font-mono justify-end tracking-wide" : ""
          } ${valueClassName ?? ""}`}
      >
        {value}
      </div>
    </div>
  );
}
