"use client";

import { useState, useEffect, useRef, useMemo, useCallback } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { privateListingsApi, categoryApi, brandApi } from "@/lib/api";
import { useSnackbar } from "@/context/SnackbarContext";
import useAuth from "@/hooks/useAuth";
import {
  ImagePlus,
  X,
  Package,
  Video,
  FileText,
  Upload,
  Truck,
  Tag,
  CheckCircle2,
  Camera,
  Send,
} from "lucide-react";
import PageHero from "@/components/customer/PageHero";

const STEPS = [
  { id: 1, label: "Details", icon: Package },
  { id: 2, label: "Photos", icon: Camera },
  { id: 3, label: "Price", icon: Tag },
  { id: 4, label: "Ship & Post", icon: Send },
];

const CONDITIONS = [
  { value: "new", label: "New" },
  { value: "used", label: "Used" },
  { value: "refurbished", label: "Refurbished" },
];

const inputClass = (hasError) =>
  `w-full px-3.5 sm:px-4 py-2.5 sm:py-3 rounded-xl border bg-white text-gray-900 text-sm sm:text-[15px] placeholder:text-gray-400 transition focus:outline-none focus:ring-2 focus:ring-[#1790d7]/25 focus:border-[#1790d7] ${
    hasError ? "border-red-400" : "border-gray-200 hover:border-gray-300"
  }`;

function useObjectUrl(file) {
  const url = useMemo(() => (file ? URL.createObjectURL(file) : null), [file]);
  useEffect(() => {
    return () => {
      if (url) URL.revokeObjectURL(url);
    };
  }, [url]);
  return url;
}

function useObjectUrls(files) {
  const urls = useMemo(() => files.map((f) => URL.createObjectURL(f)), [files]);
  useEffect(() => {
    return () => {
      urls.forEach((u) => URL.revokeObjectURL(u));
    };
  }, [urls]);
  return urls;
}

function Section({ title, subtitle, icon: Icon, children, className = "" }) {
  return (
    <section className={`bg-white rounded-2xl border border-gray-200/80 shadow-sm ${className}`}>
      <div className="flex items-center gap-3 px-4 sm:px-5 py-3.5 border-b border-gray-100">
        {Icon && (
          <span className="w-9 h-9 rounded-lg bg-[#1790d7]/10 text-[#1790d7] flex items-center justify-center shrink-0">
            <Icon className="w-4.5 h-4.5 w-[18px] h-[18px]" />
          </span>
        )}
        <div className="min-w-0">
          <h3 className="font-semibold text-gray-900 text-[15px] sm:text-base leading-tight">{title}</h3>
          {subtitle && <p className="text-xs sm:text-sm text-gray-500 mt-0.5 truncate">{subtitle}</p>}
        </div>
      </div>
      <div className="p-4 sm:p-5 space-y-4">{children}</div>
    </section>
  );
}

function Field({ label, required, hint, error, children, className = "" }) {
  return (
    <div className={className}>
      <label className="flex items-baseline gap-1 mb-1.5">
        <span className="text-sm font-medium text-gray-800">{label}</span>
        {required && <span className="text-red-500 text-xs">*</span>}
      </label>
      {hint && <p className="text-xs text-gray-500 mb-1.5">{hint}</p>}
      {children}
      {error && <p className="mt-1 text-sm text-red-500">{error}</p>}
    </div>
  );
}

function ThumbPreview({ file, onRemove }) {
  const url = useObjectUrl(file);
  if (!url) return null;
  return (
    <div className="relative inline-block">
      <img
        src={url}
        alt="Main product"
        className="w-full aspect-square max-w-[180px] object-cover rounded-xl border border-gray-200"
      />
      <button
        type="button"
        onClick={onRemove}
        className="absolute -top-2 -right-2 w-8 h-8 bg-red-500 text-white rounded-full flex items-center justify-center shadow"
        aria-label="Remove main photo"
      >
        <X className="w-4 h-4" />
      </button>
    </div>
  );
}

