"use client";
import { useState, useMemo, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
// useLocation removed — lat/lng now come from FilterPanel
import { motion, AnimatePresence } from "framer-motion";
import {
  SlidersHorizontal,
  MapPin,
  Eye,
  Clock,
  ChevronDown,
  TrendingUp,
  ShieldCheck,
  BadgePercent,
  X,
  Search,
  Grid,
  List,
} from "lucide-react";
import {
  CONDITION_LABELS,
  timeAgo,
  type BuyerListing,
} from "./mockData";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import { WishlistButton } from "./WishlistButton";
import { FilterPanel, type FilterState, DEFAULT_FILTERS } from "./FilterPanel";
import { useAppSelector, useAppDispatch } from "@/store/hooks";
import {
  fetchListings,
  type FetchListingsParams,
} from "@/store/slices/marketplaceListingsSlice";
import { fetchMarketplaceCategories } from "@/store/slices/marketplaceCategorySlice";
import { mapApiToListing } from "@/utils/marketplace";

const CATEGORY_EMOJI_MAP: Record<string, string> = {
  Electronics: "📱",
  Vehicles: "🚗",
  Furniture: "🛋️",
  Books: "📚",
  Sports: "⚽",
  "Home Appliances": "🏠",
  Fashion: "👗",
  Property: "🏢",
  Jobs: "💼",
  Services: "🔧",
};

/* ─── Constants ─────────────────────────────────────────────────────────── */
const TRUST_STATS = [
  { icon: ShieldCheck, label: "Buyer Protection", value: "100%" },
  { icon: TrendingUp, label: "Active Listings", value: "12k+" },
  { icon: BadgePercent, label: "Avg. Savings", value: "32%" },
];

const SORT_OPTIONS = [
  { value: "latest", label: "Latest" },
  { value: "price_low", label: "Price ↑" },
  { value: "price_high", label: "Price ↓" },
  { value: "most_viewed", label: "Popular" },
  { value: "most_saved", label: "Most Saved" },
];

function conditionColor(c: string) {
  if (c === "new") return "#22c55e";
  if (c === "like_new") return "#3b82f6";
  if (c === "good") return "#f0c040";
  return "#A0A0A0";
}

/* ─── Listing card (grid) ───────────────────────────────────────────────── */
function ListingCard({
  listing,
  delay = 0,
}: {
  listing: BuyerListing;
  delay?: number;
}) {
  const router = useRouter();
  const formatPrice = useFormatPrice();

  return (
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay, duration: 0.28 }}
      whileHover={{ y: -4, transition: { duration: 0.18 } }}
      onClick={() => router.push(`/marketplace/listing/${listing.slug}`)}
      className="rounded-xl overflow-hidden cursor-pointer border group"
      style={{ background: "var(--card)", borderColor: "var(--border)" }}
    >
      <div
        className="relative overflow-hidden bg-[var(--deep)]"
        style={{ aspectRatio: "4/3" }}
      >
        <img
          src={listing.images[0]}
          alt={listing.title}
          className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
        />
        <div className="absolute top-2 left-2 flex flex-col gap-1">
          {listing.isFeatured && (
            <span
              className="text-[9px] font-bold px-1.5 py-0.5 rounded-full"
              style={{ background: "#f0c040", color: "#1a1a0e" }}
            >
              ⭐ Featured
            </span>
          )}
          <span
            className="text-[9px] font-bold px-1.5 py-0.5 rounded-full text-white"
            style={{ background: conditionColor(listing.condition) + "dd" }}
          >
            {CONDITION_LABELS[listing.condition]}
          </span>
        </div>
        <div className="absolute top-2 right-2">
          <WishlistButton
            listingId={listing.id}
            size={14}
            className="w-7 h-7 rounded-full bg-black/50 backdrop-blur-sm"
          />
        </div>
        <div className="absolute bottom-0 left-0 right-0 px-2 py-1.5 bg-gradient-to-t from-black/75 to-transparent">
          <span className="text-white font-black text-sm">
            {formatPrice(listing.price)}
          </span>
          {listing.originalPrice && (
            <span className="text-white/55 text-[10px] line-through ml-1.5">
              {formatPrice(listing.originalPrice)}
            </span>
          )}
        </div>
      </div>
      <div className="p-2.5">
        <p
          className="text-xs font-semibold line-clamp-2 leading-tight mb-1.5"
          style={{ color: "var(--text-primary)" }}
        >
          {listing.title}
        </p>
        <div
          className="flex items-center gap-1 text-[10px] mb-1"
          style={{ color: "var(--text-muted)" }}
        >
          <MapPin size={9} />
          <span className="truncate">
            {listing.area}, {listing.city}
          </span>
        </div>
        <div
          className="flex items-center justify-between text-[10px]"
          style={{ color: "var(--text-muted)" }}
        >
          <span className="flex items-center gap-1">
            <Clock size={9} />
            {timeAgo(listing.postedAt)}
          </span>
          <span className="flex items-center gap-1">
            <Eye size={9} />
            {listing.views}
          </span>
        </div>
      </div>
    </motion.div>
  );
}

