"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import Image from "next/image";
import {
  Plus, PencilSimple, Trash, Package,
  X, UploadSimple, Check, MagnifyingGlass,
  ArrowUp, ArrowDown, ArrowsDownUp, FloppyDisk,
} from "@phosphor-icons/react";
import type { Product } from "@/types/product";

/* ─── Constants ──────────────────────────────────────────────────── */

const CATEGORIES = [
  "Farines Fortifiées",
  "Farines Enrichies",
  "Pâte",
  "Fruits & Légumes Séchés en Poudre",
  "Biscrotch & Moutcha",
  "Panier",
];

const CATEGORY_COLORS: Record<string, string> = {
  "Farines Fortifiées":              "bg-amber-100  text-amber-800",
  "Farines Enrichies":               "bg-yellow-100 text-yellow-800",
  "Pâte":                            "bg-orange-100 text-orange-800",
  "Fruits & Légumes Séchés en Poudre": "bg-green-100  text-green-800",
  "Biscrotch & Moutcha":             "bg-stone-100  text-stone-800",
  "Panier":                          "bg-purple-100 text-purple-800",
};

const EMPTY_FORM = {
  name:           "",
  category:       CATEGORIES[0],
  description:    "",
  description_en: "",
  description_es: "",
  description_ar: "",
  tag:            "",
  sizes:          "",
  price:          "0",
  price_gros:     "0",
  min_qty_gros:   "1",
  available:      true,
};

type FormData  = typeof EMPTY_FORM;
type ModalMode = "add" | "edit" | null;

/* ─── Page ───────────────────────────────────────────────────────── */

