"use client";

import { useState, useRef, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import type { LucideIcon } from "lucide-react";
import {
  Plus,
  Eye,
  MessageCircle,
  Heart,
  MoreVertical,
  Edit2,
  Pause,
  Play,
  CheckCircle2,
  Trash2,
  Zap,
  TrendingUp,
  Package,
  MapPin,
  Calendar,
  Star,
  X,
  Award,
  Target,
  BarChart2,
  ShoppingBag,
  FileText,
  Sparkles,
} from "lucide-react";
import type { Listing, ListingStatus, BoostPlan } from "./types";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchMyListings } from "@/store/slices/marketplaceMyListingsSlice";
import type { ApiListing } from "@/types/marketplace";
import Cookies from "js-cookie";
import apiClient from "@/lib/axiosClient";
import { API_ENDPOINTS } from "@/lib/apiEndpoints";
import { useRouter } from "next/navigation";
import { slugify } from "@/utils/marketplace";

/* ─── API → Listing mapper ──────────────────────────────────────────────────── */

function apiStatusToListingStatus(s: number): ListingStatus {
  const m: Record<number, ListingStatus> = {
    0: "draft",
    1: "active",
    2: "sold",
    3: "paused",
  };
  return m[s] ?? "draft";
}

function mapApiToListing(api: ApiListing): Listing {
  return {
    id: String(api.id),
    title: api.title,
    description: api.description,
    category: api.category_name,
    subCategory: api.category_name,
    condition: api.listing_condition === 1 ? "new" : "used",
    images: [{ id: String(api.id), url: api.image, isCover: true }],
    price: api.price,
    originalPrice: undefined,
    isNegotiable: false,
    city: api.city,
    area: api.area,
    status: apiStatusToListingStatus(api.status),
    createdAt: api.created_at,
    views: api.total_view,
    enquiries: 0,
    savedCount: api.total_wishlist,
    performanceScore: 0,
    isBoosted: api.is_featured === 1,
  };
}

/* ─── Loading skeleton ──────────────────────────────────────────────────────── */

function ListingCardSkeleton() {
  return (
    <div className="rounded-2xl border border-[var(--border)] bg-[var(--card)] overflow-hidden flex flex-col animate-pulse">
      {/* Image */}
      <div className="aspect-[4/3] bg-[var(--deep)]" />
      {/* Content */}
      <div className="flex flex-col flex-1 p-3 gap-2.5">
        <div className="space-y-1.5">
          <div className="h-3 w-11/12 rounded bg-[var(--deep)]" />
          <div className="h-3 w-7/12 rounded bg-[var(--deep)]" />
        </div>
        <div className="h-4 w-1/2 rounded bg-[var(--deep)]" />
        <div className="flex gap-1.5">
          <div className="h-4 w-16 rounded-full bg-[var(--deep)]" />
        </div>
        <div className="h-3 w-3/4 rounded bg-[var(--deep)]" />
        <div className="grid grid-cols-3 gap-1 pt-2 border-t border-[var(--border)]">
          {[0, 1, 2].map((i) => (
            <div key={i} className="flex flex-col items-center gap-1">
              <div className="h-3 w-8 rounded bg-[var(--deep)]" />
              <div className="h-2 w-6 rounded bg-[var(--deep)]" />
            </div>
          ))}
        </div>
        <div className="flex items-center justify-between pt-1">
          <div className="h-2.5 w-14 rounded bg-[var(--deep)]" />
          <div className="w-7 h-7 rounded-lg bg-[var(--deep)]" />
        </div>
      </div>
    </div>
  );
}

function DashboardSkeleton() {
  return (
    <div className="min-h-full bg-[var(--bg)] animate-pulse">
      <div className="px-4 pt-6 pb-2 flex items-center justify-between gap-3">
        <div className="space-y-2">
          <div
            className="h-6 w-32 rounded-lg"
            style={{ background: "var(--card)" }}
          />
          <div
            className="h-4 w-24 rounded"
            style={{ background: "var(--card)" }}
          />
        </div>
        <div
          className="h-9 w-28 rounded-xl"
          style={{ background: "var(--card)" }}
        />
      </div>
      <div className="px-4 pt-4 pb-2 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
        {Array.from({ length: 6 }).map((_, i) => (
          <div
            key={i}
            className="rounded-xl h-24"
            style={{
              background: "var(--card)",
              border: "1px solid var(--border)",
            }}
          />
        ))}
      </div>
      <div className="px-4 py-4 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
        {Array.from({ length: 6 }).map((_, i) => (
          <ListingCardSkeleton key={i} />
        ))}
      </div>
    </div>
  );
}

/* ─── Tab → API status param map ─────────────────────────────────────────── */
const TAB_TO_STATUS: Record<ListingStatus | "all", "all" | 0 | 1 | 2 | 3> = {
  all: "all",
  active: 1,
  draft: 0,
  sold: 2,
  paused: 3,
  deleted: "all",
};

/* Valid status transitions a seller can make */
const STATUS_TRANSITIONS: Partial<Record<ListingStatus, ListingStatus[]>> = {
  active: ["paused", "sold"],
  paused: ["active"],
};

const STATUS_API_VALUE: Partial<Record<ListingStatus, number>> = {
  active: 1,
  paused: 3,
  sold: 2,
};

const STATUS_CHANGE_LABEL: Partial<Record<ListingStatus, string>> = {
  paused: "Pause Listing",
  active: "Resume Listing",
  sold: "Mark as Sold",
};