/* ─── List card (row) ───────────────────────────────────────────────────── */
function ListCard({ listing }: { listing: BuyerListing }) {
  const router = useRouter();
  const formatPrice = useFormatPrice();

  return (
    <motion.div
      layout
      whileHover={{ x: 2 }}
      onClick={() => router.push(`/marketplace/listing/${listing.slug}`)}
      className="flex gap-3 rounded-2xl overflow-hidden cursor-pointer border p-3"
      style={{ background: "var(--card)", borderColor: "var(--border)" }}
    >
      <div className="relative w-24 h-24 rounded-xl overflow-hidden shrink-0 bg-[var(--deep)]">
        <img
          src={listing.images[0]}
          alt={listing.title}
          className="w-full h-full object-cover"
        />
        <WishlistButton
          listingId={listing.id}
          size={13}
          className="absolute top-1 right-1 w-6 h-6 rounded-full bg-black/50"
        />
      </div>
      <div className="flex-1 min-w-0">
        <p
          className="text-sm font-semibold line-clamp-2 leading-snug mb-1"
          style={{ color: "var(--text-primary)" }}
        >
          {listing.title}
        </p>
        <p
          className="text-base font-black mb-1"
          style={{ color: "var(--accent)" }}
        >
          {formatPrice(listing.price)}
          {listing.originalPrice && (
            <span
              className="text-xs font-normal line-through ml-2"
              style={{ color: "var(--text-muted)" }}
            >
              {formatPrice(listing.originalPrice)}
            </span>
          )}
        </p>
        <div
          className="flex items-center gap-3 text-[11px]"
          style={{ color: "var(--text-muted)" }}
        >
          <span className="flex items-center gap-1">
            <MapPin size={10} />
            {listing.area}, {listing.city}
          </span>
          <span
            className="px-1.5 py-0.5 rounded-full text-[10px] font-bold"
            style={{
              background: "var(--deep)",
              color:
                listing.condition === "new"
                  ? "#22c55e"
                  : "var(--text-muted)",
            }}
          >
            {CONDITION_LABELS[listing.condition]}
          </span>
        </div>
        <div
          className="flex items-center gap-3 mt-1.5 text-[10px]"
          style={{ color: "var(--text-muted)" }}
        >
          <span className="flex items-center gap-1">
            <Eye size={9} />
            {listing.views} views
          </span>
          <span className="flex items-center gap-1">
            <Clock size={9} />
            {timeAgo(listing.postedAt)}
          </span>
        </div>
      </div>
    </motion.div>
  );
}