export default function ProduitsPage() {
  const [products,     setProducts]     = useState<Product[]>([]);
  const [loading,      setLoading]      = useState(true);
  const [modalMode,    setModalMode]    = useState<ModalMode>(null);
  const [editing,      setEditing]      = useState<Product | null>(null);
  const [form,         setForm]         = useState<FormData>(EMPTY_FORM);
  const [imageFile,    setImageFile]    = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState("");
  const [saving,       setSaving]       = useState(false);
  const [search,       setSearch]       = useState("");
  const [filterCat,    setFilterCat]    = useState("Tous");
  const [deleting,     setDeleting]     = useState<number | null>(null);
  const [descTab,      setDescTab]      = useState<"fr"|"en"|"es"|"ar">("fr");
  const [reorderMode,  setReorderMode]  = useState(false);
  const [reordered,    setReordered]    = useState<Product[]>([]);
  const [savingOrder,  setSavingOrder]  = useState(false);

  const fileRef = useRef<HTMLInputElement>(null);

  const load = async () => {
    setLoading(true);
    const res  = await fetch("/api/products");
    const data = await res.json();
    setProducts(Array.isArray(data) ? data : []);
    setLoading(false);
  };

  useEffect(() => { load(); }, []);

  /* ── Modal helpers ── */
  const openAdd = () => {
    setEditing(null);
    setForm(EMPTY_FORM);
    setImageFile(null);
    setImagePreview("");
    setModalMode("add");
  };

  const openEdit = (p: Product) => {
    setEditing(p);
    setForm({
      name:           p.name,
      category:       p.category,
      description:    p.description    ?? "",
      description_en: p.description_en ?? "",
      description_es: p.description_es ?? "",
      description_ar: p.description_ar ?? "",
      tag:            p.tag   ?? "",
      sizes:          (p.sizes ?? []).join(", "),
      price:          String(p.price ?? 0),
      price_gros:     String(p.price_gros ?? 0),
      min_qty_gros:   String(p.min_qty_gros ?? 1),
      available:      p.available,
    });
    setImageFile(null);
    setImagePreview(p.image_url ?? "");
    setModalMode("edit");
  };

  const closeModal = () => {
    setModalMode(null);
    setEditing(null);
  };

  /* ── Form actions ── */
  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setImageFile(file);
    setImagePreview(URL.createObjectURL(file));
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      let image_url       = editing?.image_url       ?? "";
      let image_public_id = editing?.image_public_id ?? "";

      if (imageFile) {
        const fd = new FormData();
        fd.append("file", imageFile);
        if (image_public_id) fd.append("old_public_id", image_public_id);
        const up     = await fetch("/api/upload", { method: "POST", body: fd });
        const upData = await up.json();
        image_url       = upData.url;
        image_public_id = upData.public_id;
      }

      const sizes = form.sizes.trim() ? [form.sizes.trim()] : [];
      const body = {
        ...form,
        sizes,
        price:        parseFloat(form.price)        || 0,
        price_gros:   parseFloat(form.price_gros)   || 0,
        min_qty_gros: parseInt(form.min_qty_gros)   || 1,
        image_url,
        image_public_id,
      };

      if (modalMode === "add") {
        await fetch("/api/products", {
          method:  "POST",
          headers: { "Content-Type": "application/json" },
          body:    JSON.stringify(body),
        });
      } else if (editing) {
        await fetch(`/api/products/${editing.id}`, {
          method:  "PUT",
          headers: { "Content-Type": "application/json" },
          body:    JSON.stringify(body),
        });
      }

      await load();
      closeModal();
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (p: Product) => {
    if (!confirm(`Supprimer "${p.name}" ? Cette action est irréversible.`)) return;
    setDeleting(p.id);
    await fetch(`/api/products/${p.id}`, { method: "DELETE" });
    await load();
    setDeleting(null);
  };

  const openReorder = () => {
    // Sort by current sort_order before entering reorder mode
    setReordered([...products].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0)));
    setReorderMode(true);
  };

  const moveProduct = (id: number, direction: "up" | "down", cat: string) => {
    setReordered(prev => {
      const catItems  = prev.filter(p => p.category === cat);
      const idx       = catItems.findIndex(p => p.id === id);
      const swapIdx   = direction === "up" ? idx - 1 : idx + 1;
      if (swapIdx < 0 || swapIdx >= catItems.length) return prev;
      const next = [...prev];
      const aPos = next.findIndex(p => p.id === catItems[idx].id);
      const bPos = next.findIndex(p => p.id === catItems[swapIdx].id);
      [next[aPos], next[bPos]] = [next[bPos], next[aPos]];
      return next;
    });
  };

  const saveOrder = async () => {
    setSavingOrder(true);
    const orders = reordered.map((p, i) => ({ id: p.id, sort_order: i }));
    await fetch("/api/admin/products/reorder", {
      method:  "PATCH",
      headers: { "Content-Type": "application/json" },
      body:    JSON.stringify({ orders }),
    });
    await load();
    setSavingOrder(false);
    setReorderMode(false);
  };

  const available   = products.filter((p) => p.available).length;
  const unavailable = products.length - available;

  const filtered = useMemo(() => {
    const q = search.toLowerCase().trim();
    return products.filter((p) => {
      const matchCat  = filterCat === "Tous" || p.category === filterCat;
      const matchText = !q || p.name.toLowerCase().includes(q) || p.category.toLowerCase().includes(q);
      return matchCat && matchText;
    });
  }, [products, search, filterCat]);

  return (
    <main className="max-w-5xl mx-auto px-4 py-6 space-y-5">

      {/* Header actions */}
      <div className="flex justify-end gap-2">
        {reorderMode ? (
          <>
            <button
              onClick={() => setReorderMode(false)}
              className="flex items-center gap-1.5 border border-brand-dark/15 text-brand-dark/50 font-bold px-4 py-2 rounded-full text-xs hover:text-brand-dark transition-colors"
            >
              <X size={13} weight="bold" /> Annuler
            </button>
            <button
              onClick={saveOrder}
              disabled={savingOrder}
              className="flex items-center gap-1.5 bg-brand-dark text-brand-yellow font-bold px-4 py-2 rounded-full text-xs tracking-wide hover:scale-105 transition-transform duration-200 disabled:opacity-50"
            >
              {savingOrder
                ? <span className="w-3.5 h-3.5 border-2 border-brand-yellow/30 border-t-brand-yellow rounded-full animate-spin" />
                : <FloppyDisk size={14} weight="bold" />}
              Sauvegarder l&apos;ordre
            </button>
          </>
        ) : (
          <>
            <button
              onClick={openReorder}
              className="flex items-center gap-1.5 border border-brand-dark/15 text-brand-dark/50 font-bold px-4 py-2 rounded-full text-xs hover:text-brand-dark transition-colors"
            >
              <ArrowsDownUp size={14} weight="bold" />
              Réordonner
            </button>
            <button
              onClick={openAdd}
              className="flex items-center gap-1.5 bg-brand-dark text-brand-yellow font-bold px-4 py-2 rounded-full text-xs tracking-wide hover:scale-105 transition-transform duration-200"
            >
              <Plus size={14} weight="bold" />
              Ajouter un produit
            </button>
          </>
        )}
      </div>

      {/* Stats */}
      <div className="grid grid-cols-3 gap-3">
        {[
          { label: "Total",       value: products.length, bg: "bg-white"        },
          { label: "Disponibles", value: available,        bg: "bg-brand-yellow/15" },
          { label: "Masqués",     value: unavailable,      bg: "bg-white"        },
        ].map((s) => (
          <div key={s.label} className={`${s.bg} rounded-2xl p-4 border border-brand-dark/8`}>
            <div
              className="text-2xl font-bold text-brand-dark"
              style={{ fontFamily: "var(--font-space,sans-serif)" }}
            >
              {s.value}
            </div>
            <div className="text-[10px] font-bold text-brand-dark/40 tracking-wider uppercase mt-0.5">
              {s.label}
            </div>
          </div>
        ))}
      </div>

      {/* Search & filter */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1">
          <MagnifyingGlass
            size={15}
            weight="bold"
            className="absolute left-3.5 top-1/2 -translate-y-1/2 text-brand-dark/35 pointer-events-none"
          />
          <input
            type="search"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Rechercher un produit..."
            className="w-full pl-9 pr-8 py-2.5 rounded-xl bg-white border border-brand-dark/10 text-sm text-brand-dark placeholder:text-brand-dark/30 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 transition-all"
          />
          {search && (
            <button
              onClick={() => setSearch("")}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-brand-dark/30 hover:text-brand-dark transition-colors"
            >
              <X size={13} weight="bold" />
            </button>
          )}
        </div>
        <div className="flex gap-2 overflow-x-auto scrollbar-hide">
          {["Tous", ...CATEGORIES].map((cat) => (
            <button
              key={cat}
              onClick={() => setFilterCat(cat)}
              className={`flex-shrink-0 text-[11px] font-bold px-3.5 py-2 rounded-xl transition-all duration-200 ${
                filterCat === cat
                  ? "bg-brand-dark text-brand-yellow"
                  : "bg-white text-brand-dark/50 hover:text-brand-dark border border-brand-dark/10"
              }`}
            >
              {cat}
            </button>
          ))}
        </div>
      </div>

      {/* Reorder mode */}
      {reorderMode ? (
        <div className="space-y-4">
          <p className="text-xs text-brand-dark/40 font-semibold">Utilisez les flèches pour changer l&apos;ordre d&apos;affichage sur le site.</p>
          {CATEGORIES.map(cat => {
            const items = reordered.filter(p => p.category === cat);
            if (!items.length) return null;
            return (
              <div key={cat} className="bg-white rounded-3xl border border-brand-dark/8 overflow-hidden">
                <div className="px-5 py-3 border-b border-brand-dark/8 bg-brand-sand-light">
                  <span className={`text-[10px] font-bold tracking-wide px-2.5 py-0.5 rounded-full ${CATEGORY_COLORS[cat] ?? "bg-gray-100 text-gray-700"}`}>
                    {cat}
                  </span>
                </div>
                <ul className="divide-y divide-brand-dark/5">
                  {items.map((p, i) => (
                    <li key={p.id} className="flex items-center gap-3 px-5 py-3">
                      <span className="text-[11px] font-bold text-brand-dark/20 w-5 text-center">{i + 1}</span>
                      {p.image_url && (
                        <img src={p.image_url} alt={p.name} className="w-9 h-9 object-contain rounded-lg bg-brand-sand-light flex-shrink-0" />
                      )}
                      <span className="text-sm font-semibold text-brand-dark flex-1">{p.name}</span>
                      <div className="flex gap-1">
                        <button
                          onClick={() => moveProduct(p.id, "up", cat)}
                          disabled={i === 0}
                          className="w-7 h-7 flex items-center justify-center rounded-lg border border-brand-dark/10 text-brand-dark/40 hover:text-brand-dark hover:border-brand-dark/30 disabled:opacity-20 transition-colors"
                        >
                          <ArrowUp size={12} weight="bold" />
                        </button>
                        <button
                          onClick={() => moveProduct(p.id, "down", cat)}
                          disabled={i === items.length - 1}
                          className="w-7 h-7 flex items-center justify-center rounded-lg border border-brand-dark/10 text-brand-dark/40 hover:text-brand-dark hover:border-brand-dark/30 disabled:opacity-20 transition-colors"
                        >
                          <ArrowDown size={12} weight="bold" />
                        </button>
                      </div>
                    </li>
                  ))}
                </ul>
              </div>
            );
          })}
        </div>
      ) : loading ? (
        <LoadingSkeleton />
      ) : products.length === 0 ? (
        <EmptyState onAdd={openAdd} />
      ) : filtered.length === 0 ? (
        <div className="text-center py-16 bg-white rounded-3xl border border-brand-dark/8">
          <Package size={44} weight="light" className="text-brand-dark/20 mx-auto mb-3" />
          <p className="text-sm font-bold text-brand-dark/40">Aucun résultat</p>
          <button
            onClick={() => { setSearch(""); setFilterCat("Tous"); }}
            className="mt-4 text-xs font-bold text-brand-dark/50 underline underline-offset-2 hover:text-brand-dark transition-colors"
          >
            Réinitialiser les filtres
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {filtered.map((p) => (
            <ProductCard
              key={p.id}
              product={p}
              deleting={deleting === p.id}
              onEdit={() => openEdit(p)}
              onDelete={() => handleDelete(p)}
            />
          ))}
        </div>
      )}

      {/* ─── Product Modal ─────────────────────────────────────────── */}
      {modalMode && (
        <div
          className="fixed inset-0 z-50 flex items-end sm:items-center justify-center"
          onClick={(e) => { if (e.target === e.currentTarget) closeModal(); }}
        >
          <div className="absolute inset-0 bg-brand-dark/50 backdrop-blur-sm" />
          <div className="relative w-full sm:max-w-lg bg-white rounded-t-3xl sm:rounded-3xl shadow-2xl max-h-[92dvh] flex flex-col overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-300">
            <div className="flex items-center justify-between px-5 pt-5 pb-4 border-b border-brand-dark/8 flex-shrink-0">
              <div className="absolute top-2 left-1/2 -translate-x-1/2 w-10 h-1 bg-brand-dark/15 rounded-full sm:hidden" />
              <h2 className="font-bold text-brand-dark" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                {modalMode === "add" ? "Nouveau produit" : "Modifier le produit"}
              </h2>
              <button type="button" onClick={closeModal} className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-brand-dark/8 text-brand-dark/50 hover:text-brand-dark transition-colors">
                <X size={16} weight="bold" />
              </button>
            </div>
            <form onSubmit={handleSave} className="overflow-y-auto overscroll-contain flex-1 px-5 py-5 space-y-4" onWheel={(e) => e.stopPropagation()}>
              {/* ── Image ── */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-2">Image du produit</label>
                <div
                  role="button" tabIndex={0}
                  onClick={() => fileRef.current?.click()}
                  onKeyDown={(e) => e.key === "Enter" && fileRef.current?.click()}
                  className="relative h-36 bg-brand-off-white rounded-2xl border-2 border-dashed border-brand-dark/15 flex items-center justify-center cursor-pointer hover:border-brand-yellow transition-colors overflow-hidden group"
                >
                  {imagePreview ? (
                    <>
                      <Image src={imagePreview} alt="aperçu" fill className="object-contain p-3" />
                      <div className="absolute inset-0 bg-black/0 group-hover:bg-black/15 transition-colors flex items-center justify-center">
                        <UploadSimple size={22} weight="bold" className="text-white opacity-0 group-hover:opacity-100 transition-opacity drop-shadow" />
                      </div>
                    </>
                  ) : (
                    <div className="flex flex-col items-center gap-1.5 text-brand-dark/30 group-hover:text-brand-dark/60 transition-colors select-none">
                      <UploadSimple size={30} weight="light" />
                      <span className="text-xs font-semibold">Appuyez pour choisir</span>
                    </div>
                  )}
                </div>
                <input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleImageChange} />
              </div>
              {/* ── Name ── */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Nom <span className="text-red-400">*</span></label>
                <input required value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} placeholder="Nom du produit" className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
              </div>
              {/* ── Category ── */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Catégorie <span className="text-red-400">*</span></label>
                <select required value={form.category} onChange={(e) => setForm((f) => ({ ...f, category: e.target.value }))} className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark bg-white transition-all">
                  {CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}
                </select>
              </div>
              {/* ── Tag ── */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Tag <span className="normal-case font-normal text-brand-dark/30">(optionnel)</span></label>
                <input value={form.tag} onChange={(e) => setForm((f) => ({ ...f, tag: e.target.value }))} placeholder="ex: Nouveau, Promo, Bio..." className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
              </div>
              {/* ── Sizes ── */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Format <span className="normal-case font-normal text-brand-dark/30">(optionnel — ex : 500g, 1kg, 250ml)</span></label>
                <input value={form.sizes} onChange={(e) => setForm((f) => ({ ...f, sizes: e.target.value }))} placeholder="ex: 500g" className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
              </div>
              {/* ── Price ── */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Prix (MRU)</label>
                <input type="number" min="0" step="0.01" value={form.price} onChange={(e) => setForm((f) => ({ ...f, price: e.target.value }))} placeholder="0" className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
              </div>
              {/* ── Wholesale pricing ── */}
              <div className="bg-brand-yellow/10 border border-brand-yellow/40 rounded-2xl p-4 space-y-3">
                <div className="text-[10px] font-bold text-brand-dark/60 tracking-widest uppercase">
                  Prix en gros <span className="normal-case font-normal text-brand-dark/30">(optionnel — laisser à 0 pour désactiver)</span>
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-[10px] font-semibold text-brand-dark/50 mb-1">Prix gros (MRU)</label>
                    <input
                      type="number" min="0" step="0.01"
                      value={form.price_gros}
                      onChange={(e) => setForm((f) => ({ ...f, price_gros: e.target.value }))}
                      placeholder="0"
                      className="w-full px-3 py-2 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] font-semibold text-brand-dark/50 mb-1">Qté minimale</label>
                    <input
                      type="number" min="1" step="1"
                      value={form.min_qty_gros}
                      onChange={(e) => setForm((f) => ({ ...f, min_qty_gros: e.target.value }))}
                      placeholder="1"
                      className="w-full px-3 py-2 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all"
                    />
                  </div>
                </div>
                {parseFloat(form.price_gros) > 0 && parseInt(form.min_qty_gros) > 1 && (
                  <p className="text-[11px] text-brand-dark/50">
                    Dès <strong>{parseInt(form.min_qty_gros)} pcs</strong>, prix réduit à <strong>{parseFloat(form.price_gros).toLocaleString("fr-MR")} MRU</strong>
                  </p>
                )}
              </div>
              {/* ── Description (multi-langue) ── */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-2">
                  Description <span className="normal-case font-normal text-brand-dark/30">(optionnel)</span>
                </label>
                {/* Lang tabs */}
                <div className="flex gap-1 mb-2">
                  {(["fr","en","es","ar"] as const).map((lang) => {
                    const val = lang === "fr" ? form.description : form[`description_${lang}` as keyof typeof form] as string;
                    const filled = typeof val === "string" && val.trim().length > 0;
                    return (
                      <button
                        key={lang}
                        type="button"
                        onClick={() => setDescTab(lang)}
                        className={`relative px-3 py-1 rounded-lg text-[11px] font-bold transition-colors ${
                          descTab === lang
                            ? "bg-brand-dark text-brand-yellow"
                            : "bg-brand-dark/8 text-brand-dark/50 hover:text-brand-dark"
                        }`}
                      >
                        {lang.toUpperCase()}
                        {filled && (
                          <span className={`absolute -top-0.5 -right-0.5 w-1.5 h-1.5 rounded-full ${descTab === lang ? "bg-brand-yellow" : "bg-green-400"}`} />
                        )}
                      </button>
                    );
                  })}
                </div>
                {descTab === "fr" && (
                  <textarea rows={3} value={form.description} onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))} placeholder="Description en français..." className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all resize-none" />
                )}
                {descTab === "en" && (
                  <textarea rows={3} value={form.description_en} onChange={(e) => setForm((f) => ({ ...f, description_en: e.target.value }))} placeholder="Description in English..." className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all resize-none" />
                )}
                {descTab === "es" && (
                  <textarea rows={3} value={form.description_es} onChange={(e) => setForm((f) => ({ ...f, description_es: e.target.value }))} placeholder="Descripción en español..." className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all resize-none" />
                )}
                {descTab === "ar" && (
                  <textarea rows={3} dir="rtl" value={form.description_ar} onChange={(e) => setForm((f) => ({ ...f, description_ar: e.target.value }))} placeholder="الوصف بالعربية..." className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all resize-none" />
                )}
              </div>
              {/* ── Available toggle ── */}
              <div className="flex items-center justify-between bg-brand-sand-light rounded-xl px-4 py-3">
                <div>
                  <div className="text-sm font-bold text-brand-dark">Disponible</div>
                  <div className="text-[10px] text-brand-dark/40 mt-0.5">Visible sur le site public</div>
                </div>
                <button type="button" onClick={() => setForm((f) => ({ ...f, available: !f.available }))} aria-checked={form.available} role="switch" className={`relative w-11 h-6 rounded-full transition-colors duration-300 flex-shrink-0 ${form.available ? "bg-brand-dark" : "bg-brand-dark/20"}`}>
                  <span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow-sm flex items-center justify-center transition-transform duration-300 ${form.available ? "translate-x-5" : "translate-x-0"}`}>
                    {form.available && <Check size={10} weight="bold" className="text-brand-dark" />}
                  </span>
                </button>
              </div>
              {/* ── Submit ── */}
              <div className="pb-safe">
                <button type="submit" disabled={saving} className="w-full bg-brand-dark text-brand-yellow font-bold py-3.5 rounded-full text-sm tracking-wide flex items-center justify-center gap-2 disabled:opacity-50 hover:scale-[1.01] active:scale-[0.99] transition-transform duration-200 mt-1">
                  {saving && <span className="w-4 h-4 border-2 border-brand-yellow/30 border-t-brand-yellow rounded-full animate-spin" />}
                  {saving ? "Enregistrement..." : modalMode === "add" ? "Ajouter le produit" : "Enregistrer les modifications"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

    </main>
  );
}

/* ─── Sub-components ─────────────────────────────────────────────── */

function ProductCard({
  product, deleting, onEdit, onDelete,
}: {
  product:  Product;
  deleting: boolean;
  onEdit:   () => void;
  onDelete: () => void;
}) {
  const catColor = CATEGORY_COLORS[product.category] ?? "bg-gray-100 text-gray-700";

  return (
    <div className="bg-white rounded-3xl overflow-hidden border border-brand-dark/8 hover:shadow-lg transition-shadow duration-300 flex flex-col">

      {/* Image */}
      <div className="relative h-40 bg-brand-off-white flex items-center justify-center">
        {product.image_url ? (
          <Image
            src={product.image_url}
            alt={product.name}
            fill
            className="object-contain p-4"
          />
        ) : (
          <Package size={44} weight="light" className="text-brand-dark/20" />
        )}
        <div
          className={`absolute top-3 right-3 w-2.5 h-2.5 rounded-full ring-2 ring-white ${
            product.available ? "bg-green-400" : "bg-red-400"
          }`}
        />
      </div>

      {/* Info */}
      <div className="p-4 flex flex-col flex-1">
        <div className="flex items-start justify-between gap-2 mb-1.5">
          <h3
            className="font-bold text-brand-dark text-sm leading-tight flex-1"
            style={{ fontFamily: "var(--font-space,sans-serif)" }}
          >
            {product.name}
          </h3>
          {product.tag && (
            <span className="text-[9px] font-bold tracking-widest uppercase bg-brand-yellow text-brand-dark px-2 py-0.5 rounded-full flex-shrink-0">
              {product.tag}
            </span>
          )}
        </div>

        <span className={`self-start text-[10px] font-bold tracking-wide px-2.5 py-0.5 rounded-full mb-3 ${catColor}`}>
          {product.category}
        </span>

        {product.description && (
          <p className="text-brand-dark/40 text-xs leading-relaxed line-clamp-2 flex-1 mb-3">
            {product.description}
          </p>
        )}

        <div className="flex items-center gap-2 flex-wrap mb-3">
          {product.price > 0 && (
            <span className="text-xs font-bold text-brand-dark">{Number(product.price).toLocaleString("fr-MR")} MRU</span>
          )}
          {product.price_gros > 0 && product.min_qty_gros > 1 && (
            <span className="text-[10px] font-bold bg-brand-yellow/20 text-brand-dark/70 px-2 py-0.5 rounded-full">
              Gros: {Number(product.price_gros).toLocaleString("fr-MR")} MRU / {product.min_qty_gros}+
            </span>
          )}
        </div>

        {/* Actions */}
        <div className="flex gap-2 mt-auto">
          <button
            onClick={onEdit}
            className="flex-1 flex items-center justify-center gap-1.5 border border-brand-dark/15 text-brand-dark font-bold py-2 rounded-full text-xs hover:border-brand-dark transition-colors duration-200"
          >
            <PencilSimple size={12} weight="bold" />
            Modifier
          </button>
          <button
            onClick={onDelete}
            disabled={deleting}
            className="flex-1 flex items-center justify-center gap-1.5 border border-red-200 text-red-500 font-bold py-2 rounded-full text-xs hover:bg-red-50 transition-colors duration-200 disabled:opacity-40"
          >
            {deleting
              ? <span className="w-3 h-3 border border-red-300 border-t-red-500 rounded-full animate-spin" />
              : <Trash size={12} weight="bold" />
            }
            Supprimer
          </button>
        </div>
      </div>
    </div>
  );
}

function LoadingSkeleton() {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
      {Array.from({ length: 6 }).map((_, i) => (
        <div
          key={i}
          className="bg-white rounded-3xl overflow-hidden border border-brand-dark/8 animate-pulse"
        >
          <div className="h-40 bg-brand-dark/5" />
          <div className="p-4 space-y-2.5">
            <div className="h-3.5 bg-brand-dark/8 rounded-full w-3/4" />
            <div className="h-3   bg-brand-dark/5 rounded-full w-1/2" />
            <div className="h-3   bg-brand-dark/5 rounded-full w-full" />
          </div>
        </div>
      ))}
    </div>
  );
}

function EmptyState({ onAdd }: { onAdd: () => void }) {
  return (
    <div className="text-center py-20 bg-white rounded-3xl border border-brand-dark/8">
      <Package size={52} weight="light" className="text-brand-dark/20 mx-auto mb-4" />
      <h3 className="text-base font-bold text-brand-dark mb-1.5">Aucun produit</h3>
      <p className="text-brand-dark/40 text-sm mb-6">Commencez par ajouter votre premier produit.</p>
      <button
        onClick={onAdd}
        className="inline-flex items-center gap-2 bg-brand-dark text-brand-yellow font-bold px-6 py-3 rounded-full text-sm hover:scale-105 transition-transform duration-200"
      >
        <Plus size={15} weight="bold" />
        Ajouter un produit
      </button>
    </div>
  );
}