function GalleryPreview({ files, onRemove }) {
  const urls = useObjectUrls(files);
  return (
    <div className="flex flex-wrap gap-2.5">
      {files.map((file, i) => (
        <div key={`${file.name}-${file.size}-${i}`} className="relative w-[72px] sm:w-24">
          <div className="relative w-full aspect-square rounded-xl overflow-hidden border border-gray-200 bg-gray-50">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={urls[i]} alt="" className="w-full h-full object-cover" />
            <button
              type="button"
              onClick={() => onRemove(i)}
              className="absolute top-1 right-1 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center"
              aria-label="Remove photo"
            >
              <X className="w-3 h-3" />
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}

export default function SellItemForm() {
  const router = useRouter();
  const { user } = useAuth();
  const { showSuccess, showError } = useSnackbar();
  const formTopRef = useRef(null);
  const [config, setConfig] = useState(null);
  const [categories, setCategories] = useState([]);
  const [brands, setBrands] = useState([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({
    name: "",
    description: "",
    short_description: "",
    category_id: "",
    brand_id: "",
    price: "",
    compare_at_price: "",
    quantity: "1",
    condition: "new",
    status: "published",
    video_url: "",
    shipping_mode: "customer_pays",
    shipping_cost_cached: "",
  });
  const [thumbnail, setThumbnail] = useState(null);
  const [images, setImages] = useState([]);
  const [documents, setDocuments] = useState([]);
  const [documentLabels, setDocumentLabels] = useState([]);
  const [errors, setErrors] = useState({});
  const [showExtras, setShowExtras] = useState(false);
  const isPrivateSeller = !!user?.is_private_seller;

  useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        const [configRes, categoriesRes, brandsRes] = await Promise.all([
          privateListingsApi.config(),
          categoryApi.list(true),
          brandApi.list(),
        ]);
        if (cancelled) return;
        const cfg = configRes.config;
        setConfig(cfg);
        if (cfg?.plan_required || cfg?.remaining === 0) {
          setForm((p) => ({ ...p, status: "draft" }));
        }
        const flattenCategories = (arr) => {
          const out = [];
          (arr || []).forEach((c) => {
            out.push({ ...c, level: 0 });
            (c.children || []).forEach((ch) => {
              out.push({ ...ch, level: 1 });
              (ch.children || []).forEach((ch2) => out.push({ ...ch2, level: 2 }));
            });
          });
          return out;
        };
        setCategories(flattenCategories(categoriesRes.categories || []));
        setBrands(brandsRes.brands || []);
      } catch (err) {
        if (!cancelled) showError?.(err?.message || "Failed to load");
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [showError]);

  const formatPriceWithCommas = useCallback((val) => {
    if (val == null || val === "") return "";
    const s = String(val).replace(/,/g, "");
    const parts = s.split(".");
    const int = (parts[0] || "0").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    const dec = parts[1] != null ? "." + parts[1].replace(/\D/g, "").slice(0, 2) : "";
    return int + dec;
  }, []);

  const sanitizePriceInput = useCallback((value) => {
    let v = String(value).replace(/,/g, "").replace(/[^\d.]/g, "");
    const parts = v.split(".");
    if (parts.length > 1) v = parts[0] + "." + parts.slice(1).join("").slice(0, 2);
    return v;
  }, []);

  const handleChange = useCallback(
    (e) => {
      const { name, value, type, checked } = e.target;
      if (name === "price" || name === "compare_at_price" || name === "shipping_cost_cached") {
        setForm((p) => ({ ...p, [name]: sanitizePriceInput(value) }));
        setErrors((p) => ({ ...p, [name]: "" }));
        return;
      }
      if (name === "quantity" && !isPrivateSeller) {
        const n = Math.min(1, Math.max(0, parseInt(value, 10) || 0));
        setForm((p) => ({ ...p, quantity: String(n || 1) }));
        setErrors((p) => ({ ...p, quantity: "" }));
        return;
      }
      setForm((p) => ({ ...p, [name]: type === "checkbox" ? checked : value }));
      setErrors((p) => ({ ...p, [name]: "" }));
    },
    [isPrivateSeller, sanitizePriceInput]
  );

  const handleThumbnailAdd = (e) => {
    const file = e.target.files?.[0];
    if (file) setThumbnail(file);
    e.target.value = "";
  };

  const handleImageAdd = (e) => {
    const files = Array.from(e.target.files || []);
    setImages((p) => [...p, ...files].slice(0, 12));
    e.target.value = "";
  };

  const removeImage = (idx) => setImages((p) => p.filter((_, i) => i !== idx));

  const handleDocumentAdd = (e) => {
    const files = Array.from(e.target.files || []);
    setDocuments((p) => [...p, ...files].slice(0, 5));
    setDocumentLabels((p) => [...p, ...files.map((f) => f.name)]);
    e.target.value = "";
  };

  const removeDocument = (idx) => {
    setDocuments((p) => p.filter((_, i) => i !== idx));
    setDocumentLabels((p) => p.filter((_, i) => i !== idx));
  };

  const updateDocumentLabel = (idx, label) => {
    setDocumentLabels((p) => {
      const n = [...p];
      n[idx] = label;
      return n;
    });
  };

  const isValidUrl = (v) => {
    if (!v) return true;
    try {
      new URL(v);
      return true;
    } catch {
      return false;
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const nextErrors = {};
    if (!form.name?.trim()) nextErrors.name = "Add a title for your item";
    if (!form.category_id) nextErrors.category_id = "Pick a category";
    const price = parseFloat(form.price);
    if (isNaN(price) || price < 0) nextErrors.price = "Enter a valid price";
    const qty = parseInt(form.quantity, 10);
    const isDraft = form.status === "draft";
    if (isNaN(qty) || qty < 0 || (!isDraft && qty < 1)) {
      nextErrors.quantity = isDraft ? "Quantity must be 0 or more" : "Quantity must be at least 1";
    }
    if (!isValidUrl(form.video_url?.trim())) nextErrors.video_url = "Enter a valid URL (https://…)";
    if (!isPrivateSeller && qty > 1) nextErrors.quantity = "Quantity is limited to 1";
    const shippingMode = form.shipping_mode === "free_shipping" ? "free_shipping" : "customer_pays";
    if (shippingMode === "customer_pays") {
      const shipCost = parseFloat(form.shipping_cost_cached);
      if (isNaN(shipCost) || shipCost < 0) nextErrors.shipping_cost_cached = "Enter shipping price in PKR";
    }
    setErrors(nextErrors);
    if (Object.keys(nextErrors).length) {
      formTopRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
      showError?.(Object.values(nextErrors)[0]);
      return;
    }

    setSubmitting(true);
    try {
      const overFree = !!(config?.plan_required || config?.remaining === 0);
      const payload = {
        name: form.name.trim(),
        description: form.description?.trim() || null,
        short_description: form.short_description?.trim() || null,
        category_id: parseInt(form.category_id, 10),
        brand_id: form.brand_id ? parseInt(form.brand_id, 10) : null,
        price,
        compare_at_price: form.compare_at_price ? parseFloat(form.compare_at_price) : null,
        quantity: qty,
        condition: form.condition || "new",
        status: overFree || form.status === "draft" ? "draft" : "published",
        video_url: form.video_url?.trim() || null,
        shipping_mode: shippingMode,
        shipping_cost_cached: shippingMode === "customer_pays" ? parseFloat(form.shipping_cost_cached) : 0,
      };
      if (thumbnail) payload.thumbnail = thumbnail;
      if (images.length) payload.images = images;
      if (documents.length) {
        payload.documents = documents;
        payload.document_labels = documentLabels;
      }
      await privateListingsApi.create(payload);
      showSuccess?.(
        form.status === "draft" ? "Draft saved. Finish it anytime from My Listings." : "Listing created successfully!"
      );
      router.replace("/customer/listings");
    } catch (err) {
      const apiErrors = err?.data?.errors || {};
      const next = {};
      Object.keys(apiErrors).forEach((k) => {
        next[k] = Array.isArray(apiErrors[k]) ? apiErrors[k][0] : apiErrors[k];
      });
      setErrors((p) => ({ ...p, ...next }));
      showError?.(err?.data?.message || err?.message || "Failed to create listing");
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="w-full py-8 space-y-4 animate-pulse">
        <div className="h-20 bg-gray-100 rounded-2xl" />
        <div className="grid lg:grid-cols-12 gap-4">
          <div className="lg:col-span-7 h-64 bg-gray-100 rounded-2xl" />
          <div className="lg:col-span-5 h-64 bg-gray-100 rounded-2xl" />
        </div>
      </div>
    );
  }

  if (config && !config.enabled) {
    return (
      <div className="w-full max-w-lg mx-auto py-12">
        <div className="bg-amber-50 border border-amber-200 rounded-2xl p-6 text-center">
          <p className="text-amber-900 font-semibold">Selling is temporarily unavailable</p>
          <p className="text-sm text-amber-800 mt-2">Private listings are currently disabled.</p>
          <Link href="/customer/dashboard" className="inline-block mt-4 text-[#1790d7] font-semibold text-sm hover:underline">
            Back to Dashboard
          </Link>
        </div>
      </div>
    );
  }

  const atHardLimit = config && config.used >= (config.max_limit || config.limit);
  if (atHardLimit) {
    return (
      <div className="w-full max-w-lg mx-auto py-12">
        <div className="bg-white border border-gray-200 rounded-2xl p-6 text-center shadow-sm">
          <p className="text-gray-900 font-semibold">Listing limit reached</p>
          <p className="text-sm text-gray-600 mt-2">You have used all {config.max_limit || config.limit} listing slots.</p>
          <div className="flex flex-wrap justify-center gap-3 mt-4 text-sm">
            <Link href="/customer/listings" className="text-[#1790d7] font-semibold hover:underline">
              My Listings
            </Link>
            <Link href="/contact" className="text-gray-600 hover:underline">
              Contact Support
            </Link>
          </div>
        </div>
      </div>
    );
  }

  const overFreeLimit = !!(config?.plan_required || config?.remaining === 0);
  const listingFee = config?.listing_fee;
  const slotsLeft = config?.remaining ?? "—";
  const slotsTotal = config?.limit ?? "—";
  const submitLabel = submitting
    ? "Saving…"
    : form.status === "draft" || overFreeLimit
      ? "Save draft"
      : "Publish listing";

  return (
    <div className="w-full pb-24 sm:pb-6" ref={formTopRef}>
      <PageHero
        title="Sell an Item"
        description="Fill in the basics, add photos, set price & shipping — then publish."
        illustration="sell"
        guide={
          config
            ? `${slotsLeft} of ${slotsTotal} listing slots left${config.has_plan ? "" : ` (${config.free_limit || 3} free)`}.`
            : undefined
        }
      />

      {/* Steps — full width */}
      <ol className="mt-4 mb-5 grid grid-cols-2 sm:grid-cols-4 gap-2 w-full">
        {STEPS.map((s) => {
          const Icon = s.icon;
          return (
            <li
              key={s.id}
              className="flex items-center gap-2 px-3 py-2.5 rounded-xl bg-white border border-gray-200/80 text-sm"
            >
              <span className="w-7 h-7 rounded-lg bg-[#1790d7]/10 text-[#1790d7] flex items-center justify-center shrink-0">
                <Icon className="w-3.5 h-3.5" />
              </span>
              <span className="font-medium text-gray-800 truncate">
                <span className="text-gray-400 mr-1">{s.id}.</span>
                {s.label}
              </span>
            </li>
          );
        })}
      </ol>

      {overFreeLimit && (
        <div className="mb-4 p-3.5 bg-amber-50 border border-amber-200 rounded-xl text-sm text-amber-900 w-full">
          Free live slots are full. This listing will save as a <strong>draft</strong>
          {listingFee != null ? ` — pay Rs ${listingFee} from My Listings to go live` : ""}.
        </div>
      )}

      {Object.keys(errors).some((k) => errors[k]) && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700 w-full">
          Please fix the highlighted fields below before submitting.
        </div>
      )}

      <form id="sell-item-form" onSubmit={handleSubmit} className="w-full">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-4 lg:gap-5 w-full">
          {/* Left: details + photos */}
          <div className="lg:col-span-7 xl:col-span-8 space-y-4">
            <Section title="Item details" subtitle="What buyers see first" icon={Package}>
              <Field label="Title" required error={errors.name} hint="Be specific — brand, model, key details">
                <input
                  type="text"
                  name="name"
                  value={form.name}
                  onChange={handleChange}
                  placeholder="e.g. Samsung Galaxy A54 128GB — Excellent condition"
                  className={inputClass(!!errors.name)}
                  autoComplete="off"
                />
              </Field>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <Field label="Category" required error={errors.category_id}>
                  <select
                    name="category_id"
                    value={form.category_id}
                    onChange={handleChange}
                    className={inputClass(!!errors.category_id)}
                  >
                    <option value="">Select category</option>
                    {categories.map((c) => (
                      <option key={c.id} value={c.id}>
                        {"—".repeat(c.level || 0)} {c.name}
                      </option>
                    ))}
                  </select>
                </Field>
                <Field label="Brand (Optional)">
                  <select name="brand_id" value={form.brand_id} onChange={handleChange} className={inputClass(false)}>
                    <option value="">Select brand</option>
                    {brands.map((b) => (
                      <option key={b.id} value={b.id}>
                        {b.name}
                      </option>
                    ))}
                  </select>
                </Field>
              </div>

              <Field label="Condition">
                <div className="grid grid-cols-3 gap-2">
                  {CONDITIONS.map((opt) => {
                    const active = form.condition === opt.value;
                    return (
                      <button
                        key={opt.value}
                        type="button"
                        onClick={() => setForm((p) => ({ ...p, condition: opt.value }))}
                        className={`py-2.5 px-2 rounded-xl border text-sm font-semibold transition ${
                          active
                            ? "border-[#1790d7] bg-[#1790d7]/10 text-[#1277b8]"
                            : "border-gray-200 text-gray-600 hover:border-gray-300"
                        }`}
                      >
                        {opt.label}
                      </button>
                    );
                  })}
                </div>
              </Field>

              <Field label="Short summary" hint="Optional · shown on listing cards">
                <input
                  type="text"
                  name="short_description"
                  value={form.short_description}
                  onChange={handleChange}
                  placeholder="One short line"
                  maxLength={160}
                  className={inputClass(false)}
                />
              </Field>

              <Field label="Description" hint="Specs, what’s included, any flaws">
                <textarea
                  name="description"
                  value={form.description}
                  onChange={handleChange}
                  rows={5}
                  placeholder="Describe your item…"
                  className={`${inputClass(false)} resize-y min-h-[120px]`}
                />
              </Field>
            </Section>

            <Section title="Photos" subtitle="Clear photos sell faster" icon={Camera}>
              <div className="grid grid-cols-1 sm:grid-cols-[180px_1fr] gap-5">
                <div>
                  <p className="text-sm font-medium text-gray-800 mb-2">Main photo</p>
                  {thumbnail ? (
                    <ThumbPreview file={thumbnail} onRemove={() => setThumbnail(null)} />
                  ) : (
                    <label className="flex flex-col items-center justify-center w-full max-w-[180px] aspect-square border-2 border-dashed border-[#1790d7]/35 rounded-xl cursor-pointer hover:bg-[#1790d7]/5 bg-[#1790d7]/[0.03] transition">
                      <Upload className="w-7 h-7 text-[#1790d7] mb-1" />
                      <span className="text-xs font-semibold text-gray-800">Upload</span>
                      <span className="text-[10px] text-gray-500">Recommended</span>
                      <input type="file" accept="image/*" className="hidden" onChange={handleThumbnailAdd} />
                    </label>
                  )}
                </div>
                <div className="min-w-0">
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-sm font-medium text-gray-800">Gallery</p>
                    <span className="text-xs text-gray-500">{images.length}/12</span>
                  </div>
                  <div className="flex flex-wrap gap-2.5 items-start">
                    <GalleryPreview files={images} onRemove={removeImage} />
                    {images.length < 12 && (
                      <label className="w-[72px] sm:w-24 aspect-square rounded-xl border-2 border-dashed border-gray-300 flex flex-col items-center justify-center cursor-pointer hover:border-[#1790d7] hover:bg-[#1790d7]/5 transition">
                        <ImagePlus className="w-5 h-5 text-gray-400" />
                        <span className="text-[10px] text-gray-500 mt-1">Add</span>
                        <input type="file" accept="image/*" multiple className="hidden" onChange={handleImageAdd} />
                      </label>
                    )}
                  </div>
                  <p className="text-xs text-gray-500 mt-2">Add angles, box, and any wear.</p>
                </div>
              </div>

              <button
                type="button"
                onClick={() => setShowExtras((v) => !v)}
                className="text-sm font-medium text-[#1790d7] hover:underline"
              >
                {showExtras ? "Hide optional extras" : "+ Video or documents (optional)"}
              </button>

              {showExtras && (
                <div className="space-y-4 pt-3 border-t border-gray-100">
                  <Field label="Video link" error={errors.video_url} hint="YouTube or Vimeo">
                    <div className="relative">
                      <Video className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                      <input
                        type="url"
                        name="video_url"
                        value={form.video_url}
                        onChange={handleChange}
                        placeholder="https://…"
                        className={`${inputClass(!!errors.video_url)} pl-10`}
                      />
                    </div>
                  </Field>
                  <div>
                    <p className="text-sm font-medium text-gray-800 mb-1 flex items-center gap-1.5">
                      <FileText className="w-4 h-4 text-gray-500" />
                      Documents
                    </p>
                    <p className="text-xs text-gray-500 mb-2">PDF / DOC · max 5</p>
                    <div className="space-y-2">
                      {documents.map((file, i) => (
                        <div
                          key={i}
                          className="flex flex-col sm:flex-row sm:items-center gap-2 p-3 bg-gray-50 rounded-xl"
                        >
                          <input
                            type="text"
                            value={documentLabels[i] || ""}
                            onChange={(e) => updateDocumentLabel(i, e.target.value)}
                            placeholder="Label"
                            className="flex-1 px-3 py-2 rounded-lg border border-gray-200 text-sm bg-white"
                          />
                          <div className="flex items-center gap-2 min-w-0">
                            <span className="text-xs text-gray-500 truncate flex-1">{file.name}</span>
                            <button
                              type="button"
                              onClick={() => removeDocument(i)}
                              className="p-1.5 text-red-500 hover:bg-red-50 rounded-lg shrink-0"
                            >
                              <X className="w-4 h-4" />
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                    {documents.length < 5 && (
                      <label className="mt-2 inline-flex items-center gap-2 px-4 py-2 border border-dashed border-gray-300 rounded-xl cursor-pointer hover:border-[#1790d7] text-sm font-medium text-gray-700">
                        <Upload className="w-4 h-4" />
                        Add document
                        <input type="file" accept=".pdf,.doc,.docx" className="hidden" onChange={handleDocumentAdd} />
                      </label>
                    )}
                  </div>
                </div>
              )}
            </Section>
          </div>

          {/* Right: price, shipping, publish — sticky on desktop */}
          <div className="lg:col-span-5 xl:col-span-4 space-y-4 lg:sticky lg:top-4 lg:self-start">
            <Section title="Price & stock" subtitle="PKR" icon={Tag}>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-1 gap-4">
                <Field label="Selling price" required error={errors.price}>
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm font-semibold text-gray-500">
                      Rs
                    </span>
                    <input
                      type="text"
                      inputMode="decimal"
                      name="price"
                      value={formatPriceWithCommas(form.price)}
                      onChange={handleChange}
                      placeholder="0"
                      className={`${inputClass(!!errors.price)} pl-10`}
                    />
                  </div>
                </Field>
                <Field label="Compare at (optional)" hint="Shows discount badge">
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm font-semibold text-gray-500">
                      Rs
                    </span>
                    <input
                      type="text"
                      inputMode="decimal"
                      name="compare_at_price"
                      value={formatPriceWithCommas(form.compare_at_price)}
                      onChange={handleChange}
                      placeholder="Was price"
                      className={`${inputClass(false)} pl-10`}
                    />
                  </div>
                </Field>
              </div>
              <Field
                label="Quantity"
                required
                error={errors.quantity}
                hint={isPrivateSeller ? "Units available" : "1 per listing"}
              >
                <input
                  type="number"
                  name="quantity"
                  value={form.quantity}
                  onChange={handleChange}
                  min="1"
                  max={isPrivateSeller ? undefined : 1}
                  readOnly={!isPrivateSeller}
                  className={`${inputClass(!!errors.quantity)} w-28 ${!isPrivateSeller ? "bg-gray-50" : ""}`}
                />
              </Field>
            </Section>

            <Section title="Shipping" subtitle="Who pays delivery?" icon={Truck}>
              <div className="grid grid-cols-1 gap-2.5">
                {[
                  {
                    value: "customer_pays",
                    title: "Buyer pays shipping",
                    desc: "You set a fixed shipping fee at checkout.",
                  },
                  {
                    value: "free_shipping",
                    title: "You pay (free for buyer)",
                    desc: "Buyers see free shipping on this item.",
                  },
                ].map((opt) => {
                  const active = form.shipping_mode === opt.value;
                  return (
                    <button
                      key={opt.value}
                      type="button"
                      onClick={() => setForm((p) => ({ ...p, shipping_mode: opt.value }))}
                      className={`text-left p-3.5 rounded-xl border transition ${
                        active ? "border-[#1790d7] bg-[#1790d7]/5" : "border-gray-200 hover:border-gray-300"
                      }`}
                    >
                      <span className="flex items-center gap-2 font-semibold text-gray-900 text-sm">
                        {active && <CheckCircle2 className="w-4 h-4 text-[#1790d7] shrink-0" />}
                        {opt.title}
                      </span>
                      <span className="block text-xs text-gray-500 mt-0.5">{opt.desc}</span>
                    </button>
                  );
                })}
              </div>
              {form.shipping_mode !== "free_shipping" && (
                <Field label="Shipping price" required error={errors.shipping_cost_cached}>
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm font-semibold text-gray-500">
                      Rs
                    </span>
                    <input
                      type="text"
                      inputMode="decimal"
                      name="shipping_cost_cached"
                      value={formatPriceWithCommas(form.shipping_cost_cached)}
                      onChange={handleChange}
                      placeholder="e.g. 250"
                      className={`${inputClass(!!errors.shipping_cost_cached)} pl-10`}
                    />
                  </div>
                </Field>
              )}
            </Section>

            <Section title="Publish" subtitle="Go live or save for later" icon={Send}>
              <div className="grid grid-cols-1 gap-2.5">
                {!overFreeLimit && (
                  <label
                    className={`flex items-start gap-3 p-3.5 border rounded-xl cursor-pointer transition ${
                      form.status === "published" ? "border-[#1790d7] bg-[#1790d7]/5" : "border-gray-200"
                    }`}
                  >
                    <input
                      type="radio"
                      name="status"
                      value="published"
                      checked={form.status === "published"}
                      onChange={handleChange}
                      className="mt-0.5 accent-[#1790d7]"
                    />
                    <span>
                      <span className="block font-semibold text-gray-900 text-sm">Publish</span>
                      <span className="text-xs text-gray-500">Live or pending approval</span>
                    </span>
                  </label>
                )}
                <label
                  className={`flex items-start gap-3 p-3.5 border rounded-xl cursor-pointer transition ${
                    form.status === "draft" || overFreeLimit
                      ? "border-[#1790d7] bg-[#1790d7]/5"
                      : "border-gray-200"
                  }`}
                >
                  <input
                    type="radio"
                    name="status"
                    value="draft"
                    checked={form.status === "draft" || overFreeLimit}
                    onChange={handleChange}
                    className="mt-0.5 accent-[#1790d7]"
                  />
                  <span>
                    <span className="block font-semibold text-gray-900 text-sm">Save as draft</span>
                    <span className="text-xs text-gray-500">Activate later from My Listings</span>
                  </span>
                </label>
              </div>

              <div className="hidden sm:flex flex-col gap-2 pt-1">
                <button
                  type="submit"
                  disabled={submitting}
                  className="w-full py-3.5 bg-[#1790d7] hover:bg-[#1277b8] text-white rounded-xl font-semibold shadow-sm disabled:opacity-50 transition"
                >
                  {submitLabel}
                </button>
                <Link
                  href="/customer/listings"
                  className="w-full py-3 text-center border border-gray-200 rounded-xl text-gray-700 font-medium hover:bg-gray-50 transition text-sm"
                >
                  Cancel
                </Link>
              </div>
            </Section>
          </div>
        </div>
      </form>

      {/* Mobile sticky actions */}
      <div className="sm:hidden fixed bottom-0 inset-x-0 z-40 border-t border-gray-200 bg-white/95 backdrop-blur px-4 py-3">
        <div className="flex gap-2 w-full">
          <Link
            href="/customer/listings"
            className="px-4 py-3 border border-gray-200 rounded-xl text-gray-700 font-medium text-sm shrink-0"
          >
            Cancel
          </Link>
          <button
            type="submit"
            form="sell-item-form"
            disabled={submitting}
            className="flex-1 py-3 bg-[#1790d7] text-white rounded-xl font-semibold text-sm disabled:opacity-50"
          >
            {submitLabel}
          </button>
        </div>
      </div>
    </div>
  );
}
