"use client";
 
import { useEffect, useState, useMemo } from "react";
import { 
  Package, Search, Plus, Pencil, Trash2, Tag, Star, 
  Check, X, RefreshCw, Loader2, AlertTriangle, Folder, 
  FolderPlus, ChevronRight, ArrowUp, ArrowDown 
} from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import Button from "@/components/ui/Button";
import Input from "@/components/ui/Input";
import { listProductos, createProducto, updateProducto, deleteProducto } from "@/lib/pb/productos";
import { listCategorias, createCategoria, updateCategoria, deleteCategoria } from "@/lib/pb/categorias";
import type { Producto } from "@/lib/types/producto";
import type { Categoria } from "@/lib/types/categoria";
import { money } from "@/lib/format";
 
type TabActive = "productos" | "categorias";
 
type EditorState = {
  mode: "create" | "edit";
  id?: string;
  nombre: string;
  referencia_interna: string;
  categoria: string;
  precio_venta: number;
  cantidad_mano: number;
  favorito: boolean;
};
 
type CategoryEditorState = {
  mode: "create" | "edit";
  id?: string;
  nombre: string;
  parent?: string; // ID de categoría padre
  sort_order: number;
};
 
const EMPTY_EDITOR: EditorState = {
  mode: "create",
  nombre: "",
  referencia_interna: "",
  categoria: "",
  precio_venta: 0,
  cantidad_mano: 0,
  favorito: false,
};
 
const EMPTY_CAT_EDITOR: CategoryEditorState = {
  mode: "create",
  nombre: "",
  sort_order: 0,
};
 