const BOOST_PLANS: BoostPlan[] = [
  {
    id: "1d",
    label: "1 Day Boost",
    duration: "24 hours",
    price: 49,
    reach: "~500",
    estimatedViews: "80–150",
  },
  {
    id: "7d",
    label: "7 Day Boost",
    duration: "7 days",
    price: 199,
    reach: "~3,500",
    estimatedViews: "600–1,200",
    badge: "Popular",
  },
  {
    id: "30d",
    label: "30 Day Boost",
    duration: "30 days",
    price: 599,
    reach: "~15,000",
    estimatedViews: "2,500–5,000",
    badge: "Best Value",
  },
];

const CONDITION_LABELS: Record<string, string> = {
  new: "Brand New",
  used: "Used",
};

/* ─── Stat Card ─────────────────────────────────────────────────────────────── */

function StatCard({
  label,
  value,
  sub,
  icon: Icon,
  accent,
  delay = 0,
}: {
  label: string;
  value: string | number;
  sub?: string;
  icon: LucideIcon;
  accent?: string;
  delay?: number;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay, duration: 0.35, ease: "easeOut" }}
      className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 flex flex-col gap-3"
    >
      <div className="flex items-start justify-between">
        <p className="text-xs font-semibold uppercase tracking-widest text-[var(--text-muted)]">
          {label}
        </p>
        <div
          className="w-7 h-7 rounded-lg flex items-center justify-center"
          style={{ background: accent ? `${accent}15` : "var(--deep)" }}
        >
          <Icon size={14} color={accent ?? "var(--text-muted)"} />
        </div>
      </div>
      <div>
        <p className="text-2xl font-black text-[var(--text-primary)]">
          {value}
        </p>
        {sub && (
          <p className="text-xs text-[var(--text-muted)] mt-0.5">{sub}</p>
        )}
      </div>
    </motion.div>
  );
}

/* ─── Status badge ──────────────────────────────────────────────────────────── */

