"use client";
import { useState, useRef, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import dynamic from "next/dynamic";
import { motion, AnimatePresence } from "framer-motion";
import toast from "react-hot-toast";
import {
  ChevronLeft,
  MapPin,
  Eye,
  Heart,
  Share2,
  MessageCircle,
  Flag,
  Star,
  Clock,
  ChevronRight,
  ChevronLeft as ChevLeft,
  X,
  ZoomIn,
  BadgeCheck,
} from "lucide-react";
import {
  CONDITION_LABELS,
  timeAgo,
} from "@/components/marketplace/buyer/mockData";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import { WishlistButton } from "@/components/marketplace/buyer/WishlistButton";
import { ShareModal } from "@/components/marketplace/buyer/ShareModal";
import {
  BuyNowModal,
  type BuyNowListing,
} from "@/components/marketplace/buyer/BuyNowModal";
import { useWishlist } from "@/lib/WishlistContext";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import Cookies from "js-cookie";
import { useMessaging } from "@/lib/MessagingContext";

const MarketplaceMap = dynamic(
  () =>
    import("@/components/marketplace/buyer/MarketplaceMap").then((m) => ({
      default: m.MarketplaceMap,
    })),
  {
    ssr: false,
    loading: () => (
      <div
        className="rounded-2xl animate-pulse"
        style={{ height: 248, background: "var(--deep)" }}
      />
    ),
  },
);
import {
  fetchListingDetail,
  clearListingDetail,
} from "@/store/slices/marketplaceListingDetailSlice";
import { mapApiDetailToListing, mapApiToListing } from "@/utils/marketplace";
import apiClient from "@/lib/axiosClient";
import { API_ENDPOINTS } from "@/lib/apiEndpoints";

/* ─── Image gallery ─────────────────────────────────────────────────────── */
function Gallery({
  images,
  title,
  isSold,
}: {
  images: string[];
  title: string;
  isSold: boolean;
}) {
  const [current, setCurrent] = useState(0);
  const [fullscreen, setFullscreen] = useState(false);
  const touchStartX = useRef(0);

  const prev = () => setCurrent((c) => (c === 0 ? images.length - 1 : c - 1));
  const next = () => setCurrent((c) => (c === images.length - 1 ? 0 : c + 1));

  const handleTouchStart = (e: React.TouchEvent) => {
    touchStartX.current = e.touches[0].clientX;
  };
  const handleTouchEnd = (e: React.TouchEvent) => {
    const diff = touchStartX.current - e.changedTouches[0].clientX;
    if (diff > 50) next();
    else if (diff < -50) prev();
  };

  return (
    <>
      <div
        className="relative bg-[var(--deep)] overflow-hidden"
        style={{ aspectRatio: "4/3" }}
        onTouchStart={handleTouchStart}
        onTouchEnd={handleTouchEnd}
      >
        <AnimatePresence mode="wait">
          <motion.img
            key={current}
            src={images[current]}
            alt={`${title} ${current + 1}`}
            className="w-full h-full object-cover"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
          />
        </AnimatePresence>

        <div className="absolute top-3 right-3 px-2 py-1 rounded-full text-[11px] font-bold text-white bg-black/50 backdrop-blur-sm">
          {current + 1} / {images.length}
        </div>

        {isSold && (
          <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
            <div
              className="px-6 py-2 rounded-full text-white font-black text-lg tracking-widest uppercase shadow-2xl"
              style={{
                background: "rgba(239,68,68,0.92)",
                letterSpacing: "0.15em",
              }}
            >
              SOLD OUT
            </div>
          </div>
        )}

        <button
          onClick={() => setFullscreen(true)}
          className="absolute bottom-3 right-3 w-9 h-9 rounded-full bg-black/50 backdrop-blur-sm flex items-center justify-center"
        >
          <ZoomIn size={16} className="text-white" />
        </button>

        {images.length > 1 && (
          <>
            <button
              onClick={prev}
              className="absolute left-2 top-1/2 -translate-y-1/2 hidden sm:flex w-9 h-9 rounded-full bg-black/50 backdrop-blur-sm items-center justify-center"
            >
              <ChevLeft size={18} className="text-white" />
            </button>
            <button
              onClick={next}
              className="absolute right-2 top-1/2 -translate-y-1/2 hidden sm:flex w-9 h-9 rounded-full bg-black/50 backdrop-blur-sm items-center justify-center"
            >
              <ChevronRight size={18} className="text-white" />
            </button>
          </>
        )}
      </div>

      {images.length > 1 && (
        <div className="flex gap-2 px-4 py-2 overflow-x-auto no-scrollbar">
          {images.map((img, i) => (
            <button
              key={i}
              onClick={() => setCurrent(i)}
              className="shrink-0 w-14 h-14 rounded-lg overflow-hidden border-2 transition-all"
              style={{
                borderColor: i === current ? "var(--accent)" : "transparent",
                opacity: i === current ? 1 : 0.6,
              }}
            >
              <img src={img} alt="" className="w-full h-full object-cover" />
            </button>
          ))}
        </div>
      )}

      <AnimatePresence>
        {fullscreen && (
          <motion.div
            className="fixed inset-0 z-[300] flex items-center justify-center bg-black"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
          >
            <button
              onClick={() => setFullscreen(false)}
              className="absolute top-4 right-4 z-10 w-10 h-10 rounded-full bg-white/10 flex items-center justify-center"
            >
              <X size={20} className="text-white" />
            </button>
            <div
              className="text-white text-sm absolute top-4 left-1/2 -translate-x-1/2"
              style={{ color: "rgba(255,255,255,0.7)" }}
            >
              {current + 1} / {images.length}
            </div>
            <img
              src={images[current]}
              alt=""
              className="max-w-full max-h-full object-contain"
            />
            {images.length > 1 && (
              <>
                <button
                  onClick={prev}
                  className="absolute left-4 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white/10 flex items-center justify-center"
                >
                  <ChevLeft size={20} className="text-white" />
                </button>
                <button
                  onClick={next}
                  className="absolute right-4 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white/10 flex items-center justify-center"
                >
                  <ChevronRight size={20} className="text-white" />
                </button>
              </>
            )}
          </motion.div>
        )}
      </AnimatePresence>

      <style>{`
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
      `}</style>
    </>
  );
}

/* ─── Seller card ─────────────────────────────────────────────────────────── */
type ListingType = ReturnType<typeof mapApiDetailToListing>;
function SellerCard({
  listing,
  onChat,
  onBuyNow,
  isSeller,
  isSold,
  chatLoading,
}: {
  listing: ListingType;
  onChat: () => void;
  onBuyNow: () => void;
  isSeller: boolean;
  isSold: boolean;
  chatLoading: boolean;
}) {
  return (
    <div
      className="rounded-2xl border p-4"
      style={{ background: "var(--card)", borderColor: "var(--border)" }}
    >
      <h3
        className="text-xs font-bold uppercase tracking-wider mb-3"
        style={{ color: "var(--text-muted)" }}
      >
        Seller Information
      </h3>
      <div className="flex items-center gap-3 mb-4">
        <div className="relative">
          <img
            src={listing.sellerAvatar}
            alt={listing.sellerName}
            className="w-12 h-12 rounded-full object-cover"
          />
          {listing.sellerVerified && (
            <div
              className="absolute -bottom-1 -right-1 w-5 h-5 rounded-full flex items-center justify-center"
              style={{ background: "#3b82f6" }}
            >
              <BadgeCheck size={12} className="text-white" />
            </div>
          )}
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-1.5">
            <p
              className="text-sm font-bold truncate"
              style={{ color: "var(--text-primary)" }}
            >
              {listing.sellerName}
            </p>
          </div>
          <p className="text-xs" style={{ color: "var(--text-muted)" }}>
            Joined{" "}
            {new Date(listing.sellerJoinedDate).toLocaleDateString("en-IN", {
              month: "short",
              year: "numeric",
            })}
          </p>
        </div>
      </div>

      <div className="grid grid-cols-3 gap-3 mb-4">
        {[
          { label: "Views", value: listing.views },
          { label: "Saved", value: listing.savedCount },
          {
            label: "Rating",
            value: (
              <span className="flex items-center gap-0.5">
                <Star size={10} className="fill-[#f0c040] text-[#f0c040]" />
                4.8
              </span>
            ),
          },
        ].map((stat) => (
          <div
            key={stat.label}
            className="rounded-xl p-2 text-center"
            style={{ background: "var(--deep)" }}
          >
            <p
              className="text-base font-black"
              style={{ color: "var(--text-primary)" }}
            >
              {stat.value}
            </p>
            <p className="text-[10px]" style={{ color: "var(--text-muted)" }}>
              {stat.label}
            </p>
          </div>
        ))}
      </div>

      <div className="flex gap-2">
        {isSold ? (
          <div
            className="flex-1 flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-sm font-bold"
            style={{ background: "rgba(239,68,68,0.12)", color: "#ef4444" }}
          >
            Item Sold Out
          </div>
        ) : !isSeller ? (
          <>
            <motion.button
              whileTap={{ scale: 0.97 }}
              onClick={onChat}
              disabled={chatLoading}
              className="flex-1 flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-sm font-bold text-white disabled:opacity-70"
              style={{ background: "var(--accent)" }}
            >
              <MessageCircle size={15} />
              {chatLoading ? "Opening…" : "Chat"}
            </motion.button>
            {listing.condition === "new" && (
              <motion.button
                whileTap={{ scale: 0.97 }}
                onClick={onBuyNow}
                className="flex-1 flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-sm font-bold border"
                style={{
                  background: "var(--deep)",
                  borderColor: "var(--border)",
                  color: "var(--text-primary)",
                }}
              >
                Buy It Now
              </motion.button>
            )}
          </>
        ) : null}
      </div>
    </div>
  );
}

/* ─── Loading skeleton ─────────────────────────────────────────────────── */
function ListingDetailSkeleton() {
  return (
    <div
      className="min-h-full pb-32 md:pb-8 animate-pulse"
      style={{ background: "var(--bg)" }}
    >
      <div className="px-4 pt-4 pb-2">
        <div
          className="h-5 w-14 rounded-full"
          style={{ background: "var(--deep)" }}
        />
      </div>
      <div className="max-w-5xl mx-auto px-0 sm:px-4">
        <div className="lg:grid lg:grid-cols-[1fr_340px] lg:gap-6">
          <div>
            <div
              className="aspect-[4/3]"
              style={{ background: "var(--deep)" }}
            />
            <div className="px-4 mt-4 space-y-3">
              <div
                className="h-8 w-40 rounded-xl"
                style={{ background: "var(--deep)" }}
              />
              <div
                className="h-6 w-3/4 rounded-xl"
                style={{ background: "var(--deep)" }}
              />
              <div
                className="h-4 w-full rounded"
                style={{ background: "var(--deep)" }}
              />
              <div
                className="h-4 w-5/6 rounded"
                style={{ background: "var(--deep)" }}
              />
              <div
                className="h-4 w-4/6 rounded"
                style={{ background: "var(--deep)" }}
              />
            </div>
          </div>
          <div className="hidden lg:flex flex-col gap-4 pt-0">
            <div
              className="h-40 rounded-2xl"
              style={{ background: "var(--deep)" }}
            />
            <div
              className="h-32 rounded-2xl"
              style={{ background: "var(--deep)" }}
            />
          </div>
        </div>
      </div>
    </div>
  );
}

/* ─── Price block ──────────────────────────────────────────────────────────── */
function PriceBlock({
  listing,
  discount,
  isSold,
}: {
  listing: ListingType;
  discount: number;
  isSold: boolean;
}) {
  const formatPrice = useFormatPrice();
  return (
    <div
      className="rounded-2xl border p-4"
      style={{ background: "var(--card)", borderColor: "var(--border)" }}
    >
      {isSold && (
        <div
          className="flex items-center gap-1.5 text-xs font-bold px-3 py-1.5 rounded-xl mb-3 w-fit"
          style={{ background: "rgba(239,68,68,0.15)", color: "#ef4444" }}
        >
          <span className="w-2 h-2 rounded-full bg-red-500 inline-block" />
          SOLD OUT — This item is no longer available
        </div>
      )}
      <div className="flex items-start gap-3 mb-3">
        <div className="flex-1">
          <div className="flex items-baseline gap-2 flex-wrap">
            <span
              className="text-3xl font-black"
              style={{
                color: isSold ? "var(--text-muted)" : "var(--accent)",
                textDecoration: isSold ? "line-through" : "none",
                opacity: isSold ? 0.5 : 1,
              }}
            >
              {formatPrice(listing.price)}
            </span>
            {listing.originalPrice && (
              <span
                className="text-base line-through"
                style={{ color: "var(--text-muted)" }}
              >
                {formatPrice(listing.originalPrice)}
              </span>
            )}
          </div>
          {discount > 0 && (
            <span
              className="inline-block text-xs font-bold px-2 py-0.5 rounded-full mt-1"
              style={{ background: "rgba(34,197,94,0.15)", color: "#22c55e" }}
            >
              {discount}% off
            </span>
          )}
        </div>
        {listing.isNegotiable && (
          <span
            className="text-xs font-bold px-2.5 py-1 rounded-full shrink-0"
            style={{
              background: "rgba(240,192,64,0.15)",
              color: "var(--accent-gold)",
            }}
          >
            Negotiable
          </span>
        )}
      </div>

      <h1
        className="text-base font-black leading-snug mb-3"
        style={{ color: "var(--text-primary)" }}
      >
        {listing.title}
      </h1>

      <div className="flex flex-wrap gap-2 mb-3">
        <span
          className="flex items-center gap-1 text-xs font-semibold px-2.5 py-1 rounded-full"
          style={{ background: "var(--deep)", color: "var(--text-muted)" }}
        >
          🏷️ {CONDITION_LABELS[listing.condition] ?? listing.condition}
        </span>
        <span
          className="flex items-center gap-1 text-xs font-semibold px-2.5 py-1 rounded-full"
          style={{ background: "var(--deep)", color: "var(--text-muted)" }}
        >
          📁 {listing.subCategory}
        </span>
      </div>

      <div
        className="flex items-center gap-4 text-xs border-t pt-3"
        style={{ borderColor: "var(--border)", color: "var(--text-muted)" }}
      >
        <span className="flex items-center gap-1">
          <Eye size={12} />
          {listing.views} views
        </span>
        <span className="flex items-center gap-1">
          <Heart size={12} />
          {listing.savedCount} saved
        </span>
        <span className="flex items-center gap-1">
          <Clock size={12} />
          {timeAgo(listing.postedAt)}
        </span>
      </div>

      <div
        className="flex items-center gap-1.5 text-xs mt-2"
        style={{ color: "var(--text-muted)" }}
      >
        <MapPin size={12} style={{ color: "var(--accent)" }} />
        {listing.area}, {listing.city}
        {listing.pincode ? ` — ${listing.pincode}` : ""}
      </div>
    </div>
  );
}

/* ─── Action buttons (desktop sidebar) ──────────────────────────────────── */
function ActionButtons({
  listing,
  onShare,
  onChat,
  onBuyNow,
  isSeller,
  isSold,
  chatLoading,
}: {
  listing: ListingType;
  onShare: () => void;
  onChat: () => void;
  onBuyNow: () => void;
  isSeller: boolean;
  isSold: boolean;
  chatLoading: boolean;
}) {
  const { has, toggle } = useWishlist();

  return (
    <div className="flex flex-col gap-2">
      {isSold ? (
        <div
          className="w-full flex items-center justify-center gap-2 py-3.5 rounded-xl font-bold text-sm"
          style={{ background: "rgba(239,68,68,0.12)", color: "#ef4444" }}
        >
          Item Sold Out
        </div>
      ) : !isSeller ? (
        <div className={`grid gap-2 ${listing.condition === "new" ? "grid-cols-2" : "grid-cols-1"}`}>
          {listing.condition === "new" && (
            <motion.button
              onClick={onBuyNow}
              whileTap={{ scale: 0.97 }}
              className="flex items-center justify-center gap-2 py-3.5 rounded-xl font-bold text-sm border"
              style={{
                background: "var(--card)",
                borderColor: "var(--border)",
                color: "var(--text-primary)",
              }}
            >
              Buy It Now
            </motion.button>
          )}
          <motion.button
            onClick={onChat}
            disabled={chatLoading}
            whileTap={{ scale: 0.97 }}
            className="flex items-center justify-center gap-2 py-3.5 rounded-xl font-bold text-sm text-white disabled:opacity-70"
            style={{ background: "var(--accent)" }}
          >
            <MessageCircle size={16} />
            {chatLoading ? "Opening…" : "Contact Seller"}
          </motion.button>
        </div>
      ) : null}
      <div className="grid grid-cols-2 gap-2">
        <div
          className="flex items-center justify-center gap-1.5 py-3 rounded-xl border text-sm font-bold cursor-pointer"
          onClick={() => toggle(listing.id)}
          style={{
            background: has(listing.id) ? "rgba(252,0,0,0.1)" : "var(--card)",
            borderColor: has(listing.id) ? "var(--accent)" : "var(--border)",
          }}
        >
          <WishlistButton listingId={listing.id} size={16} />
          <span
            style={{
              color: has(listing.id) ? "var(--accent)" : "var(--text-primary)",
            }}
          >
            {has(listing.id) ? "Saved" : "Save"}
          </span>
        </div>
        <button
          onClick={onShare}
          className="flex items-center justify-center gap-1.5 py-3 rounded-xl border text-sm font-bold"
          style={{
            background: "var(--card)",
            borderColor: "var(--border)",
            color: "var(--text-primary)",
          }}
        >
          <Share2 size={15} />
          Share
        </button>
      </div>
      <button
        className="w-full flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-xs"
        style={{ color: "var(--text-muted)" }}
      >
        <Flag size={12} />
        Report this listing
      </button>
    </div>
  );
}

/* ─── Page ─────────────────────────────────────────────────────────────── */
export default function ListingDetailPage() {
  const router = useRouter();
  const { slug } = useParams<{ slug: string }>();
  const dispatch = useAppDispatch();
  const [shareOpen, setShareOpen] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const [chatLoading, setChatLoading] = useState(false);
  const [buyNowListing, setBuyNowListing] = useState<BuyNowListing | null>(
    null,
  );
  const { has } = useWishlist();

  const { user, isAuthenticated } = useAppSelector((s) => s.auth);
  const { startConversation } = useMessaging();
  const formatPrice = useFormatPrice();

  const {
    listing: apiListing,
    similar: apiSimilar,
    isLoading,
    error,
  } = useAppSelector((s) => s.marketplaceListingDetail);

  /* Extract numeric listing ID from slug (format: "title-words-{id}") */
  const listingId = (() => {
    const last = slug?.split("-").at(-1) ?? "";
    const n = parseInt(last, 10);
    return Number.isFinite(n) && !isNaN(n) ? n : NaN;
  })();

  useEffect(() => {
    if (isNaN(listingId)) return;
    dispatch(fetchListingDetail(listingId));
    /* Fire-and-forget: increment view count */
    apiClient
      .post(API_ENDPOINTS.CLASSIFIED.ADD_VIEW, { listing_id: listingId })
      .catch(() => { });
    return () => {
      dispatch(clearListingDetail());
    };
  }, [dispatch, listingId]);

  /* ── Loading state ── */
  if (isLoading || (!apiListing && !error && !isNaN(listingId))) {
    return <ListingDetailSkeleton />;
  }

  /* ── Error / not found ── */
  if (error || !apiListing || isNaN(listingId)) {
    return (
      <div
        className="min-h-full flex flex-col items-center justify-center py-20 text-center"
        style={{ background: "var(--bg)" }}
      >
        <div className="text-5xl mb-4">😕</div>
        <h2
          className="text-xl font-bold mb-2"
          style={{ color: "var(--text-primary)" }}
        >
          Listing not found
        </h2>
        <p className="text-sm mb-5" style={{ color: "var(--text-muted)" }}>
          This listing may have been removed or sold.
        </p>
        <button
          onClick={() => router.push("/marketplace")}
          className="px-5 py-2.5 rounded-full font-bold text-sm text-white"
          style={{ background: "var(--accent)" }}
        >
          Browse Marketplace
        </button>
      </div>
    );
  }

  const listing = mapApiDetailToListing(apiListing);
  const similar = apiSimilar.map(mapApiToListing);

  const myChannelId = user?.channel_id ?? Cookies.get("channel_id") ?? "";
  const isSeller = !!myChannelId && myChannelId === listing.sellerId;
  const isSold = listing.listingStatus === "sold";

  const handleChat = async () => {
    if (!isAuthenticated) {
      router.push("/auth/login");
      return;
    }
    if (isSeller || isSold) return;
    if (!listing.sellerFirebaseId) {
      toast.error("This seller is not available for chat right now.");
      return;
    }

    console.log("[handleChat] starting", {
      myChannelId,
      isAuthenticated,
      sellerId: listing.sellerId,
      sellerFirebaseId: listing.sellerFirebaseId,
      sellerName: listing.sellerName,
    });

    setChatLoading(true);
    try {
      const convId = await startConversation({
        sellerChannelId: listing.sellerId,
        sellerFirebaseId: listing.sellerFirebaseId,
        sellerName: listing.sellerName,
        sellerAvatar: listing.sellerAvatar,
        listingId: String(listing.id),
        listingTitle: listing.title,
        listingImage: listing.images[0] ?? "",
        listingPrice: listing.price,
      });
      console.log("[handleChat] startConversation returned convId:", convId);
      router.push(`/marketplace/messages${convId ? `?conv=${convId}` : ""}`);
    } catch (err) {
      console.error("[handleChat] startConversation threw:", err);
      router.push("/marketplace/messages");
    } finally {
      setChatLoading(false);
    }
  };

  const handleBuyNow = () => {
    if (!isAuthenticated) {
      router.push("/auth/login");
      return;
    }
    if (isSeller || isSold) return;
    setBuyNowListing({
      id: String(listing.id),
      title: listing.title,
      price: listing.price,
      image: listing.images[0] ?? "",
      listingSlug: slug,
      availableQuantity: listing.quantity ?? 1,
    });
  };

  const handleBuyNowSuccess = (orderId: number) => {
    setBuyNowListing(null);
    toast.success("Order placed successfully!");
    router.push(`/marketplace/orders/${orderId}`);
  };

  const handleBuyNowError = (message: string) => {
    setBuyNowListing(null);
    toast.error(
      message === "Payment cancelled"
        ? "Payment was cancelled."
        : "Payment failed. Please try again.",
    );
  };

  const pageUrl = `${typeof window !== "undefined" ? window.location.origin : ""}/marketplace/listing/${slug}`;
  const discount = listing.originalPrice
    ? Math.round((1 - listing.price / listing.originalPrice) * 100)
    : 0;
  const descLines = listing.description.split("\n");
  const shortDesc = descLines[0];
  const hasMore = descLines.length > 1 || listing.description.length > 200;

  return (
    <div
      className="min-h-full pb-32 md:pb-8"
      style={{ background: "var(--bg)" }}
    >
      {/* Back button */}
      <div className="px-4 pt-4 pb-2">
        <button
          onClick={() => router.back()}
          className="flex items-center gap-1 text-sm font-semibold"
          style={{ color: "var(--text-muted)" }}
        >
          <ChevronLeft size={18} />
          Back
        </button>
      </div>

      {/* Desktop: 2-column layout */}
      <div className="max-w-5xl mx-auto px-0 sm:px-4">
        <div className="lg:grid lg:grid-cols-[1fr_340px] lg:gap-6">
          {/* Left column */}
          <div>
            {/* Gallery */}
            <div className="lg:rounded-2xl overflow-hidden">
              <Gallery
                images={listing.images}
                title={listing.title}
                isSold={isSold}
              />
            </div>

            {/* Price + title (mobile) */}
            <div className="px-4 mt-4 lg:hidden">
              <PriceBlock
                listing={listing}
                discount={discount}
                isSold={isSold}
              />
            </div>

            {/* Description */}
            <div className="px-4 mt-5">
              <h3
                className="text-sm font-bold mb-2"
                style={{ color: "var(--text-primary)" }}
              >
                Description
              </h3>
              <div
                className="text-sm leading-relaxed"
                style={{ color: "var(--text-muted)" }}
              >
                {expanded ? (
                  <p className="whitespace-pre-line">{listing.description}</p>
                ) : (
                  <p>{shortDesc}</p>
                )}
                {hasMore && (
                  <button
                    onClick={() => setExpanded((p) => !p)}
                    className="text-xs font-bold mt-1"
                    style={{ color: "var(--accent)" }}
                  >
                    {expanded ? "Read less ↑" : "Read more ↓"}
                  </button>
                )}
              </div>
            </div>

            {/* Specs */}
            {listing.specs && Object.keys(listing.specs).length > 0 && (
              <div className="px-4 mt-5">
                <h3
                  className="text-sm font-bold mb-3"
                  style={{ color: "var(--text-primary)" }}
                >
                  Specifications
                </h3>
                <div className="grid grid-cols-2 gap-2">
                  {Object.entries(listing.specs).map(([key, val]) => (
                    <div
                      key={key}
                      className="rounded-xl p-3 border"
                      style={{
                        background: "var(--card)",
                        borderColor: "var(--border)",
                      }}
                    >
                      <p
                        className="text-[10px] font-bold uppercase tracking-wider mb-0.5"
                        style={{ color: "var(--text-muted)" }}
                      >
                        {key}
                      </p>
                      <p
                        className="text-sm font-semibold"
                        style={{ color: "var(--text-primary)" }}
                      >
                        {val}
                      </p>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Location */}
            <div className="px-4 mt-5">
              <h3
                className="text-sm font-bold mb-3"
                style={{ color: "var(--text-primary)" }}
              >
                Location
              </h3>
              <MarketplaceMap
                lat={parseFloat(apiListing.latitude)}
                lng={parseFloat(apiListing.longitude)}
                area={listing.area}
                city={listing.city}
                pincode={listing.pincode}
              />
            </div>

            {/* Seller card (mobile) */}
            <div className="px-4 mt-5 lg:hidden">
              <SellerCard
                listing={listing}
                onChat={handleChat}
                onBuyNow={handleBuyNow}
                isSeller={isSeller}
                isSold={isSold}
                chatLoading={chatLoading}
              />
            </div>
          </div>

          {/* Right column (desktop only) */}
          <div className="hidden lg:flex flex-col gap-4 pt-0">
            <PriceBlock listing={listing} discount={discount} isSold={isSold} />
            <ActionButtons
              listing={listing}
              onShare={() => setShareOpen(true)}
              onChat={handleChat}
              onBuyNow={handleBuyNow}
              isSeller={isSeller}
              isSold={isSold}
              chatLoading={chatLoading}
            />
            <SellerCard
              listing={listing}
              onChat={handleChat}
              onBuyNow={handleBuyNow}
              isSeller={isSeller}
              isSold={isSold}
              chatLoading={chatLoading}
            />
          </div>
        </div>

        {/* Similar listings */}
        {similar.length > 0 && (
          <div className="px-4 mt-8">
            <h3
              className="text-sm font-bold mb-3"
              style={{ color: "var(--text-primary)" }}
            >
              Similar Listings
            </h3>
            <div className="flex gap-3 overflow-x-auto pb-2 no-scrollbar">
              {similar.map((l) => (
                <motion.div
                  key={l.id}
                  whileHover={{ scale: 1.02 }}
                  onClick={() => router.push(`/marketplace/listing/${l.slug}`)}
                  className="shrink-0 w-40 rounded-xl overflow-hidden cursor-pointer border"
                  style={{
                    background: "var(--card)",
                    borderColor: "var(--border)",
                  }}
                >
                  <div className="relative h-28 bg-[var(--deep)]">
                    <img
                      src={l.images[0]}
                      alt={l.title}
                      className="w-full h-full object-cover"
                    />
                    <div className="absolute bottom-0 left-0 right-0 p-1.5 bg-gradient-to-t from-black/70 to-transparent">
                      <span className="text-white font-black text-xs">
                        {formatPrice(l.price)}
                      </span>
                    </div>
                  </div>
                  <div className="p-2">
                    <p
                      className="text-[11px] font-semibold line-clamp-2"
                      style={{ color: "var(--text-primary)" }}
                    >
                      {l.title}
                    </p>
                    <p
                      className="text-[10px] mt-0.5"
                      style={{ color: "var(--text-muted)" }}
                    >
                      {l.city}
                    </p>
                  </div>
                </motion.div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Sticky bottom bar (mobile) */}
      <div
        className="fixed bottom-0 left-0 right-0 z-[60] px-4 pt-3 border-t flex gap-2 items-center lg:hidden"
        style={{
          background: "var(--bg)",
          borderColor: "var(--border)",
          paddingBottom: "calc(12px + env(safe-area-inset-bottom, 0px))",
        }}
      >
        <div
          className="w-12 h-12 rounded-xl border shrink-0 flex items-center justify-center"
          style={{
            background: has(listing.id) ? "rgba(252,0,0,0.12)" : "var(--card)",
            borderColor: has(listing.id) ? "var(--accent)" : "var(--border)",
          }}
        >
          <WishlistButton listingId={listing.id} size={20} />
        </div>
        <button
          onClick={() => setShareOpen(true)}
          className="w-12 h-12 rounded-xl border flex items-center justify-center shrink-0"
          style={{ background: "var(--card)", borderColor: "var(--border)" }}
        >
          <Share2 size={18} style={{ color: "var(--text-muted)" }} />
        </button>
        {isSold ? (
          <div
            className="flex-1 flex items-center justify-center gap-2 py-3 rounded-xl font-bold text-sm"
            style={{ background: "rgba(239,68,68,0.12)", color: "#ef4444" }}
          >
            Item Sold Out
          </div>
        ) : !isSeller ? (
          <div className="flex-1 flex gap-2">
            {listing.condition === "new" && (
              <motion.button
                onClick={handleBuyNow}
                whileTap={{ scale: 0.97 }}
                className="flex-1 flex items-center justify-center gap-1.5 py-3 rounded-xl font-bold text-sm border"
                style={{
                  background: "var(--card)",
                  borderColor: "var(--border)",
                  color: "var(--text-primary)",
                }}
              >
                Buy It Now
              </motion.button>
            )}
            <motion.button
              onClick={handleChat}
              disabled={chatLoading}
              whileTap={{ scale: 0.97 }}
              className="flex-1 flex items-center justify-center gap-2 py-3 rounded-xl font-bold text-sm text-white disabled:opacity-70"
              style={{ background: "var(--accent)" }}
            >
              <MessageCircle size={16} />
              {chatLoading ? "Opening…" : "Chat"}
            </motion.button>
          </div>
        ) : null}
      </div>

      {/* Share modal */}
      <ShareModal
        open={shareOpen}
        onClose={() => setShareOpen(false)}
        url={pageUrl}
        title={listing.title}
      />

      {/* Buy It Now — direct PayPal checkout */}
      <BuyNowModal
        listing={buyNowListing}
        onClose={() => setBuyNowListing(null)}
        onSuccess={handleBuyNowSuccess}
        onError={handleBuyNowError}
      />
    </div>
  );
}