export default function CatalogoPage() {
  const [tabActive, setTabActive] = useState<TabActive>("productos");
  const [productos, setProductos] = useState<Producto[]>([]);
  const [categorias, setCategorias] = useState<Categoria[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [selectedCategory, setSelectedCategory] = useState<string>("todos");
  const [err, setErr] = useState("");
  const [busyId, setBusyId] = useState<string | null>(null);
 
  // Modales
  const [editor, setEditor] = useState<EditorState | null>(null);
  const [catEditor, setCatEditor] = useState<CategoryEditorState | null>(null);
  const [showCleanupConfirm, setShowCleanupConfirm] = useState(false);
 
  async function loadData() {
    setLoading(true);
    setErr("");
    try {
      const [prodRes, catRes] = await Promise.all([
        listProductos(),
        listCategorias()
      ]);
      setProductos(prodRes);
      setCategorias(catRes);
    } catch (e) {
      setErr((e as Error).message || "No se pudo cargar la información.");
    } finally {
      setLoading(false);
    }
  }
 
  useEffect(() => {
    loadData();
  }, []);
 
  // Jerarquía de Categorías estructurada para UI
  const categoryTree = useMemo(() => {
    const rootCats = categorias.filter(c => !c.parent).sort((a,b) => (a.sort_order || 0) - (b.sort_order || 0));
    return rootCats.map(root => {
      const subs = categorias.filter(c => c.parent === root.id).sort((a,b) => (a.sort_order || 0) - (b.sort_order || 0));
      return {
        ...root,
        subcategories: subs
      };
    });
  }, [categorias]);
 
  // Lista plana de categorías formateadas con parent/sub (para selectores de productos)
  const categoryOptions = useMemo(() => {
    const list: { val: string; label: string }[] = [];
    categoryTree.forEach(root => {
      list.push({ val: root.nombre, label: root.nombre });
      root.subcategories.forEach(sub => {
        list.push({ val: `${root.nombre} / ${sub.nombre}`, label: `↳ ${root.nombre} / ${sub.nombre}` });
      });
    });
    return list;
  }, [categoryTree]);
 
  const filteredProductos = useMemo(() => {
    const q = search.toLowerCase().trim();
    return productos.filter((p) => {
      const matchesSearch = 
        !q ||
        (p.nombre || "").toLowerCase().includes(q) ||
        (p.referencia_interna || "").toLowerCase().includes(q) ||
        (p.categoria || "").toLowerCase().includes(q);
      
      const matchesCategory = 
        selectedCategory === "todos" || 
        p.categoria?.trim() === selectedCategory ||
        p.categoria?.trim().startsWith(selectedCategory + " /");
 
      return matchesSearch && matchesCategory;
    });
  }, [productos, search, selectedCategory]);
 
  async function toggleFavorito(p: Producto) {
    setBusyId(`fav-${p.id}`);
    try {
      const updated = await updateProducto(p.id, { favorito: !p.favorito });
      setProductos((prev) => prev.map((item) => (item.id === p.id ? updated : item)));
    } catch (e) {
      setErr("Error al actualizar favorito.");
    } finally {
      setBusyId(null);
    }
  }
 
  async function handleDelete(id: string) {
    if (!confirm("¿Borrar definitivamente este producto del catálogo?")) return;
    setBusyId(`del-${id}`);
    try {
      await deleteProducto(id);
      setProductos((prev) => prev.filter((item) => item.id !== id));
    } catch (e) {
      setErr("Error al borrar el producto.");
    } finally {
      setBusyId(null);
    }
  }
 
  async function saveEditor() {
    if (!editor || !editor.nombre.trim()) return;
    setBusyId("editor-save");
    try {
      const payload: Partial<Producto> = {
        nombre: editor.nombre.trim(),
        referencia_interna: editor.referencia_interna.trim() || undefined,
        categoria: editor.categoria.trim() || undefined,
        precio_venta: Number(editor.precio_venta) || 0,
        cantidad_mano: Number(editor.cantidad_mano) || 0,
        favorito: editor.favorito,
      };
 
      if (editor.mode === "edit" && editor.id) {
        const updated = await updateProducto(editor.id, payload);
        setProductos((prev) => prev.map((item) => (item.id === editor.id ? updated : item)));
      } else {
        const created = await createProducto(payload);
        setProductos((prev) => [created, ...prev]);
      }
      setEditor(null);
    } catch (e) {
      alert((e as Error).message || "No se pudo guardar el producto.");
    } finally {
      setBusyId(null);
    }
  }
 
  async function performCatalogCleanup() {
    setBusyId("cleanup");
    try {
      const toDelete = filteredProductos;
      if (toDelete.length === 0) {
        alert("No hay productos seleccionados para borrar.");
        return;
      }
      if (!confirm(`¿Confirmar borrado masivo de los ${toDelete.length} productos en pantalla? Esta acción no se puede deshacer.`)) {
        return;
      }
      for (const p of toDelete) {
        await deleteProducto(p.id);
      }
      setProductos((prev) => prev.filter((p) => !toDelete.some((d) => d.id === p.id)));
      setShowCleanupConfirm(false);
    } catch (e) {
      alert("Error durante la limpieza.");
    } finally {
      setBusyId(null);
    }
  }
 
  function openEdit(p: Producto) {
    setEditor({
      mode: "edit",
      id: p.id,
      nombre: p.nombre,
      referencia_interna: p.referencia_interna || "",
      categoria: p.categoria || "",
      precio_venta: p.precio_venta || 0,
      cantidad_mano: p.cantidad_mano || 0,
      favorito: !!p.favorito,
    });
  }
 
  // ── Lógica de Categorías ───────────────────────────────────────────────────
 
  async function saveCategoryEditor() {
    if (!catEditor || !catEditor.nombre.trim()) return;
    setBusyId("cat-editor-save");
    try {
      const payload: Partial<Categoria> = {
        nombre: catEditor.nombre.trim(),
        parent: catEditor.parent || undefined,
        sort_order: catEditor.sort_order,
      };
 
      if (catEditor.mode === "edit" && catEditor.id) {
        const updated = await updateCategoria(catEditor.id, payload);
        setCategorias((prev) => prev.map((item) => (item.id === catEditor.id ? updated : item)));
      } else {
        const created = await createCategoria(payload);
        setCategorias((prev) => [...prev, created]);
      }
      setCatEditor(null);
    } catch (e) {
      alert((e as Error).message || "No se pudo guardar la categoría.");
    } finally {
      setBusyId(null);
    }
  }
 
  async function handleDeleteCategory(id: string) {
    const hasSubcats = categorias.some(c => c.parent === id);
    let msg = "¿Borrar definitivamente esta categoría?";
    if (hasSubcats) {
      msg = "Esta categoría tiene subcategorías vinculadas. Al borrarla se eliminarán todas sus subcategorías. ¿Confirmar?";
    }
    if (!confirm(msg)) return;
 
    setBusyId(`cat-del-${id}`);
    try {
      await deleteCategoria(id);
      // Actualizar estado local eliminando la categoría y sus subcategorías (cascada)
      setCategorias((prev) => prev.filter((item) => item.id !== id && item.parent !== id));
    } catch (e) {
      alert("Error al borrar la categoría.");
    } finally {
      setBusyId(null);
    }
  }
 
  async function moveCategory(c: Categoria, direction: "up" | "down") {
    // Agrupar elementos hermanos (root o subcats)
    const siblings = categorias
      .filter(item => item.parent === c.parent)
      .sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));
 
    const idx = siblings.findIndex(item => item.id === c.id);
    if (idx === -1) return;
 
    const swapIdx = direction === "up" ? idx - 1 : idx + 1;
    if (swapIdx < 0 || swapIdx >= siblings.length) return;
 
    const sibling = siblings[swapIdx];
    const originalOrder = c.sort_order || 0;
    const swapOrder = sibling.sort_order || 0;
 
    // Si tienen el mismo orden, forzamos índices claros
    const nextOriginalOrder = swapOrder === originalOrder ? (direction === "up" ? originalOrder - 1 : originalOrder + 1) : swapOrder;
    const nextSwapOrder = originalOrder;
 
    setBusyId(`cat-move-${c.id}`);
    try {
      const [u1, u2] = await Promise.all([
        updateCategoria(c.id, { sort_order: nextOriginalOrder }),
        updateCategoria(sibling.id, { sort_order: nextSwapOrder })
      ]);
      setCategorias((prev) => 
        prev.map(item => item.id === c.id ? u1 : item.id === sibling.id ? u2 : item)
      );
    } catch (e) {
      alert("No se pudo reordenar la categoría.");
    } finally {
      setBusyId(null);
    }
  }
 
  return (
    <div className="max-w-7xl space-y-4">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
        <div>
          <div className="flex items-center gap-3">
            <Package className="h-6 w-6 text-brand-dark" />
            <h1 className="text-xl font-extrabold text-ink">Catálogo de Productos</h1>
          </div>
          <p className="mt-0.5 text-xs font-medium text-ink-soft">
            Gestioná el catálogo, categorías y subcategorías para el autocompletado en pedidos.
          </p>
        </div>
 
        <div className="flex flex-wrap items-center gap-2">
          {tabActive === "productos" ? (
            <>
              <Button type="button" variant="secondary" onClick={() => setEditor({ ...EMPTY_EDITOR, mode: "create" })}>
                <Plus size={16} /> Nuevo producto
              </Button>
              {productos.length > 0 && (
                <Button type="button" variant="danger" onClick={() => setShowCleanupConfirm(true)}>
                  <Trash2 size={16} /> Limpiar catálogo
                </Button>
              )}
            </>
          ) : (
            <Button type="button" variant="secondary" onClick={() => setCatEditor({ ...EMPTY_CAT_EDITOR, mode: "create", sort_order: categorias.filter(c => !c.parent).length })}>
              <Plus size={16} /> Nueva Categoría
            </Button>
          )}
          <button
            onClick={loadData}
            className="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-line bg-surface text-faint hover:text-ink"
            title="Actualizar"
          >
            <RefreshCw size={16} className={loading ? "animate-spin" : ""} />
          </button>
        </div>
      </div>
 
      {err && (
        <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-bad">
          {err}
        </div>
      )}
 
      {/* Selector de Pestañas */}
      <div className="flex border-b border-line shrink-0">
        <button
          onClick={() => setTabActive("productos")}
          className={`px-4 py-2 text-sm font-semibold border-b-2 transition-colors ${
            tabActive === "productos"
              ? "border-brand text-brand"
              : "border-transparent text-faint hover:text-ink"
          }`}
        >
          Productos ({filteredProductos.length})
        </button>
        <button
          onClick={() => setTabActive("categorias")}
          className={`px-4 py-2 text-sm font-semibold border-b-2 transition-colors ${
            tabActive === "categorias"
              ? "border-brand text-brand"
              : "border-transparent text-faint hover:text-ink"
          }`}
        >
          Categorías & Subcategorías ({categorias.length})
        </button>
      </div>
 
      {tabActive === "productos" ? (
        <>
          {/* Barra de Filtros */}
          <div className="card p-4 flex flex-col md:flex-row gap-3 items-center">
            <label className="relative flex-1 w-full">
              <Search size={14} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-faint" />
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Buscar por código, nombre o categoría"
                className="h-10 w-full rounded-xl border border-line bg-surface pl-9 pr-3 text-sm text-ink outline-none focus:border-brand"
              />
            </label>
            <div className="flex items-center gap-2 w-full md:w-auto">
              <Tag size={16} className="text-faint flex-shrink-0" />
              <select
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
                className="h-10 rounded-xl border border-line bg-surface px-3 text-sm text-ink outline-none focus:border-brand w-full md:w-56"
              >
                <option value="todos">Todas las categorías</option>
                {categoryOptions.map((opt) => (
                  <option key={opt.val} value={opt.val}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>
          </div>
 
          {loading ? (
            <div className="grid place-items-center py-20 text-faint">
              <Loader2 className="h-6 w-6 animate-spin" />
            </div>
          ) : filteredProductos.length === 0 ? (
            <div className="grid place-items-center rounded-xl border border-dashed border-line bg-surface px-4 py-16 text-center">
              <div>
                <Package className="mx-auto mb-3 h-10 w-10 text-faint opacity-40" />
                <p className="text-sm font-semibold text-ink-soft">No se encontraron productos.</p>
                <p className="text-xs text-faint mt-1">Intentá cambiar los filtros o agregá un nuevo producto.</p>
              </div>
            </div>
          ) : (
            <div className="card overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-left text-sm">
                  <thead>
                    <tr className="border-b border-line bg-canvas/50 text-[11px] font-bold uppercase tracking-wider text-faint select-none">
                      <th className="px-4 py-3 w-10" />
                      <th className="px-4 py-3 w-32">Código</th>
                      <th className="px-4 py-3">Nombre</th>
                      <th className="px-4 py-3 w-44">Categoría</th>
                      <th className="px-4 py-3 w-28 text-right">Precio</th>
                      <th className="px-4 py-3 w-24 text-center">Stock</th>
                      <th className="px-4 py-3 w-20 text-center">Acciones</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-line/60">
                    {filteredProductos.map((p) => (
                      <tr key={p.id} className="hover:bg-canvas/40 transition-colors">
                        <td className="px-4 py-3">
                          <button
                            onClick={() => toggleFavorito(p)}
                            disabled={busyId === `fav-${p.id}`}
                            className={`text-amber-400 hover:text-amber-500 disabled:opacity-50`}
                          >
                            <Star size={16} fill={p.favorito ? "currentColor" : "none"} />
                          </button>
                        </td>
                        <td className="px-4 py-3 font-mono text-xs font-semibold text-ink">
                          {p.referencia_interna || "—"}
                        </td>
                        <td className="px-4 py-3 font-medium text-ink">
                          {p.nombre}
                        </td>
                        <td className="px-4 py-3 text-ink-soft font-medium">
                          {p.categoria || "—"}
                        </td>
                        <td className="px-4 py-3 text-right font-medium text-ink tabular-nums">
                          {money(p.precio_venta)}
                        </td>
                        <td className="px-4 py-3 text-center text-ink-soft tabular-nums">
                          {p.cantidad_mano ?? 0}
                        </td>
                        <td className="px-4 py-3 text-center">
                          <div className="flex items-center justify-center gap-1">
                            <button
                              onClick={() => openEdit(p)}
                              className="h-7 w-7 rounded-lg hover:bg-canvas text-faint hover:text-ink inline-flex items-center justify-center"
                              title="Editar"
                            >
                              <Pencil size={14} />
                            </button>
                            <button
                              onClick={() => handleDelete(p.id)}
                              disabled={busyId === `del-${p.id}`}
                              className="h-7 w-7 rounded-lg hover:bg-red-50 text-faint hover:text-bad inline-flex items-center justify-center disabled:opacity-50"
                              title="Borrar"
                            >
                              {busyId === `del-${p.id}` ? (
                                <Loader2 size={14} className="animate-spin" />
                              ) : (
                                <Trash2 size={14} />
                              )}
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </>
      ) : (
        /* PESTAÑA CATEGORIAS */
        <div className="grid gap-6 md:grid-cols-2">
          {/* Listado de Categorias */}
          <div className="space-y-3">
            <h2 className="text-sm font-extrabold text-ink uppercase tracking-wide">Estructura Jerárquica</h2>
            {categoryTree.length === 0 ? (
              <div className="rounded-xl border border-dashed border-line bg-surface p-8 text-center text-faint text-xs">
                No hay categorías creadas. Agrega una categoría principal arriba.
              </div>
            ) : (
              <div className="space-y-3">
                {categoryTree.map((root, rootIdx) => (
                  <div key={root.id} className="rounded-xl border border-line bg-surface overflow-hidden shadow-sm">
                    {/* Fila Categoria Principal */}
                    <div className="flex items-center justify-between gap-3 bg-canvas/30 px-3.5 py-2.5 border-b border-line">
                      <div className="flex items-center gap-2">
                        <Folder className="h-4.5 w-4.5 text-brand" />
                        <span className="text-sm font-bold text-ink">{root.nombre}</span>
                      </div>
                      <div className="flex items-center gap-1">
                        <button
                          onClick={() => setCatEditor({ mode: "create", parent: root.id, nombre: "", sort_order: root.subcategories.length })}
                          className="h-7 px-2 rounded-lg hover:bg-canvas text-brand inline-flex items-center gap-1 text-[11px] font-bold"
                          title="Añadir subcategoría"
                        >
                          <FolderPlus size={13} /> + Sub
                        </button>
                        <button
                          onClick={() => setCatEditor({ mode: "edit", id: root.id, nombre: root.nombre, parent: undefined, sort_order: root.sort_order || 0 })}
                          className="h-7 w-7 rounded-lg hover:bg-canvas text-faint hover:text-ink inline-flex items-center justify-center"
                          title="Editar"
                        >
                          <Pencil size={13} />
                        </button>
                        <button
                          onClick={() => moveCategory(root, "up")}
                          disabled={rootIdx === 0 || busyId !== null}
                          className="h-7 w-7 rounded-lg hover:bg-canvas text-faint hover:text-ink inline-flex items-center justify-center disabled:opacity-30"
                        >
                          <ArrowUp size={13} />
                        </button>
                        <button
                          onClick={() => moveCategory(root, "down")}
                          disabled={rootIdx === categoryTree.length - 1 || busyId !== null}
                          className="h-7 w-7 rounded-lg hover:bg-canvas text-faint hover:text-ink inline-flex items-center justify-center disabled:opacity-30"
                        >
                          <ArrowDown size={13} />
                        </button>
                        <button
                          onClick={() => handleDeleteCategory(root.id)}
                          disabled={busyId === `cat-del-${root.id}`}
                          className="h-7 w-7 rounded-lg hover:bg-red-50 text-faint hover:text-bad inline-flex items-center justify-center disabled:opacity-50"
                        >
                          <Trash2 size={13} />
                        </button>
                      </div>
                    </div>
 
                    {/* Subcategorias */}
                    <div className="divide-y divide-line bg-surface/50">
                      {root.subcategories.length === 0 ? (
                        <div className="px-8 py-2.5 text-xs text-faint italic flex items-center gap-1.5">
                          <ChevronRight size={12} /> Sin subcategorías creadas.
                        </div>
                      ) : (
                        root.subcategories.map((sub, subIdx) => (
                          <div key={sub.id} className="flex items-center justify-between gap-3 px-8 py-2 hover:bg-canvas/10">
                            <span className="text-xs font-semibold text-ink-soft">{sub.nombre}</span>
                            <div className="flex items-center gap-1">
                              <button
                                onClick={() => setCatEditor({ mode: "edit", id: sub.id, nombre: sub.nombre, parent: root.id, sort_order: sub.sort_order || 0 })}
                                className="h-6 w-6 rounded hover:bg-canvas text-faint hover:text-ink inline-flex items-center justify-center"
                              >
                                <Pencil size={12} />
                              </button>
                              <button
                                onClick={() => moveCategory(sub, "up")}
                                disabled={subIdx === 0 || busyId !== null}
                                className="h-6 w-6 rounded hover:bg-canvas text-faint hover:text-ink inline-flex items-center justify-center disabled:opacity-30"
                              >
                                <ArrowUp size={12} />
                              </button>
                              <button
                                onClick={() => moveCategory(sub, "down")}
                                disabled={subIdx === root.subcategories.length - 1 || busyId !== null}
                                className="h-6 w-6 rounded hover:bg-canvas text-faint hover:text-ink inline-flex items-center justify-center disabled:opacity-30"
                              >
                                <ArrowDown size={12} />
                              </button>
                              <button
                                onClick={() => handleDeleteCategory(sub.id)}
                                className="h-6 w-6 rounded hover:bg-red-50 text-faint hover:text-bad inline-flex items-center justify-center"
                              >
                                <Trash2 size={12} />
                              </button>
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
          <div className="rounded-xl border border-line bg-canvas/30 p-4 space-y-2 text-ink">
            <h3 className="text-sm font-extrabold">Ayuda de Categorías</h3>
            <p className="text-xs text-ink-soft leading-relaxed">
              Las categorías permiten clasificar los productos del catálogo. Al estructurarlas como "Categoría Principal" y "Subcategoría", se desplegarán ordenadamente en los pedidos en formato de rama jerárquica (ej. Cocina / Alacenas).
            </p>
            <p className="text-xs text-ink-soft leading-relaxed">
              El botón de ordenamiento <ArrowUp size={12} className="inline" /> y <ArrowDown size={12} className="inline" /> te permite organizar el orden exacto en el que figurarán tanto en los desplegables de búsqueda como en los filtros rápidos.
            </p>
          </div>
        </div>
      )}
 
      {/* Modal Editor Producto */}
      {editor && (
        <div className="fixed inset-0 z-50 grid place-items-center bg-black/40 p-4" onClick={() => setEditor(null)}>
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-surface rounded-2xl border border-line p-6 max-w-md w-full shadow-2xl flex flex-col gap-4 text-ink"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between border-b border-line pb-3">
              <h3 className="text-base font-extrabold text-ink">
                {editor.mode === "create" ? "Nuevo Producto" : "Editar Producto"}
              </h3>
              <button onClick={() => setEditor(null)} className="text-faint hover:text-ink">
                <X size={18} />
              </button>
            </div>
 
            <div className="grid gap-3">
              <Input
                label="Nombre del Producto *"
                value={editor.nombre}
                onChange={(e) => setEditor((prev) => prev ? { ...prev, nombre: e.target.value } : null)}
                placeholder="Ej: Módulo Alacena 2 Puertas"
                required
              />
              <div className="grid grid-cols-2 gap-3">
                <Input
                  label="Código (Ref. Interna)"
                  value={editor.referencia_interna}
                  onChange={(e) => setEditor((prev) => prev ? { ...prev, referencia_interna: e.target.value } : null)}
                  placeholder="Ej: MOD-120"
                />
                <label className="flex flex-col gap-1.5">
                  <span className="text-xs font-semibold text-ink-soft">Categoría</span>
                  <select
                    value={editor.categoria}
                    onChange={(e) => setEditor((prev) => prev ? { ...prev, categoria: e.target.value } : null)}
                    className="h-11 rounded-xl border border-line bg-surface px-3 text-sm text-ink outline-none focus:border-brand w-full"
                  >
                    <option value="">— Ninguna —</option>
                    {categoryOptions.map((opt) => (
                      <option key={opt.val} value={opt.val}>
                        {opt.label}
                      </option>
                    ))}
                  </select>
                </label>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <Input
                  label="Precio de Venta ($)"
                  type="number"
                  value={String(editor.precio_venta || "")}
                  onChange={(e) => setEditor((prev) => prev ? { ...prev, precio_venta: Number(e.target.value) || 0 } : null)}
                  placeholder="0"
                />
                <Input
                  label="Stock actual"
                  type="number"
                  value={String(editor.cantidad_mano || "")}
                  onChange={(e) => setEditor((prev) => prev ? { ...prev, cantidad_mano: Number(e.target.value) || 0 } : null)}
                  placeholder="0"
                />
              </div>
              <label className="flex items-center gap-2 cursor-pointer p-2 rounded-lg hover:bg-canvas">
                <input
                  type="checkbox"
                  checked={editor.favorito}
                  onChange={(e) => setEditor((prev) => prev ? { ...prev, favorito: e.target.checked } : null)}
                  className="w-4 h-4 accent-brand"
                />
                <Star size={16} className="text-amber-400 fill-amber-400" />
                <span className="text-sm text-ink">Producto favorito (aparece arriba)</span>
              </label>
            </div>
 
            <div className="flex gap-2 justify-end mt-2">
              <Button type="button" variant="secondary" onClick={() => setEditor(null)}>Cancelar</Button>
              <Button type="button" onClick={saveEditor} loading={busyId === "editor-save"} disabled={!editor.nombre.trim()}>
                Guardar
              </Button>
            </div>
          </motion.div>
        </div>
      )}
 
      {/* Modal Editor Categoría */}
      {catEditor && (
        <div className="fixed inset-0 z-50 grid place-items-center bg-black/40 p-4" onClick={() => setCatEditor(null)}>
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-surface rounded-2xl border border-line p-6 max-w-sm w-full shadow-2xl flex flex-col gap-4 text-ink"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between border-b border-line pb-3">
              <h3 className="text-base font-extrabold text-ink">
                {catEditor.mode === "create" 
                  ? (catEditor.parent ? "Nueva Subcategoría" : "Nueva Categoría Principal")
                  : "Editar Categoría"
                }
              </h3>
              <button onClick={() => setCatEditor(null)} className="text-faint hover:text-ink">
                <X size={18} />
              </button>
            </div>
 
            <div className="grid gap-3">
              <Input
                label="Nombre de Categoría *"
                value={catEditor.nombre}
                onChange={(e) => setCatEditor((prev) => prev ? { ...prev, nombre: e.target.value } : null)}
                placeholder="Ej: Cocina, Placards, Alacenas..."
                required
                autoFocus
              />
              <Input
                label="Orden de Clasificación (Nº)"
                type="number"
                value={String(catEditor.sort_order)}
                onChange={(e) => setCatEditor((prev) => prev ? { ...prev, sort_order: Number(e.target.value) || 0 } : null)}
                placeholder="0"
              />
            </div>
 
            <div className="flex gap-2 justify-end mt-2">
              <Button type="button" variant="secondary" onClick={() => setCatEditor(null)}>Cancelar</Button>
              <Button type="button" onClick={saveCategoryEditor} loading={busyId === "cat-editor-save"} disabled={!catEditor.nombre.trim()}>
                Guardar
              </Button>
            </div>
          </motion.div>
        </div>
      )}
 
      {/* Modal Confirmación Limpieza Catálogo */}
      {showCleanupConfirm && (
        <div className="fixed inset-0 z-50 grid place-items-center bg-black/40 p-4" onClick={() => setShowCleanupConfirm(false)}>
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-surface rounded-2xl border border-line p-6 max-w-md w-full shadow-2xl flex flex-col gap-4 text-ink"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-start gap-3">
              <div className="p-2 bg-red-50 rounded-xl text-bad border border-red-100 flex-shrink-0">
                <AlertTriangle size={24} />
              </div>
              <div>
                <h3 className="text-lg font-bold text-ink">Limpieza masiva de catálogo</h3>
                <p className="text-sm text-ink-soft mt-1">
                  Se borrarán de forma masiva los **{filteredProductos.length}** productos que coinciden con los filtros de búsqueda actuales.
                </p>
                <p className="text-xs text-faint mt-2 font-medium bg-canvas p-2 rounded-lg border border-line">
                  Filtro actual: {selectedCategory === "todos" ? "Todas las categorías" : `Categoría "${selectedCategory}"`} 
                  {search && ` + Búsqueda: "${search}"`}.
                </p>
              </div>
            </div>
 
            <div className="flex gap-2 justify-end mt-2">
              <Button variant="secondary" onClick={() => setShowCleanupConfirm(false)}>Atrás</Button>
              <Button variant="danger" onClick={performCatalogCleanup} loading={busyId === "cleanup"}>
                Confirmar borrado masivo
              </Button>
            </div>
          </motion.div>
        </div>
      )}
    </div>
  );
}