/* ─── Main component ─────────────────────────────────────────────────────── */
export function MarketplaceHome() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const urlQuery = searchParams.get("q") ?? "";

  const { categories: apiCategories } = useAppSelector(
    (s) => s.marketplaceCategory,
  );

  const categoryChips = apiCategories
    .filter((c) => c.status === 1)
    .sort((a, b) => a.sort_order - b.sort_order)
    .map((c) => ({
      id: c.id,
      name: c.name,
      emoji: CATEGORY_EMOJI_MAP[c.name] ?? "📦",
    }));

  const dispatch = useAppDispatch();
  const { listings: rawListings, isLoading: listingsLoading } = useAppSelector(
    (s) => s.marketplaceListings,
  );

  /* State */
  const [searchInput, setSearchInput] = useState(urlQuery);
  const [quickFilter, setQuickFilter] = useState<number | "all">("all");
  const [filterOpen, setFilterOpen] = useState(false);
  const [filters, setFilters] = useState<FilterState>(DEFAULT_FILTERS);
  const [sort, setSort] = useState("latest");
  const [showSortMenu, setShowSortMenu] = useState(false);
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
  const [visibleCount, setVisibleCount] = useState(20);

  /* Mode: "home" when no query, "results" when query active */
  const isSearchMode = urlQuery.trim().length > 0;

  /* ── Fetch categories on mount (handles direct page reload) ─────────────── */
  useEffect(() => {
    dispatch(fetchMarketplaceCategories());
  }, [dispatch]);

  /* ── Fetch from API whenever filters / search / category change ─────────── */
  useEffect(() => {
    const params: FetchListingsParams = {};

    if (isSearchMode && urlQuery) params.search = urlQuery;

    if (quickFilter !== "all") params.category_id = quickFilter;

    if (filters.priceMin) params.min_price = parseInt(filters.priceMin);
    if (filters.priceMax) params.max_price = parseInt(filters.priceMax);
    if (filters.condition)
      params.listing_condition = parseInt(filters.condition);
    if (filters.date) params.date = filters.date;
    if (filters.latitude) params.latitude = parseFloat(filters.latitude);
    if (filters.longitude) params.longitude = parseFloat(filters.longitude);

    dispatch(fetchListings(params));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [urlQuery, isSearchMode, quickFilter, filters, dispatch]);

  /* Reset pagination when filters change */
  useEffect(() => {
    setVisibleCount(20);
  }, [urlQuery, quickFilter, filters]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const q = searchInput.trim();
    if (q) router.push(`/marketplace?q=${encodeURIComponent(q)}`);
  };

  const clearSearch = () => {
    setSearchInput("");
    setFilters(DEFAULT_FILTERS);
    setSort("latest");
    router.push("/marketplace");
  };

  /* ── Map API data + client-side sort ───────────────────────────────────── */
  const results = useMemo(() => {
    const items = rawListings.map(mapApiToListing);
    if (sort === "price_low") items.sort((a, b) => a.price - b.price);
    else if (sort === "price_high") items.sort((a, b) => b.price - a.price);
    else if (sort === "most_viewed") items.sort((a, b) => b.views - a.views);
    else if (sort === "most_saved")
      items.sort((a, b) => b.savedCount - a.savedCount);
    else
      items.sort(
        (a, b) =>
          new Date(b.postedAt).getTime() - new Date(a.postedAt).getTime(),
      );
    return items;
  }, [rawListings, sort]);

  const activeFilterCount = [
    filters.priceMin,
    filters.priceMax,
    filters.condition,
    filters.date,
    filters.latitude,
    filters.longitude,
  ].filter(Boolean).length;

  const currentSortLabel =
    SORT_OPTIONS.find((s) => s.value === sort)?.label ?? "Latest";

  /* ══════════════════════════════════════════════════════════════════════════
     SEARCH RESULTS MODE
  ══════════════════════════════════════════════════════════════════════════ */
  if (isSearchMode) {
    return (
      <div className="min-h-full" style={{ background: "var(--bg)" }}>
        {/* ── Results toolbar ─────────────────────────────────────────────── */}
        <div
          className="sticky top-0 z-20 px-4 py-2.5 border-b flex items-center gap-2"
          style={{ background: "var(--bg)", borderColor: "var(--border)" }}
        >
          {/* Back / Clear */}
          <button
            onClick={clearSearch}
            className="flex items-center gap-1.5 shrink-0 px-3 py-1.5 rounded-full text-xs font-bold border"
            style={{
              borderColor: "var(--border)",
              background: "var(--card)",
              color: "var(--text-muted)",
            }}
          >
            <X size={12} />
            <span className="hidden sm:inline">Clear</span>
          </button>

          {/* Editable search input */}
          <form onSubmit={handleSearch} className="flex-1 min-w-0">
            <div
              className="flex items-center gap-2 px-3 py-1.5 rounded-full border"
              style={{
                background: "var(--card)",
                borderColor: "var(--accent)",
              }}
            >
              <Search
                size={12}
                style={{ color: "var(--accent)", flexShrink: 0 }}
              />
              <input
                value={searchInput}
                onChange={(e) => setSearchInput(e.target.value)}
                className="flex-1 min-w-0 bg-transparent outline-none text-xs font-semibold"
                style={{ color: "var(--text-primary)" }}
              />
              {searchInput && (
                <button
                  type="button"
                  onClick={() => setSearchInput("")}
                  style={{
                    color: "var(--text-muted)",
                    background: "none",
                    border: "none",
                    cursor: "pointer",
                  }}
                >
                  <X size={11} />
                </button>
              )}
            </div>
          </form>

          {/* Sort */}
          <div className="relative shrink-0">
            <button
              onClick={() => setShowSortMenu((p) => !p)}
              className="flex items-center gap-1 text-xs font-semibold px-3 py-1.5 rounded-full border"
              style={{
                borderColor: "var(--border)",
                background: "var(--card)",
                color: "var(--text-primary)",
              }}
            >
              <span className="hidden sm:inline">{currentSortLabel}</span>
              <ChevronDown size={12} />
            </button>
            <AnimatePresence>
              {showSortMenu && (
                <motion.div
                  initial={{ opacity: 0, scale: 0.95, y: -4 }}
                  animate={{ opacity: 1, scale: 1, y: 0 }}
                  exit={{ opacity: 0, scale: 0.95 }}
                  className="absolute right-0 top-9 z-50 rounded-xl border overflow-hidden min-w-[150px]"
                  style={{
                    background: "var(--card)",
                    borderColor: "var(--border)",
                  }}
                >
                  {SORT_OPTIONS.map((opt) => (
                    <button
                      key={opt.value}
                      onClick={() => {
                        setSort(opt.value);
                        setShowSortMenu(false);
                      }}
                      className="flex items-center justify-between w-full px-4 py-2.5 text-sm"
                      style={{
                        color:
                          sort === opt.value
                            ? "var(--accent)"
                            : "var(--text-primary)",
                        background:
                          sort === opt.value
                            ? "rgba(252,0,0,0.08)"
                            : "transparent",
                      }}
                    >
                      {opt.label}
                      {sort === opt.value && (
                        <span style={{ color: "var(--accent)", fontSize: 10 }}>
                          ✓
                        </span>
                      )}
                    </button>
                  ))}
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          {/* Filter button */}
          <motion.button
            whileTap={{ scale: 0.92 }}
            onClick={() => setFilterOpen(true)}
            className="relative shrink-0 flex items-center gap-1.5 px-3 py-1.5 rounded-full border text-xs font-semibold"
            style={{
              background:
                activeFilterCount > 0 ? "rgba(252,0,0,0.08)" : "var(--card)",
              borderColor:
                activeFilterCount > 0 ? "var(--accent)" : "var(--border)",
              color:
                activeFilterCount > 0 ? "var(--accent)" : "var(--text-muted)",
            }}
          >
            <SlidersHorizontal size={13} />
            <span className="hidden sm:inline">Filters</span>
            {activeFilterCount > 0 && (
              <span
                className="w-4 h-4 rounded-full text-white text-[9px] font-black flex items-center justify-center"
                style={{ background: "var(--accent)" }}
              >
                {activeFilterCount}
              </span>
            )}
          </motion.button>

          {/* View toggle */}
          <div
            className="flex rounded-lg overflow-hidden border shrink-0"
            style={{ borderColor: "var(--border)" }}
          >
            <button
              onClick={() => setViewMode("grid")}
              className="p-1.5 transition-colors"
              style={{
                background:
                  viewMode === "grid" ? "var(--accent)" : "var(--card)",
                color: viewMode === "grid" ? "#fff" : "var(--text-muted)",
              }}
            >
              <Grid size={14} />
            </button>
            <button
              onClick={() => setViewMode("list")}
              className="p-1.5 transition-colors"
              style={{
                background:
                  viewMode === "list" ? "var(--accent)" : "var(--card)",
                color: viewMode === "list" ? "#fff" : "var(--text-muted)",
              }}
            >
              <List size={14} />
            </button>
          </div>
        </div>

        {/* Results count */}
        <div className="px-4 pt-3 pb-1  mx-auto">
          <p className="text-xs" style={{ color: "var(--text-muted)" }}>
            <strong style={{ color: "var(--text-primary)" }}>
              {results.length}
            </strong>{" "}
            results for{" "}
            <strong style={{ color: "var(--accent)" }}>
              &ldquo;{urlQuery}&rdquo;
            </strong>
          </p>
        </div>

        {/* Results grid / list */}
        <div className="px-4 pb-24 pt-2  mx-auto">
          <AnimatePresence mode="wait">
            {listingsLoading ? (
              <motion.div
                key="loading"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3"
              >
                {Array.from({ length: 10 }).map((_, i) => (
                  <div
                    key={i}
                    className="rounded-xl overflow-hidden border animate-pulse"
                    style={{
                      background: "var(--card)",
                      borderColor: "var(--border)",
                    }}
                  >
                    <div
                      className="aspect-[4/3]"
                      style={{ background: "var(--deep)" }}
                    />
                    <div className="p-2.5 space-y-2">
                      <div
                        className="h-3 rounded"
                        style={{ background: "var(--deep)", width: "80%" }}
                      />
                      <div
                        className="h-3 rounded"
                        style={{ background: "var(--deep)", width: "50%" }}
                      />
                    </div>
                  </div>
                ))}
              </motion.div>
            ) : results.length === 0 ? (
              <motion.div
                key="empty"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex flex-col items-center justify-center py-24 text-center"
              >
                <div className="text-5xl mb-4">🔍</div>
                <h3
                  className="text-base font-bold mb-1"
                  style={{ color: "var(--text-primary)" }}
                >
                  No results found
                </h3>
                <p
                  className="text-sm mb-5"
                  style={{ color: "var(--text-muted)" }}
                >
                  Try a different search or clear your filters
                </p>
                <button
                  onClick={clearSearch}
                  className="px-5 py-2 rounded-full text-sm font-bold text-white"
                  style={{ background: "var(--accent)" }}
                >
                  Back to Home
                </button>
              </motion.div>
            ) : viewMode === "grid" ? (
              <motion.div
                key="grid"
                className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3"
              >
                {results.slice(0, visibleCount).map((l, i) => (
                  <motion.div
                    key={l.id}
                    initial={{ opacity: 0, y: 12 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: i * 0.04 }}
                  >
                    <ListingCard listing={l} />
                  </motion.div>
                ))}
              </motion.div>
            ) : (
              <motion.div key="list" className="flex flex-col gap-3">
                {results.slice(0, visibleCount).map((l, i) => (
                  <motion.div
                    key={l.id}
                    initial={{ opacity: 0, x: -12 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: i * 0.04 }}
                  >
                    <ListCard listing={l} />
                  </motion.div>
                ))}
              </motion.div>
            )}
          </AnimatePresence>
          {visibleCount < results.length && (
            <div className="flex justify-center mt-6">
              <motion.button
                whileTap={{ scale: 0.97 }}
                onClick={() => setVisibleCount((v) => v + 20)}
                className="flex items-center gap-2 px-6 py-2.5 rounded-full text-sm font-bold border"
                style={{
                  borderColor: "var(--border)",
                  background: "var(--card)",
                  color: "var(--text-primary)",
                }}
              >
                Load more · {results.length - visibleCount} remaining
              </motion.button>
            </div>
          )}
        </div>

        <FilterPanel
          open={filterOpen}
          onClose={() => setFilterOpen(false)}
          filters={filters}
          onApply={(f) => setFilters(f)}
          resultCount={results.length}
        />

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

  /* ══════════════════════════════════════════════════════════════════════════
     HOME MODE (no search query)
  ══════════════════════════════════════════════════════════════════════════ */
  return (
    <div className="min-h-full" style={{ background: "var(--bg)" }}>
      {/* ── Trust stats bar ───────────────────────────────────────────────── */}
      <div
        style={{
          background:
            "linear-gradient(90deg, rgba(252,0,0,0.06) 0%, transparent 60%)",
          borderBottom: "1px solid var(--border)",
        }}
      >
        <div className=" mx-auto px-4 md:px-6">
          <div className="hidden sm:flex items-center gap-8 py-2.5">
            {TRUST_STATS.map((s) => (
              <div key={s.label} className="flex items-center gap-2">
                <s.icon
                  size={13}
                  style={{ color: "var(--accent)", opacity: 0.85 }}
                />
                <span
                  style={{
                    fontSize: 11,
                    color: "var(--text-muted)",
                    fontWeight: 600,
                  }}
                >
                  <strong
                    style={{ color: "var(--text-primary)", fontWeight: 800 }}
                  >
                    {s.value}
                  </strong>{" "}
                  {s.label}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ── Search bar ───────────────────────────────────────────────────── */}
      <div className=" mx-auto px-4 md:px-6 py-3">
        <form onSubmit={handleSearch}>
          <div
            className="flex items-center gap-3 px-4 rounded-2xl border transition-all"
            style={{
              background: "var(--card)",
              borderColor: "var(--border)",
              height: 48,
            }}
            onFocusCapture={(e) =>
              ((e.currentTarget as HTMLElement).style.borderColor =
                "var(--accent)")
            }
            onBlurCapture={(e) =>
              ((e.currentTarget as HTMLElement).style.borderColor =
                "var(--border)")
            }
          >
            <Search
              size={16}
              style={{ color: "var(--text-muted)", flexShrink: 0 }}
            />
            <input
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
              placeholder="Search products, sellers, categories…"
              className="flex-1 bg-transparent outline-none text-sm"
              style={{ color: "var(--text-primary)" }}
            />
            {searchInput && (
              <button
                type="button"
                onClick={() => setSearchInput("")}
                style={{
                  color: "var(--text-muted)",
                  background: "none",
                  border: "none",
                  cursor: "pointer",
                  padding: 2,
                }}
              >
                <X size={14} />
              </button>
            )}
            <button
              type="submit"
              className="shrink-0 flex items-center gap-1.5 px-4 py-1.5 rounded-xl text-xs font-bold text-white"
              style={{
                background: "var(--accent)",
                border: "none",
                cursor: "pointer",
              }}
            >
              Search
            </button>
          </div>
        </form>
      </div>

      {/* ── Category strip ────────────────────────────────────────────────── */}
      <div
        style={{
          borderBottom: "1px solid var(--border)",
          background: "var(--card)",
        }}
      >
        <div className=" mx-auto px-4 md:px-6">
          <div className="flex gap-1.5 overflow-x-auto py-3 no-scrollbar">
            <motion.button
              whileTap={{ scale: 0.92 }}
              onClick={() => setQuickFilter("all")}
              className="shrink-0 flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-bold border transition-all"
              style={{
                borderColor:
                  quickFilter === "all" ? "var(--accent)" : "var(--border)",
                background:
                  quickFilter === "all" ? "rgba(252,0,0,0.08)" : "transparent",
                color:
                  quickFilter === "all" ? "var(--accent)" : "var(--text-muted)",
              }}
            >
              🏠 All
            </motion.button>
            {categoryChips.map((cat) => {
              const active = quickFilter === cat.id;
              return (
                <motion.button
                  key={cat.id}
                  whileTap={{ scale: 0.92 }}
                  onClick={() => setQuickFilter(cat.id)}
                  className="shrink-0 flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-bold border transition-all"
                  style={{
                    borderColor: active ? "var(--accent)" : "var(--border)",
                    background: active ? "rgba(252,0,0,0.08)" : "transparent",
                    color: active ? "var(--accent)" : "var(--text-muted)",
                  }}
                >
                  <span>{cat.emoji}</span>
                  <span className="hidden sm:inline">{cat.name}</span>
                </motion.button>
              );
            })}
          </div>
        </div>
      </div>

      {/* ── Filter bar + listings ─────────────────────────────────────────── */}
      <div className=" mx-auto px-4 md:px-6">
        {/* Sticky filter bar */}
        <div
          className="sticky z-20 -mx-4 md:-mx-6 px-4 md:px-6"
          style={{
            top: 0,
            background: "var(--bg)",
            borderBottom: "1px solid var(--border)",
          }}
        >
          <div className="flex items-center gap-2 py-2.5">
            <p
              className="text-xs flex-1 shrink-0"
              style={{ color: "var(--text-muted)" }}
            >
              <strong style={{ color: "var(--text-primary)" }}>
                {results.length}
              </strong>{" "}
              listing{results.length !== 1 ? "s" : ""}
            </p>

            {/* Sort dropdown */}
            <div className="relative shrink-0">
              <button
                onClick={() => setShowSortMenu((p) => !p)}
                className="flex items-center gap-1 text-xs font-semibold px-3 py-1.5 rounded-full border"
                style={{
                  borderColor: "var(--border)",
                  background: "var(--card)",
                  color: "var(--text-primary)",
                }}
              >
                <span className="hidden sm:inline">
                  {SORT_OPTIONS.find((s) => s.value === sort)?.label ??
                    "Latest"}
                </span>
                <ChevronDown size={12} />
              </button>
              <AnimatePresence>
                {showSortMenu && (
                  <motion.div
                    initial={{ opacity: 0, scale: 0.95, y: -4 }}
                    animate={{ opacity: 1, scale: 1, y: 0 }}
                    exit={{ opacity: 0, scale: 0.95 }}
                    className="absolute right-0 top-9 z-50 rounded-xl border overflow-hidden min-w-[150px]"
                    style={{
                      background: "var(--card)",
                      borderColor: "var(--border)",
                    }}
                  >
                    {SORT_OPTIONS.map((opt) => (
                      <button
                        key={opt.value}
                        onClick={() => {
                          setSort(opt.value);
                          setShowSortMenu(false);
                        }}
                        className="flex items-center justify-between w-full px-4 py-2.5 text-sm"
                        style={{
                          color:
                            sort === opt.value
                              ? "var(--accent)"
                              : "var(--text-primary)",
                          background:
                            sort === opt.value
                              ? "rgba(252,0,0,0.08)"
                              : "transparent",
                        }}
                      >
                        {opt.label}
                      </button>
                    ))}
                  </motion.div>
                )}
              </AnimatePresence>
            </div>

            {/* Filters button */}
            <motion.button
              whileTap={{ scale: 0.92 }}
              onClick={() => setFilterOpen(true)}
              className="relative shrink-0 flex items-center gap-1.5 px-3 py-1.5 rounded-full border text-xs font-semibold"
              style={{
                background:
                  activeFilterCount > 0 ? "rgba(252,0,0,0.08)" : "var(--card)",
                borderColor:
                  activeFilterCount > 0 ? "var(--accent)" : "var(--border)",
                color:
                  activeFilterCount > 0 ? "var(--accent)" : "var(--text-muted)",
              }}
            >
              <SlidersHorizontal size={13} />
              <span className="hidden sm:inline">Filters</span>
              {activeFilterCount > 0 && (
                <span
                  className="w-4 h-4 rounded-full text-white text-[9px] font-black flex items-center justify-center"
                  style={{ background: "var(--accent)" }}
                >
                  {activeFilterCount}
                </span>
              )}
            </motion.button>
          </div>
        </div>

        {/* Listings grid */}
        <div className="pt-4 pb-24">
          <AnimatePresence mode="wait">
            {listingsLoading ? (
              <motion.div
                key="loading"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3"
              >
                {Array.from({ length: 10 }).map((_, i) => (
                  <div
                    key={i}
                    className="rounded-xl overflow-hidden border animate-pulse"
                    style={{
                      background: "var(--card)",
                      borderColor: "var(--border)",
                    }}
                  >
                    <div
                      className="aspect-[4/3]"
                      style={{ background: "var(--deep)" }}
                    />
                    <div className="p-2.5 space-y-2">
                      <div
                        className="h-3 rounded"
                        style={{ background: "var(--deep)", width: "80%" }}
                      />
                      <div
                        className="h-3 rounded"
                        style={{ background: "var(--deep)", width: "50%" }}
                      />
                    </div>
                  </div>
                ))}
              </motion.div>
            ) : results.length === 0 ? (
              <motion.div
                key="empty"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0 }}
                className="flex flex-col items-center justify-center py-24 text-center"
              >
                <div className="text-5xl mb-4">🔍</div>
                <h3
                  className="text-base font-bold mb-1"
                  style={{ color: "var(--text-primary)" }}
                >
                  No listings found
                </h3>
                <p
                  className="text-sm mb-5"
                  style={{ color: "var(--text-muted)" }}
                >
                  Try adjusting your filters
                </p>
                <button
                  onClick={() => {
                    setQuickFilter("all");
                    setFilters(DEFAULT_FILTERS);
                  }}
                  className="px-5 py-2 rounded-full text-sm font-bold text-white"
                  style={{ background: "var(--accent)" }}
                >
                  Clear Filters
                </button>
              </motion.div>
            ) : (
              <motion.div
                key="grid"
                className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3"
              >
                {results.slice(0, visibleCount).map((l, i) => (
                  <ListingCard
                    key={l.id}
                    listing={l}
                    delay={Math.min(i * 0.03, 0.3)}
                  />
                ))}
              </motion.div>
            )}
          </AnimatePresence>
          {visibleCount < results.length && (
            <div className="flex justify-center mt-6">
              <motion.button
                whileTap={{ scale: 0.97 }}
                onClick={() => setVisibleCount((v) => v + 20)}
                className="flex items-center gap-2 px-6 py-2.5 rounded-full text-sm font-bold border"
                style={{
                  borderColor: "var(--border)",
                  background: "var(--card)",
                  color: "var(--text-primary)",
                }}
              >
                Load more · {results.length - visibleCount} remaining
              </motion.button>
            </div>
          )}
        </div>
      </div>

      {/* Filter panel */}
      <FilterPanel
        open={filterOpen}
        onClose={() => setFilterOpen(false)}
        filters={filters}
        onApply={(f) => setFilters(f)}
        resultCount={results.length}
      />

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