function StatusBadge({ status }: { status: ListingStatus }) {
  const map: Record<ListingStatus, { label: string; cls: string }> = {
    active: {
      label: "Active",
      cls: "bg-emerald-500/10 text-emerald-400 border-emerald-500/20",
    },
    sold: {
      label: "Sold",
      cls: "bg-[rgba(240,192,64,0.12)] text-[#f0c040] border-[rgba(240,192,64,0.3)]",
    },
    draft: {
      label: "Draft",
      cls: "bg-[var(--deep)] text-[var(--text-muted)] border-[var(--border)]",
    },
    paused: {
      label: "Paused",
      cls: "bg-orange-500/10 text-orange-400 border-orange-500/20",
    },
    deleted: {
      label: "Deleted",
      cls: "bg-[rgba(252,0,0,0.1)] text-[#fc0000] border-[rgba(252,0,0,0.2)]",
    },
  };
  const { label, cls } = map[status];
  return (
    <span
      className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full border ${cls}`}
    >
      {label}
    </span>
  );
}

/* ─── Action Menu ───────────────────────────────────────────────────────────── */

function ActionMenu({
  listing,
  onAction,
  onClose,
}: {
  listing: Listing;
  onAction: (action: string, id: string) => void;
  onClose: () => void;
}) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) onClose();
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [onClose]);

  const actions: Array<{
    id: string;
    label: string;
    icon: LucideIcon;
    show: boolean;
    gold?: boolean;
    danger?: boolean;
  }> = [
    {
      id: "edit",
      label: "Edit Listing",
      icon: Edit2,
      show: listing.status === "draft",
    },
    {
      id: "pause",
      label: listing.status === "paused" ? "Resume Listing" : "Pause Listing",
      icon: listing.status === "paused" ? Play : Pause,
      show: listing.status === "active" || listing.status === "paused",
    },
    {
      id: "sold",
      label: "Mark as Sold",
      icon: CheckCircle2,
      show: listing.status === "active" || listing.status === "paused",
    },
    {
      id: "boost",
      label: "Boost Listing",
      icon: Zap,
      show: listing.status === "active",
      gold: true,
    },
    { id: "delete", label: "Delete", icon: Trash2, show: true, danger: true },
  ].filter((a) => a.show);

  return (
    <motion.div
      ref={ref}
      initial={{ opacity: 0, scale: 0.92, y: -6 }}
      animate={{ opacity: 1, scale: 1, y: 0 }}
      exit={{ opacity: 0, scale: 0.92, y: -6 }}
      transition={{ duration: 0.15 }}
      className="absolute right-0 top-8 z-50 min-w-[180px] rounded-xl border border-[var(--border)] bg-[var(--card)] shadow-2xl shadow-black/20 overflow-hidden"
    >
      {actions.map((action) => (
        <button
          key={action.id}
          type="button"
          onClick={() => {
            onAction(action.id, listing.id);
            onClose();
          }}
          className={`w-full flex items-center gap-3 px-4 py-2.5 text-sm transition-colors text-left ${
            action.danger
              ? "text-[#fc0000] hover:bg-[rgba(252,0,0,0.08)]"
              : action.gold
                ? "text-[#f0c040] hover:bg-[rgba(240,192,64,0.08)]"
                : "text-[var(--text-primary)] hover:bg-[var(--deep)]"
          }`}
        >
          <action.icon size={14} className="flex-shrink-0" />
          {action.label}
        </button>
      ))}
    </motion.div>
  );
}

/* ─── Listing Card ──────────────────────────────────────────────────────────── */

function ListingCard({
  listing,
  onAction,
  onSelect,
  currencyCode,
}: {
  listing: Listing;
  onAction: (action: string, id: string) => void;
  onSelect: () => void;
  currencyCode: string;
}) {
  const [menuOpen, setMenuOpen] = useState(false);
  const cover = listing.images.find((img) => img.isCover) ?? listing.images[0];
  const discount =
    listing.originalPrice && listing.price < listing.originalPrice
      ? Math.round(
          ((listing.originalPrice - listing.price) / listing.originalPrice) *
            100,
        )
      : 0;

  return (
    <motion.div
      layout
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, scale: 0.95 }}
      whileHover={{ y: -2 }}
      transition={{ duration: 0.25 }}
      onClick={onSelect}
      className={`relative rounded-2xl border bg-[var(--card)] overflow-hidden flex flex-col transition-all cursor-pointer ${
        listing.status === "sold"
          ? "border-[rgba(240,192,64,0.2)] opacity-80"
          : listing.status === "draft"
            ? "border-dashed border-[var(--border)]"
            : "border-[var(--border)] hover:border-[rgba(252,0,0,0.2)] hover:shadow-lg hover:shadow-[rgba(252,0,0,0.06)]"
      }`}
    >
      {/* Image — fixed height so all cards share the same image slot */}
      <div className="relative h-36 sm:h-40 bg-[var(--deep)] flex-shrink-0 overflow-hidden">
        {cover ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={cover.url}
            alt={listing.title}
            className="absolute inset-0 w-full h-full object-cover"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Package size={28} className="text-[var(--text-muted)]" />
          </div>
        )}

        {/* Overlays */}
        <div className="absolute top-2 left-2 flex flex-col gap-1">
          <StatusBadge status={listing.status} />
          {listing.isBoosted && (
            <span className="text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full bg-[rgba(240,192,64,0.9)] text-[#1a1a2e] flex items-center gap-1">
              <Zap size={9} />
              Boosted
            </span>
          )}
        </div>

        {discount > 0 && (
          <div className="absolute top-2 right-2 bg-[#fc0000] text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md">
            -{discount}%
          </div>
        )}

        {listing.status === "sold" && (
          <div className="absolute inset-0 bg-black/40 flex items-center justify-center">
            <span className="text-[#f0c040] font-black text-lg uppercase tracking-widest rotate-[-15deg] border-4 border-[#f0c040] px-3 py-1 rounded-lg">
              SOLD
            </span>
          </div>
        )}

        {listing.status === "draft" && (
          <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
            <span className="text-white/60 font-semibold text-sm">Draft</span>
          </div>
        )}
      </div>

      {/* Content */}
      <div className="flex flex-col flex-1 p-3">
        {/* Variable content — grows naturally */}
        <div className="flex flex-col gap-2">
          <p className="text-sm font-semibold text-[var(--text-primary)] line-clamp-2 leading-tight">
            {listing.title}
          </p>

          <div className="flex items-baseline gap-1.5 flex-wrap">
            <span className="text-base font-black text-[var(--text-primary)]">
              {currencyCode}
              {listing.price.toLocaleString()}
            </span>
            {listing.originalPrice && listing.price < listing.originalPrice && (
              <span className="text-xs text-[var(--text-muted)] line-through">
                {currencyCode}
                {listing.originalPrice.toLocaleString()}
              </span>
            )}
          </div>

          <div className="flex items-center gap-1.5 flex-wrap">
            <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-[var(--deep)] border border-[var(--border)] text-[var(--text-muted)] font-medium">
              {CONDITION_LABELS[listing.condition]}
            </span>
            {listing.isNegotiable && (
              <span className="text-[10px] text-[#f0c040]">Negotiable</span>
            )}
          </div>

          <div className="flex items-center gap-1 text-[10px] text-[var(--text-muted)]">
            <MapPin size={10} className="text-[#fc0000] flex-shrink-0" />
            <span className="truncate">
              {listing.area}, {listing.city}
            </span>
          </div>

          {/* Metrics */}
          {listing.status !== "draft" && (
            <div className="grid grid-cols-3 gap-1 pt-2 border-t border-[var(--border)]">
              {[
                { icon: Eye, value: listing.views, label: "Views" },
                {
                  icon: MessageCircle,
                  value: listing.enquiries,
                  label: "Enquiries",
                },
                { icon: Heart, value: listing.savedCount, label: "Saved" },
              ].map((metric) => (
                <div
                  key={metric.label}
                  className="flex flex-col items-center gap-0.5"
                >
                  <div className="flex items-center gap-0.5">
                    <metric.icon
                      size={10}
                      className="text-[var(--text-muted)]"
                    />
                    <span className="text-xs font-bold text-[var(--text-primary)]">
                      {metric.value >= 1000
                        ? `${(metric.value / 1000).toFixed(1)}k`
                        : metric.value}
                    </span>
                  </div>
                  <span className="text-[9px] text-[var(--text-muted)] uppercase tracking-wide">
                    {metric.label}
                  </span>
                </div>
              ))}
            </div>
          )}

          {/* Performance score */}
          {listing.status === "active" && listing.performanceScore > 0 && (
            <div className="flex items-center gap-2">
              <div className="flex-1 h-1 rounded-full bg-[var(--deep)] overflow-hidden">
                <motion.div
                  initial={{ width: 0 }}
                  animate={{ width: `${listing.performanceScore}%` }}
                  transition={{ delay: 0.4, duration: 0.6, ease: "easeOut" }}
                  className="h-full rounded-full"
                  style={{
                    background:
                      listing.performanceScore >= 80
                        ? "#22c55e"
                        : listing.performanceScore >= 50
                          ? "#f0c040"
                          : "#fc0000",
                  }}
                />
              </div>
              <span className="text-[10px] font-bold text-[var(--text-muted)] w-8 text-right">
                {listing.performanceScore}%
              </span>
            </div>
          )}
        </div>

        {/* Date + action — always pinned to the bottom of the card */}
        <div className="flex items-center justify-between pt-2 mt-auto">
          <div className="flex items-center gap-1 text-[10px] text-[var(--text-muted)]">
            <Calendar size={10} />
            <span>
              {new Date(listing.createdAt).toLocaleDateString("en-IN", {
                day: "numeric",
                month: "short",
              })}
            </span>
          </div>
          {/* <div className="relative">
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation();
                setMenuOpen((v) => !v);
              }}
              className="w-7 h-7 rounded-lg flex items-center justify-center text-[var(--text-muted)] hover:bg-[var(--deep)] hover:text-[var(--text-primary)] transition-colors"
            >
              <MoreVertical size={14} />
            </button>
            <AnimatePresence>
              {menuOpen && (
                <ActionMenu
                  listing={listing}
                  onAction={onAction}
                  onClose={() => setMenuOpen(false)}
                />
              )}
            </AnimatePresence>
          </div> */}
        </div>
      </div>
    </motion.div>
  );
}

/* ─── Boost Modal ───────────────────────────────────────────────────────────── */

function BoostModal({
  listing,
  onClose,
  currencyCode,
}: {
  listing: Listing;
  onClose: () => void;
  currencyCode: string;
}) {
  const [selected, setSelected] = useState<string | null>(null);
  const [boosting, setBoosting] = useState(false);
  const [boosted, setBoosted] = useState(false);

  const handleBoost = async () => {
    if (!selected) return;
    setBoosting(true);
    await new Promise((r) => setTimeout(r, 1500));
    setBoosting(false);
    setBoosted(true);
    setTimeout(onClose, 2000);
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4"
      style={{ background: "rgba(0,0,0,0.7)", backdropFilter: "blur(4px)" }}
      onClick={onClose}
    >
      <motion.div
        initial={{ opacity: 0, scale: 0.95, y: 20 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        exit={{ opacity: 0, scale: 0.95, y: 20 }}
        transition={{ type: "spring", stiffness: 300, damping: 30 }}
        onClick={(e) => e.stopPropagation()}
        className="w-full max-w-md rounded-2xl border border-[var(--border)] bg-[var(--card)] overflow-hidden"
      >
        {/* Header */}
        <div
          className="relative p-5 pb-4 border-b border-[var(--border)]"
          style={{
            background:
              "linear-gradient(135deg, rgba(240,192,64,0.08) 0%, var(--card) 100%)",
          }}
        >
          <button
            type="button"
            onClick={onClose}
            className="absolute top-4 right-4 w-7 h-7 rounded-full bg-[var(--deep)] flex items-center justify-center text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
          >
            <X size={14} />
          </button>
          <div className="flex items-center gap-3 mb-1">
            <div className="w-9 h-9 rounded-xl bg-[rgba(240,192,64,0.15)] border border-[rgba(240,192,64,0.3)] flex items-center justify-center">
              <Zap size={18} className="text-[#f0c040]" />
            </div>
            <div>
              <h2 className="text-base font-black text-[var(--text-primary)]">
                Boost Listing
              </h2>
              <p className="text-xs text-[var(--text-muted)]">
                {listing.title}
              </p>
            </div>
          </div>
        </div>

        {boosted ? (
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="p-8 flex flex-col items-center gap-3 text-center"
          >
            <div className="w-14 h-14 rounded-full bg-[rgba(240,192,64,0.12)] border-2 border-[#f0c040] flex items-center justify-center">
              <Sparkles size={24} className="text-[#f0c040]" />
            </div>
            <h3 className="text-lg font-black text-[var(--text-primary)]">
              Boost Active!
            </h3>
            <p className="text-sm text-[var(--text-muted)]">
              Your listing is now being promoted to buyers in your area.
            </p>
          </motion.div>
        ) : (
          <div className="p-4 space-y-3">
            <p className="text-xs text-[var(--text-muted)]">
              Choose a boost plan to get more visibility and sell faster
            </p>

            {BOOST_PLANS.map((plan) => (
              <motion.button
                key={plan.id}
                type="button"
                whileHover={{ scale: 1.01 }}
                whileTap={{ scale: 0.99 }}
                onClick={() => setSelected(plan.id)}
                className={`relative w-full rounded-xl border p-4 text-left transition-all duration-200 ${
                  selected === plan.id
                    ? "border-[#f0c040] bg-[rgba(240,192,64,0.08)]"
                    : "border-[var(--border)] bg-[var(--deep)] hover:border-[rgba(240,192,64,0.4)]"
                }`}
              >
                {plan.badge && (
                  <span className="absolute top-2 right-2 text-[10px] font-bold px-2 py-0.5 rounded-full bg-[#f0c040] text-[#1a1a2e]">
                    {plan.badge}
                  </span>
                )}
                <div className="flex items-start gap-3">
                  <div
                    className={`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 mt-0.5 transition-all ${
                      selected === plan.id
                        ? "border-[#f0c040] bg-[#f0c040]"
                        : "border-[var(--border)]"
                    }`}
                  >
                    {selected === plan.id && (
                      <div className="w-1.5 h-1.5 rounded-full bg-[#1a1a2e]" />
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-baseline justify-between gap-2 mb-1.5">
                      <p className="text-sm font-bold text-[var(--text-primary)]">
                        {plan.label}
                      </p>
                      <p className="text-sm font-black text-[var(--text-primary)] flex-shrink-0">
                        {currencyCode}
                        {plan.price}
                      </p>
                    </div>
                    <div className="grid grid-cols-2 gap-x-4 gap-y-1">
                      <div className="flex items-center gap-1.5">
                        <Target
                          size={11}
                          className="text-[var(--text-muted)]"
                        />
                        <span className="text-xs text-[var(--text-muted)]">
                          {plan.reach} reach
                        </span>
                      </div>
                      <div className="flex items-center gap-1.5">
                        <Eye size={11} className="text-[var(--text-muted)]" />
                        <span className="text-xs text-[var(--text-muted)]">
                          {plan.estimatedViews} views
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </motion.button>
            ))}

            <div className="grid grid-cols-3 gap-2 pt-1">
              {[
                { icon: TrendingUp, label: "Top placement" },
                { icon: Award, label: "Priority search" },
                { icon: Star, label: "Featured badge" },
              ].map((benefit) => (
                <div
                  key={benefit.label}
                  className="flex flex-col items-center gap-1.5 rounded-xl bg-[var(--deep)] border border-[var(--border)] p-2.5"
                >
                  <benefit.icon size={14} className="text-[#f0c040]" />
                  <span className="text-[10px] text-[var(--text-muted)] text-center leading-tight">
                    {benefit.label}
                  </span>
                </div>
              ))}
            </div>

            <motion.button
              type="button"
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.97 }}
              onClick={handleBoost}
              disabled={!selected || boosting}
              className="w-full flex items-center justify-center gap-2 rounded-xl py-3.5 text-sm font-bold transition-all disabled:opacity-50 disabled:cursor-not-allowed"
              style={{
                background: selected ? "#f0c040" : "var(--deep)",
                color: selected ? "#1a1a2e" : "var(--text-muted)",
              }}
            >
              {boosting ? (
                <>
                  <motion.div
                    animate={{ rotate: 360 }}
                    transition={{
                      duration: 1,
                      repeat: Infinity,
                      ease: "linear",
                    }}
                    className="w-4 h-4 border-2 border-[#1a1a2e]/30 border-t-[#1a1a2e] rounded-full"
                  />
                  Activating boost...
                </>
              ) : (
                <>
                  <Zap size={16} />
                  {selected
                    ? `Boost for ${currencyCode}${BOOST_PLANS.find((p) => p.id === selected)?.price}`
                    : "Select a plan"}
                </>
              )}
            </motion.button>
          </div>
        )}
      </motion.div>
    </motion.div>
  );
}

/* ─── Empty State ───────────────────────────────────────────────────────────── */

function EmptyState({ onCreate }: { onCreate: () => void }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
      className="flex flex-col items-center justify-center py-20 px-6 text-center"
    >
      <div className="w-20 h-20 rounded-2xl bg-[var(--card)] border border-[var(--border)] flex items-center justify-center mb-6 shadow-lg">
        <ShoppingBag size={32} className="text-[var(--text-muted)]" />
      </div>
      <h3 className="text-lg font-black text-[var(--text-primary)] mb-2">
        No Listings Yet
      </h3>
      <p className="text-sm text-[var(--text-muted)] mb-8 max-w-xs leading-relaxed">
        Create your first listing and start selling today. It only takes 2
        minutes.
      </p>
      <motion.button
        whileHover={{ scale: 1.04 }}
        whileTap={{ scale: 0.96 }}
        onClick={onCreate}
        className="flex items-center gap-2 rounded-xl bg-[#fc0000] hover:bg-[#ff4040] px-6 py-3.5 text-sm font-bold text-white transition-all shadow-lg shadow-[rgba(252,0,0,0.25)]"
      >
        <Plus size={16} />
        Create First Listing
      </motion.button>
    </motion.div>
  );
}

/* ─── Status Sheet ──────────────────────────────────────────────────────────── */

const STATUS_CFG: Record<
  ListingStatus,
  { label: string; color: string; bg: string; icon: LucideIcon; desc: string }
> = {
  active: {
    label: "Active",
    color: "#22c55e",
    bg: "rgba(34,197,94,0.1)",
    icon: CheckCircle2,
    desc: "Visible to buyers",
  },
  paused: {
    label: "Paused",
    color: "#f59e0b",
    bg: "rgba(245,158,11,0.1)",
    icon: Pause,
    desc: "Hidden from search",
  },
  draft: {
    label: "Draft",
    color: "#6b7280",
    bg: "rgba(107,114,128,0.1)",
    icon: FileText,
    desc: "Not published yet",
  },
  sold: {
    label: "Sold",
    color: "#6366f1",
    bg: "rgba(99,102,241,0.1)",
    icon: ShoppingBag,
    desc: "Marked as sold",
  },
  deleted: {
    label: "Deleted",
    color: "#ef4444",
    bg: "rgba(239,68,68,0.1)",
    icon: X,
    desc: "Listing removed",
  },
};

function StatusSheet({
  listing,
  onClose,
  onStatusChange,
  onEdit,
  onDelete,
  currencyCode,
}: {
  listing: Listing;
  onClose: () => void;
  onStatusChange: (id: string, status: ListingStatus) => void;
  onEdit: (id: string) => void;
  onDelete: (id: string) => void;
  currencyCode: string;
}) {
  const [confirmDelete, setConfirmDelete] = useState(false);
  const cover = listing.images.find((i) => i.isCover) ?? listing.images[0];
  const cfg = STATUS_CFG[listing.status];

  return (
    <motion.div
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center sm:p-4"
      style={{ background: "rgba(0,0,0,0.55)", backdropFilter: "blur(4px)" }}
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      onClick={onClose}
    >
      <motion.div
        className="w-full sm:max-w-md rounded-t-3xl sm:rounded-2xl overflow-hidden"
        style={{ background: "var(--card)", border: "1px solid var(--border)" }}
        initial={{ y: "100%" }}
        animate={{ y: 0 }}
        exit={{ y: "100%" }}
        transition={{ type: "spring", stiffness: 340, damping: 32 }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Handle (mobile) */}
        <div className="flex justify-center pt-3 pb-1 sm:hidden">
          <div
            className="w-9 h-1 rounded-full"
            style={{ background: "var(--border)" }}
          />
        </div>

        {/* Header */}
        <div
          className="flex items-center justify-between px-5 pt-4 pb-3"
          style={{ borderBottom: "1px solid var(--border)" }}
        >
          <p
            className="font-black text-sm"
            style={{ color: "var(--text-primary)" }}
          >
            Manage Listing
          </p>
          <button
            onClick={onClose}
            style={{
              color: "var(--text-muted)",
              background: "none",
              border: "none",
              cursor: "pointer",
              padding: 4,
            }}
          >
            <X size={18} />
          </button>
        </div>

        {/* Listing preview */}
        <div
          className="flex items-center gap-3 px-5 py-4"
          style={{ borderBottom: "1px solid var(--border)" }}
        >
          {cover ? (
            <img
              src={cover.url}
              alt={listing.title}
              className="w-14 h-14 rounded-xl object-cover shrink-0"
            />
          ) : (
            <div
              className="w-14 h-14 rounded-xl shrink-0 flex items-center justify-center"
              style={{ background: "var(--deep)" }}
            >
              <Package size={22} style={{ color: "var(--text-muted)" }} />
            </div>
          )}
          <div className="flex-1 min-w-0">
            <p
              className="text-sm font-bold truncate"
              style={{ color: "var(--text-primary)" }}
            >
              {listing.title}
            </p>
            <div className="flex items-center gap-2 mt-1">
              <span className="text-sm font-black" style={{ color: "#fc0000" }}>
                {currencyCode}
                {listing.price.toLocaleString()}
              </span>
              <span
                className="text-[10px] font-bold px-2 py-0.5 rounded-full flex items-center gap-1"
                style={{ background: cfg.bg, color: cfg.color }}
              >
                <cfg.icon size={9} />
                {cfg.label}
              </span>
            </div>
            <div
              className="flex items-center gap-3 mt-0.5"
              style={{ color: "var(--text-muted)" }}
            >
              <span className="flex items-center gap-1 text-[10px]">
                <Eye size={9} />
                {listing.views} views
              </span>
              <span className="flex items-center gap-1 text-[10px]">
                <MessageCircle size={9} />
                {listing.enquiries} enquiries
              </span>
            </div>
          </div>
        </div>

        {/* Status selector */}
        <div
          className="px-5 py-4"
          style={{ borderBottom: "1px solid var(--border)" }}
        >
          <p
            className="text-xs font-bold uppercase tracking-wider mb-3"
            style={{ color: "var(--text-muted)" }}
          >
            Change Status
          </p>

          {listing.status === "draft" ? (
            <div
              className="rounded-xl p-4 text-xs leading-relaxed"
              style={{
                background: "rgba(99,102,241,0.06)",
                border: "1px solid rgba(99,102,241,0.25)",
                color: "var(--text-muted)",
              }}
            >
              <p
                className="font-bold mb-2"
                style={{ color: "var(--text-primary)", fontSize: 13 }}
              >
                Draft — pending review
              </p>
              <p>
                The seller can change the product status from{" "}
                <strong style={{ color: "var(--text-primary)" }}>Active</strong>{" "}
                to{" "}
                <strong style={{ color: "var(--text-primary)" }}>Paused</strong>{" "}
                and vice versa. The seller can also change the product status
                from{" "}
                <strong style={{ color: "var(--text-primary)" }}>Active</strong>{" "}
                to{" "}
                <strong style={{ color: "var(--text-primary)" }}>Sold</strong>.
              </p>
            </div>
          ) : listing.status === "sold" ? (
            <div
              className="rounded-xl p-4 text-xs leading-relaxed"
              style={{
                background: "rgba(240,192,64,0.06)",
                border: "1px solid rgba(240,192,64,0.25)",
                color: "var(--text-muted)",
              }}
            >
              <p
                className="font-bold mb-1"
                style={{ color: "#f0c040", fontSize: 13 }}
              >
                Sold — final status
              </p>
              <p>
                This listing has been marked as sold and is no longer visible to
                buyers.
              </p>
            </div>
          ) : (
            <div className="flex flex-col gap-2">
              {(STATUS_TRANSITIONS[listing.status] ?? []).map((s) => {
                const c = STATUS_CFG[s];
                return (
                  <motion.button
                    key={s}
                    whileTap={{ scale: 0.96 }}
                    onClick={() => onStatusChange(listing.id, s)}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 12,
                      padding: "12px 14px",
                      borderRadius: 12,
                      cursor: "pointer",
                      textAlign: "left",
                      border: `1.5px solid ${c.color}40`,
                      background: c.bg,
                      width: "100%",
                    }}
                  >
                    <div
                      style={{
                        width: 36,
                        height: 36,
                        borderRadius: 10,
                        flexShrink: 0,
                        background: c.color,
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                      }}
                    >
                      <c.icon size={16} color="#fff" />
                    </div>
                    <div>
                      <p
                        style={{
                          fontSize: 13,
                          fontWeight: 700,
                          color: c.color,
                          lineHeight: 1.2,
                        }}
                      >
                        {STATUS_CHANGE_LABEL[s]}
                      </p>
                      <p
                        style={{
                          fontSize: 11,
                          color: "var(--text-muted)",
                          marginTop: 2,
                        }}
                      >
                        {c.desc}
                      </p>
                    </div>
                  </motion.button>
                );
              })}
            </div>
          )}
        </div>

        {/* Actions */}
        <div className="px-5 py-4 flex gap-2">
          {listing.status === "draft" && (
            <motion.button
              whileTap={{ scale: 0.97 }}
              onClick={() => {
                onEdit(listing.id);
                onClose();
              }}
              className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-bold"
              style={{
                background: "var(--bg)",
                border: "1px solid var(--border)",
                color: "var(--text-primary)",
                cursor: "pointer",
              }}
            >
              <Edit2 size={14} />
              Edit Listing
            </motion.button>
          )}

          {!confirmDelete ? (
            <motion.button
              whileTap={{ scale: 0.97 }}
              onClick={() => setConfirmDelete(true)}
              className="flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold"
              style={{
                background: "rgba(239,68,68,0.08)",
                border: "1px solid rgba(239,68,68,0.25)",
                color: "#ef4444",
                cursor: "pointer",
              }}
            >
              <Trash2 size={14} />
            </motion.button>
          ) : (
            <motion.button
              whileTap={{ scale: 0.97 }}
              onClick={() => {
                onDelete(listing.id);
                onClose();
              }}
              className="flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold"
              style={{
                background: "#ef4444",
                color: "#fff",
                border: "none",
                cursor: "pointer",
              }}
              initial={{ scale: 0.9 }}
              animate={{ scale: 1 }}
            >
              <Trash2 size={14} />
              Confirm
            </motion.button>
          )}
        </div>
      </motion.div>
    </motion.div>
  );
}

/* ─── Dashboard Root ────────────────────────────────────────────────────────── */

const FILTERS: { id: ListingStatus | "all"; label: string }[] = [
  { id: "all", label: "all" },
  { id: "active", label: "Active" },
  { id: "sold", label: "Sold" },
  { id: "draft", label: "Drafts" },
  { id: "paused", label: "Paused" },
];

interface MarketplaceDashboardProps {
  onCreateListing: () => void;
}

export function MarketplaceDashboard({
  onCreateListing,
}: MarketplaceDashboardProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const {
    listings: apiListings,
    stats: apiStats,
    isLoading,
  } = useAppSelector((s) => s.marketplaceMyListings);
  const currencyCode = useAppSelector((s) => s.generalSetting.currencyCode);

  const [activeFilter, setActiveFilter] = useState<ListingStatus | "all">(
    "all",
  );
  const [boostTarget, setBoostTarget] = useState<Listing | null>(null);
  const [selectedListing, setSelectedListing] = useState<Listing | null>(null);

  /* On mount: fetch "All" to populate stats */
  useEffect(() => {
    dispatch(fetchMyListings("all"));
  }, [dispatch]);

  /* Map raw API listings → UI Listing shape */
  const listings = apiListings.map(mapApiToListing);

  /* Tab change: call API with the matching status param */
  const handleTabChange = (tab: ListingStatus | "all") => {
    setActiveFilter(tab);
    dispatch(fetchMyListings(TAB_TO_STATUS[tab]));
  };

  const handleAction = (action: string, id: string) => {
    if (action === "boost") {
      const listing = listings.find((l) => l.id === id);
      if (listing) setBoostTarget(listing);
    }
  };

  const handleStatusChange = async (id: string, newStatus: ListingStatus) => {
    const statusValue = STATUS_API_VALUE[newStatus];
    if (statusValue == null) return;
    setSelectedListing(null);
    const channelId = Cookies.get("channel_id") ?? "";
    const form = new FormData();
    form.append("listing_id", id);
    form.append("channel_id", channelId);
    form.append("status", String(statusValue));
    try {
      await apiClient.post(API_ENDPOINTS.CLASSIFIED.EDIT_LISTING, form, {
        headers: { "Content-Type": "multipart/form-data" },
      });
    } catch {}
    dispatch(fetchMyListings(TAB_TO_STATUS[activeFilter]));
  };

  const handleDelete = async (id: string) => {
    setSelectedListing(null);
    const channelId = Cookies.get("channel_id") ?? "";
    try {
      await apiClient.post(API_ENDPOINTS.CLASSIFIED.DELETE_LISTING, {
        listing_id: Number(id),
        channel_id: channelId,
      });
    } catch {}
    dispatch(fetchMyListings("all"));
  };

  /* Stats use server values; enquiries not in API so sum locally */
  const stats = {
    total: apiStats.totalListings,
    active: apiStats.active,
    sold: apiStats.sold,
    draft: apiStats.draft,
    views: apiStats.views,
    enquiries: listings.reduce((acc, l) => acc + l.enquiries, 0),
  };

  if (isLoading && listings.length === 0 && apiStats.totalListings === 0)
    return <DashboardSkeleton />;

  const filtered = listings; /* API already returns the filtered set */

  return (
    <div className="min-h-full bg-[var(--bg)]">
      {/* Page header */}
      <div className="px-4 pt-6 pb-2 flex items-center justify-between gap-3">
        <div>
          <h1 className="text-xl font-black text-[var(--text-primary)]">
            My Listings
          </h1>
          <p className="text-xs text-[var(--text-muted)] mt-0.5">
            {stats.total} total · {stats.active} active
          </p>
        </div>
        {/* <motion.button
          whileHover={{ scale: 1.04 }}
          whileTap={{ scale: 0.96 }}
          onClick={onCreateListing}
          className="flex items-center gap-1.5 rounded-xl bg-[#fc0000] hover:bg-[#ff4040] active:bg-[#c80000] px-4 py-2.5 text-sm font-bold text-white transition-all shadow-lg shadow-[rgba(252,0,0,0.2)] flex-shrink-0"
        >
          <Plus size={16} />
          <span className="hidden xs:inline">New Listing</span>
        </motion.button> */}
      </div>

      {/* Stats grid */}
      <div className="px-4 pt-4 pb-2 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
        <StatCard label="Total" value={stats.total} icon={Package} delay={0} />
        <StatCard
          label="Active"
          value={stats.active}
          icon={BarChart2}
          accent="#22c55e"
          delay={0.05}
        />
        <StatCard
          label="Sold"
          value={stats.sold}
          icon={CheckCircle2}
          accent="#f0c040"
          delay={0.1}
        />
        <StatCard
          label="Drafts"
          value={stats.draft}
          icon={FileText}
          delay={0.15}
        />
        <StatCard
          label="Total Views"
          value={
            stats.views >= 1000
              ? `${(stats.views / 1000).toFixed(1)}k`
              : stats.views
          }
          sub="All time"
          icon={Eye}
          accent="#fc0000"
          delay={0.2}
        />
        <StatCard
          label="Enquiries"
          value={stats.enquiries}
          sub="All time"
          icon={MessageCircle}
          accent="#3c096c"
          delay={0.25}
        />
      </div>

      {/* Filters */}
      <div className="px-4 pt-3 pb-1 flex gap-2 overflow-x-auto scrollbar-hide">
        {FILTERS.map((filter) => {
          const statCounts: Record<string, number> = {
            all: apiStats.totalListings,
            active: apiStats.active,
            sold: apiStats.sold,
            draft: apiStats.draft,
            paused: apiStats.paused,
          };
          const count = statCounts[filter.id] ?? 0;
          return (
            <motion.button
              key={filter.id}
              type="button"
              whileHover={{ scale: 1.03 }}
              whileTap={{ scale: 0.97 }}
              onClick={() => handleTabChange(filter.id)}
              className={`flex items-center gap-1.5 flex-shrink-0 rounded-full px-3.5 py-1.5 text-xs font-semibold transition-all duration-200 ${
                activeFilter === filter.id
                  ? "bg-[#fc0000] text-white shadow-md shadow-[rgba(252,0,0,0.25)]"
                  : "bg-[var(--card)] border border-[var(--border)] text-[var(--text-secondary)] hover:border-[rgba(252,0,0,0.3)]"
              }`}
            >
              {filter.label}
              <span
                className={`text-[10px] font-bold px-1 py-0.5 rounded-full ${
                  activeFilter === filter.id
                    ? "bg-white/20 text-white"
                    : "bg-[var(--deep)] text-[var(--text-muted)]"
                }`}
              >
                {count}
              </span>
            </motion.button>
          );
        })}
      </div>

      {/* Listing grid */}
      <div className="px-4 py-4">
        {isLoading ? (
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
            {Array.from({ length: 6 }).map((_, i) => (
              <ListingCardSkeleton key={i} />
            ))}
          </div>
        ) : filtered.length === 0 ? (
          <EmptyState onCreate={onCreateListing} />
        ) : (
          <motion.div
            layout
            className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3"
          >
            <AnimatePresence>
              {filtered.map((listing) => (
                <ListingCard
                  key={listing.id}
                  listing={listing}
                  onAction={handleAction}
                  onSelect={() => setSelectedListing(listing)}
                  currencyCode={currencyCode}
                />
              ))}
            </AnimatePresence>
          </motion.div>
        )}
      </div>

      {/* Boost Modal */}
      <AnimatePresence>
        {boostTarget && (
          <BoostModal
            listing={boostTarget}
            onClose={() => setBoostTarget(null)}
            currencyCode={currencyCode}
          />
        )}
      </AnimatePresence>

      {/* Status Sheet */}
      <AnimatePresence>
        {selectedListing && (
          <StatusSheet
            listing={selectedListing}
            onClose={() => setSelectedListing(null)}
            onStatusChange={handleStatusChange}
            currencyCode={currencyCode}
            onEdit={(id) => {
              const l = listings.find((x) => x.id === id);
              if (l) {
                const slug = `${slugify(l.title)}-${l.id}`;
                router.push(`/marketplace/create?edit=${slug}`);
              }
            }}
            onDelete={handleDelete}
          />
        )}
      </AnimatePresence>
    </div>
  );
}
