"use client";

import { useState, useTransition } from "react";
import Image from "next/image";
import Link from "next/link";
import {
  Package, Tag, Images, ShoppingBag, Plus, Edit2, Trash2, X,
  CheckCircle, XCircle, Star, StarOff, Loader2, Eye, EyeOff,
  TrendingUp, ChevronDown, Users,
} from "lucide-react";
import {
  saveCategoryAction, deleteCategoryAction,
  saveProductAction, deleteProductAction, toggleProductFeatured,
  saveSlideAction, deleteSlideAction,
  updateOrderStatusAction,
} from "./actions";

// ── Types ─────────────────────────────────────────────────────────────────────

type Category = { id: string; name: string; slug: string; parentId: string | null };
type ProductImage = { id: string; url: string; isPrimary: boolean; sortOrder: number };
type Product = {
  id: string; name: string; slug: string; description: string | null;
  price: number; stock: number; isFeatured: boolean; isActive: boolean;
  categoryId: string | null; createdAt: string;
  category: Category | null;
  images: ProductImage[];
  _count: { variations: number };
};
type Slide = { id: string; imageUrl: string; title: string | null; subtitle: string | null; ctaText: string | null; ctaLink: string | null; isActive: boolean; sortOrder: number };
type OrderItem = { id: string; quantity: number; unitPrice: number; product: { name: string } };
type Order = {
  id: string; status: string; total: number; guestEmail: string | null; createdAt: string;
  shippingName: string | null; shippingCity: string | null; shippingCountry: string | null;
  user: { name: string; email: string } | null;
  items: OrderItem[];
};
type CustomerOrder = { id: string; total: number; status: string; createdAt: string };
type Customer = {
  id: string; name: string; email: string; phone: string | null; createdAt: string;
  orders: CustomerOrder[];
  _count: { orders: number };
};

type Props = { products: Product[]; categories: Category[]; slides: Slide[]; orders: Order[]; customers: Customer[] };

const TABS = [
  { id: "products", label: "Products", icon: Package },
  { id: "categories", label: "Categories", icon: Tag },
  { id: "slider", label: "Shop Slider", icon: Images },
  { id: "orders", label: "Orders", icon: ShoppingBag },
  { id: "customers", label: "Customers", icon: Users },
] as const;
type TabId = (typeof TABS)[number]["id"];

const ORDER_STATUSES = ["pending", "paid", "shipped", "completed", "cancelled", "refunded"];

const STATUS_COLORS: Record<string, string> = {
  pending: "bg-amber-50 text-amber-700 border-amber-200",
  paid: "bg-blue-50 text-blue-700 border-blue-200",
  shipped: "bg-purple-50 text-purple-700 border-purple-200",
  completed: "bg-emerald-50 text-emerald-700 border-emerald-200",
  cancelled: "bg-red-50 text-red-700 border-red-200",
  refunded: "bg-neutral-100 text-neutral-600 border-neutral-200",
};

// ── Helpers ───────────────────────────────────────────────────────────────────

function useToast() {
  const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
  function show(type: "ok" | "err", text: string) {
    setMsg({ type, text });
    setTimeout(() => setMsg(null), 4000);
  }
  const Toast = msg ? (
    <div className={`fixed bottom-6 right-6 z-50 flex items-center gap-2.5 px-4 py-3 rounded-xl shadow-lg text-sm font-medium border ${msg.type === "ok" ? "bg-emerald-50 text-emerald-800 border-emerald-200" : "bg-red-50 text-red-700 border-red-200"}`}>
      {msg.type === "ok" ? <CheckCircle size={16} /> : <XCircle size={16} />}
      {msg.text}
    </div>
  ) : null;
  return { show, Toast };
}

function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-neutral-100">
          <h3 className="font-bold text-neutral-800">{title}</h3>
          <button onClick={onClose} className="text-neutral-400 hover:text-neutral-600"><X size={18} /></button>
        </div>
        <div className="p-6">{children}</div>
      </div>
    </div>
  );
}

function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-xs font-semibold text-neutral-500 uppercase tracking-wide mb-1.5">{label}</label>
      {children}
      {hint && <p className="text-xs text-neutral-400 mt-1">{hint}</p>}
    </div>
  );
}

function normalizeImageSrc(value: string | null | undefined): string {
  const input = (value ?? "").trim();
  if (!input) return "";
  if (input.startsWith("http://") || input.startsWith("https://") || input.startsWith("data:") || input.startsWith("blob:")) {
    return input;
  }
  if (input.startsWith("//")) {
    return `https:${input}`;
  }
  if (input.startsWith("/")) {
    return input;
  }
  return `/${input}`;
}

const inp = "w-full border border-neutral-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-navy-500";
const sel = `${inp} bg-white`;

// ── Main Component ────────────────────────────────────────────────────────────

export default function AdminProductsClient({ products, categories, slides, orders, customers }: Props) {
  const [tab, setTab] = useState<TabId>("products");
  const [isPending, startTransition] = useTransition();
  const { show, Toast } = useToast();

  // modal state
  const [modal, setModal] = useState<null | { type: "product" | "category" | "slide"; data?: unknown }>(null);
  const closeModal = () => setModal(null);

  function run(action: () => Promise<void>, msg: string) {
    startTransition(async () => {
      try { await action(); show("ok", msg); closeModal(); }
      catch { show("err", "Action failed. Please try again."); }
    });
  }

  // ── Category modal ──────────────────────────────────────────────────────────
  function CategoryModal({ cat }: { cat?: Category }) {
    return (
      <Modal title={cat ? "Edit Category" : "New Category"} onClose={closeModal}>
        <form action={(fd) => run(() => saveCategoryAction(fd), cat ? "Category updated." : "Category created.")} className="space-y-4">
          <input type="hidden" name="id" defaultValue={cat?.id ?? ""} />
          <Field label="Name"><input name="name" defaultValue={cat?.name} required className={inp} /></Field>
          <Field label="Parent Category">
            <select name="parentId" defaultValue={cat?.parentId ?? ""} className={sel}>
              <option value="">— None (top-level) —</option>
              {categories.filter(c => c.id !== cat?.id).map(c => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
          </Field>
          <div className="flex justify-end gap-3 pt-2">
            <button type="button" onClick={closeModal} className="px-4 py-2 text-sm text-neutral-600 hover:text-neutral-800">Cancel</button>
            <button type="submit" disabled={isPending} className="flex items-center gap-2 px-5 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800 disabled:opacity-60">
              {isPending && <Loader2 size={13} className="animate-spin" />} Save
            </button>
          </div>
        </form>
      </Modal>
    );
  }

  // ── Slide modal ─────────────────────────────────────────────────────────────
  function SlideModal({ slide }: { slide?: Slide }) {
    return (
      <Modal title={slide ? "Edit Slide" : "New Slide"} onClose={closeModal}>
        <form action={(fd) => run(() => saveSlideAction(fd), slide ? "Slide updated." : "Slide created.")} className="space-y-4">
          <input type="hidden" name="id" defaultValue={slide?.id ?? ""} />
          <Field label="Image URL" hint="Full URL to banner image (recommended: 1600×600px)">
            <input name="imageUrl" defaultValue={slide?.imageUrl} className={inp} placeholder="https://…" />
          </Field>
          <Field label="Or Upload Image From PC" hint="If you upload a file, it will be used instead of the URL.">
            <input name="imageFile" type="file" accept="image/*" className={inp} />
          </Field>
          <div className="grid grid-cols-2 gap-4">
            <Field label="Title"><input name="title" defaultValue={slide?.title ?? ""} className={inp} /></Field>
            <Field label="Subtitle"><input name="subtitle" defaultValue={slide?.subtitle ?? ""} className={inp} /></Field>
            <Field label="CTA Button Text"><input name="ctaText" defaultValue={slide?.ctaText ?? ""} className={inp} placeholder="Shop Now" /></Field>
            <Field label="CTA Link"><input name="ctaLink" defaultValue={slide?.ctaLink ?? ""} className={inp} placeholder="/shop" /></Field>
          </div>
          <Field label="Status">
            <select name="isActive" defaultValue={slide ? (slide.isActive ? "true" : "false") : "true"} className={sel}>
              <option value="true">Active</option>
              <option value="false">Inactive</option>
            </select>
          </Field>
          <div className="flex justify-end gap-3 pt-2">
            <button type="button" onClick={closeModal} className="px-4 py-2 text-sm text-neutral-600">Cancel</button>
            <button type="submit" disabled={isPending} className="flex items-center gap-2 px-5 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800 disabled:opacity-60">
              {isPending && <Loader2 size={13} className="animate-spin" />} Save
            </button>
          </div>
        </form>
      </Modal>
    );
  }

  // ── Product modal ───────────────────────────────────────────────────────────
  function ProductModal({ product }: { product?: Product }) {
    const [varRows, setVarRows] = useState<{ sku: string; size: string; colour: string; price: string; stock: string }[]>(
      product ? [] : []
    );

    return (
      <Modal title={product ? "Edit Product" : "New Product"} onClose={closeModal}>
        <form action={(fd) => {
          // Inject variations as JSON
          const varJson = JSON.stringify(varRows.filter(r => r.size || r.colour || r.sku).map(r => ({
            sku: r.sku || undefined,
            size: r.size || undefined,
            colour: r.colour || undefined,
            price: r.price ? parseFloat(r.price) : undefined,
            stock: r.stock ? parseInt(r.stock) : 0,
          })));
          fd.set("variations", varJson);
          run(() => saveProductAction(fd), product ? "Product updated." : "Product created.");
        }} className="space-y-5">
          <input type="hidden" name="id" defaultValue={product?.id ?? ""} />

          <div className="grid grid-cols-2 gap-4">
            <div className="col-span-2">
              <Field label="Product Name"><input name="name" defaultValue={product?.name} required className={inp} /></Field>
            </div>
            <Field label="Price (USD)"><input name="price" type="number" step="0.01" defaultValue={String(product?.price ?? "")} required className={inp} /></Field>
            <Field label="Stock Quantity"><input name="stock" type="number" defaultValue={String(product?.stock ?? "0")} className={inp} /></Field>
            <Field label="Category">
              <select name="categoryId" defaultValue={product?.categoryId ?? ""} className={sel}>
                <option value="">— No Category —</option>
                {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </Field>
            <Field label="Status">
              <select name="isActive" defaultValue={product ? (product.isActive ? "true" : "false") : "true"} className={sel}>
                <option value="true">Active</option>
                <option value="false">Inactive (hidden)</option>
              </select>
            </Field>
          </div>

          <Field label="Description">
            <textarea name="description" defaultValue={product?.description ?? ""} rows={3} className={`${inp} resize-none`} />
          </Field>

          <Field label="Image URLs" hint="One URL per line. First image will be the primary/thumbnail.">
            <textarea
              name="images"
              defaultValue={product?.images.map(i => i.url).join("\n") ?? ""}
              rows={4}
              className={`${inp} resize-none font-mono text-xs`}
              placeholder={"https://example.com/image1.jpg\nhttps://example.com/image2.jpg"}
            />
          </Field>

          <Field label="Featured">
            <select name="isFeatured" defaultValue={product ? (product.isFeatured ? "true" : "false") : "false"} className={sel}>
              <option value="false">No</option>
              <option value="true">Yes — show on home page</option>
            </select>
          </Field>

          {/* Variations */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="text-xs font-semibold text-neutral-500 uppercase tracking-wide">Variations (optional)</label>
              <button type="button" onClick={() => setVarRows(r => [...r, { sku: "", size: "", colour: "", price: "", stock: "0" }])}
                className="flex items-center gap-1 text-xs text-navy-600 hover:text-navy-800 font-medium">
                <Plus size={12} /> Add Row
              </button>
            </div>
            {varRows.length > 0 && (
              <div className="space-y-2 border border-neutral-200 rounded-xl p-3">
                <div className="grid grid-cols-6 gap-2 text-[10px] font-bold text-neutral-400 uppercase px-1">
                  <span>SKU</span><span>Size</span><span>Colour</span><span>Price</span><span>Stock</span><span></span>
                </div>
                {varRows.map((row, i) => (
                  <div key={i} className="grid grid-cols-6 gap-2 items-center">
                    {(["sku", "size", "colour", "price", "stock"] as const).map(k => (
                      <input key={k} value={row[k]} onChange={e => setVarRows(r => r.map((x, j) => j === i ? { ...x, [k]: e.target.value } : x))}
                        className="border border-neutral-300 rounded-lg px-2 py-1.5 text-xs focus:outline-none focus:border-navy-500"
                        placeholder={k} type={k === "price" || k === "stock" ? "number" : "text"} />
                    ))}
                    <button type="button" onClick={() => setVarRows(r => r.filter((_, j) => j !== i))} className="text-red-400 hover:text-red-600 flex justify-center"><X size={14} /></button>
                  </div>
                ))}
              </div>
            )}
            <input type="hidden" name="variations" value="[]" />
          </div>

          <div className="flex justify-end gap-3 pt-2">
            <button type="button" onClick={closeModal} className="px-4 py-2 text-sm text-neutral-600">Cancel</button>
            <button type="submit" disabled={isPending} className="flex items-center gap-2 px-5 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800 disabled:opacity-60">
              {isPending && <Loader2 size={13} className="animate-spin" />} Save Product
            </button>
          </div>
        </form>
      </Modal>
    );
  }

  // ── Order detail modal ──────────────────────────────────────────────────────
  const [orderDetailId, setOrderDetailId] = useState<string | null>(null);
  const detailOrder = orders.find(o => o.id === orderDetailId);

  return (
    <div className="p-8">
      {Toast}
      {modal?.type === "category" && <CategoryModal cat={modal.data as Category | undefined} />}
      {modal?.type === "slide" && <SlideModal slide={modal.data as Slide | undefined} />}
      {modal?.type === "product" && <ProductModal product={modal.data as Product | undefined} />}

      {/* Order detail modal */}
      {detailOrder && (
        <Modal title={`Order #${detailOrder.id.slice(-8).toUpperCase()}`} onClose={() => setOrderDetailId(null)}>
          <div className="space-y-4 text-sm">
            <div className="grid grid-cols-2 gap-3">
              <div><span className="text-neutral-500">Customer:</span> <span className="font-medium">{detailOrder.user?.name ?? detailOrder.guestEmail ?? "Guest"}</span></div>
              <div><span className="text-neutral-500">Email:</span> <span className="font-medium">{detailOrder.user?.email ?? detailOrder.guestEmail ?? "—"}</span></div>
              <div><span className="text-neutral-500">Ship to:</span> <span className="font-medium">{[detailOrder.shippingName, detailOrder.shippingCity, detailOrder.shippingCountry].filter(Boolean).join(", ") || "—"}</span></div>
              <div><span className="text-neutral-500">Date:</span> <span className="font-medium">{new Date(detailOrder.createdAt).toLocaleDateString()}</span></div>
            </div>
            <div className="border border-neutral-200 rounded-xl overflow-hidden">
              <table className="w-full text-xs">
                <thead className="bg-neutral-50"><tr className="text-neutral-500"><th className="px-4 py-2 text-left">Item</th><th className="px-4 py-2 text-right">Qty</th><th className="px-4 py-2 text-right">Unit Price</th><th className="px-4 py-2 text-right">Subtotal</th></tr></thead>
                <tbody>{detailOrder.items.map(item => (
                  <tr key={item.id} className="border-t border-neutral-100">
                    <td className="px-4 py-2">{item.product.name}</td>
                    <td className="px-4 py-2 text-right">{item.quantity}</td>
                    <td className="px-4 py-2 text-right">${Number(item.unitPrice).toFixed(2)}</td>
                    <td className="px-4 py-2 text-right font-medium">${(Number(item.unitPrice) * item.quantity).toFixed(2)}</td>
                  </tr>
                ))}</tbody>
                <tfoot className="bg-neutral-50 border-t border-neutral-200"><tr><td colSpan={3} className="px-4 py-2 font-bold text-right">Total</td><td className="px-4 py-2 font-bold text-right">${Number(detailOrder.total).toFixed(2)}</td></tr></tfoot>
              </table>
            </div>
            <div>
              <label className="text-xs font-semibold text-neutral-500 uppercase tracking-wide block mb-2">Update Status</label>
              <div className="flex gap-2 flex-wrap">
                {ORDER_STATUSES.map(s => (
                  <button key={s} onClick={() => run(() => updateOrderStatusAction(detailOrder.id, s), `Order marked as ${s}.`)}
                    className={`px-3 py-1.5 rounded-lg text-xs font-semibold border transition-colors ${detailOrder.status === s ? STATUS_COLORS[s] : "border-neutral-200 text-neutral-500 hover:border-neutral-400"}`}>
                    {s.charAt(0).toUpperCase() + s.slice(1)}
                  </button>
                ))}
              </div>
            </div>
          </div>
        </Modal>
      )}

      <div className="mb-8">
        <h1 className="text-2xl font-bold text-neutral-900">E Commerce Management</h1>
        <p className="text-neutral-500 text-sm mt-0.5">Manage products, categories, slider, orders, and customers</p>
      </div>

      {/* Tabs */}
      <div className="flex gap-2 mb-6 border-b border-neutral-200">
        {TABS.map((t) => {
          const Icon = t.icon;
          return (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={`flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${tab === t.id ? "border-navy-600 text-navy-700" : "border-transparent text-neutral-500 hover:text-neutral-700"}`}
            >
              <Icon size={16} />
              {t.label}
            </button>
          );
        })}
      </div>

          {/* ── PRODUCTS ── */}
          {tab === "products" && (
            <div>
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-lg font-bold text-neutral-800">All Products</h2>
                <button onClick={() => setModal({ type: "product" })} className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800">
                  <Plus size={15} /> Add Product
                </button>
              </div>

              {products.length === 0 ? (
                <div className="bg-white rounded-2xl border border-neutral-200 p-16 text-center text-neutral-400">
                  <Package size={40} className="mx-auto mb-3 opacity-30" />
                  <p className="text-sm">No products yet. Add your first one.</p>
                </div>
              ) : (
                <div className="bg-white rounded-2xl border border-neutral-200 overflow-hidden">
                  <table className="w-full text-sm">
                    <thead className="bg-neutral-50 border-b border-neutral-200">
                      <tr className="text-xs font-semibold text-neutral-500 uppercase tracking-wide">
                        <th className="px-4 py-3 text-left">Product</th>
                        <th className="px-4 py-3 text-left">Category</th>
                        <th className="px-4 py-3 text-right">Price</th>
                        <th className="px-4 py-3 text-right">Stock</th>
                        <th className="px-4 py-3 text-center">Status</th>
                        <th className="px-4 py-3 text-center">Featured</th>
                        <th className="px-4 py-3 text-center">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-neutral-100">
                      {products.map(p => (
                        <tr key={p.id} className="hover:bg-neutral-50">
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-3">
                              {p.images[0] ? (
                                <Image src={p.images[0].url} alt={p.name} width={40} height={40} className="rounded-lg object-cover w-10 h-10" unoptimized />
                              ) : (
                                <div className="w-10 h-10 rounded-lg bg-neutral-100 flex items-center justify-center"><Package size={16} className="text-neutral-300" /></div>
                              )}
                              <div>
                                <div className="font-medium text-neutral-800">{p.name}</div>
                                <div className="text-xs text-neutral-400">{p._count.variations} variation{p._count.variations !== 1 ? "s" : ""}</div>
                              </div>
                            </div>
                          </td>
                          <td className="px-4 py-3 text-neutral-500">{p.category?.name ?? "—"}</td>
                          <td className="px-4 py-3 text-right font-medium">${Number(p.price).toFixed(2)}</td>
                          <td className="px-4 py-3 text-right">
                            <span className={`font-medium ${p.stock === 0 ? "text-red-500" : p.stock < 5 ? "text-amber-500" : "text-neutral-700"}`}>{p.stock}</span>
                          </td>
                          <td className="px-4 py-3 text-center">
                            <span className={`inline-flex px-2.5 py-1 rounded-full text-xs font-semibold border ${p.isActive ? "bg-emerald-50 text-emerald-700 border-emerald-200" : "bg-neutral-100 text-neutral-500 border-neutral-200"}`}>
                              {p.isActive ? "Active" : "Hidden"}
                            </span>
                          </td>
                          <td className="px-4 py-3 text-center">
                            <button onClick={() => run(() => toggleProductFeatured(p.id, !p.isFeatured), p.isFeatured ? "Removed from featured." : "Marked as featured.")}
                              className={`transition-colors ${p.isFeatured ? "text-amber-500 hover:text-amber-600" : "text-neutral-300 hover:text-amber-400"}`}>
                              {p.isFeatured ? <Star size={18} fill="currentColor" /> : <StarOff size={18} />}
                            </button>
                          </td>
                          <td className="px-4 py-3 text-center">
                            <div className="flex items-center justify-center gap-2">
                              <button onClick={() => setModal({ type: "product", data: p })} className="p-1.5 text-neutral-400 hover:text-navy-600 hover:bg-navy-50 rounded-lg"><Edit2 size={14} /></button>
                              <button onClick={() => {
                                // TODO(security): Replace native confirm() with custom modal dialog to avoid blocking main thread.
                                if (confirm(`Delete "${p.name}"?`)) run(() => deleteProductAction(p.id), "Product deleted.");
                              }}
                                className="p-1.5 text-neutral-400 hover:text-red-600 hover:bg-red-50 rounded-lg"><Trash2 size={14} /></button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}

          {/* ── CATEGORIES ── */}
          {tab === "categories" && (
            <div>
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-lg font-bold text-neutral-800">Product Categories</h2>
                <button onClick={() => setModal({ type: "category" })} className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800">
                  <Plus size={15} /> Add Category
                </button>
              </div>
              {categories.length === 0 ? (
                <div className="bg-white rounded-2xl border border-neutral-200 p-16 text-center text-neutral-400">
                  <Tag size={40} className="mx-auto mb-3 opacity-30" />
                  <p className="text-sm">No categories yet.</p>
                </div>
              ) : (
                <div className="bg-white rounded-2xl border border-neutral-200 overflow-hidden">
                  <table className="w-full text-sm">
                    <thead className="bg-neutral-50 border-b border-neutral-200">
                      <tr className="text-xs font-semibold text-neutral-500 uppercase tracking-wide">
                        <th className="px-4 py-3 text-left">Name</th>
                        <th className="px-4 py-3 text-left">Slug</th>
                        <th className="px-4 py-3 text-left">Parent</th>
                        <th className="px-4 py-3 text-center">Products</th>
                        <th className="px-4 py-3 text-center">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-neutral-100">
                      {categories.map(c => (
                        <tr key={c.id} className="hover:bg-neutral-50">
                          <td className="px-4 py-3 font-medium text-neutral-800">{c.name}</td>
                          <td className="px-4 py-3 text-neutral-400 font-mono text-xs">{c.slug}</td>
                          <td className="px-4 py-3 text-neutral-500">{categories.find(x => x.id === c.parentId)?.name ?? "—"}</td>
                          <td className="px-4 py-3 text-center text-neutral-600">{products.filter(p => p.categoryId === c.id).length}</td>
                          <td className="px-4 py-3 text-center">
                            <div className="flex items-center justify-center gap-2">
                              <button onClick={() => setModal({ type: "category", data: c })} className="p-1.5 text-neutral-400 hover:text-navy-600 hover:bg-navy-50 rounded-lg"><Edit2 size={14} /></button>
                              <button onClick={() => {
                                // TODO(security): Replace native confirm() with custom modal dialog to avoid blocking main thread.
                                if (confirm(`Delete "${c.name}"?`)) run(() => deleteCategoryAction(c.id), "Category deleted.");
                              }}
                                className="p-1.5 text-neutral-400 hover:text-red-600 hover:bg-red-50 rounded-lg"><Trash2 size={14} /></button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}

          {/* ── SLIDER ── */}
          {tab === "slider" && (
            <div>
              <div className="flex items-center justify-between mb-6">
                <div>
                  <h2 className="text-lg font-bold text-neutral-800">Shop Banner Slides</h2>
                  <p className="text-sm text-neutral-400 mt-0.5">These appear in the hero carousel on the shop page.</p>
                </div>
                <button onClick={() => setModal({ type: "slide" })} className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800">
                  <Plus size={15} /> Add Slide
                </button>
              </div>
              {slides.length === 0 ? (
                <div className="bg-white rounded-2xl border border-neutral-200 p-16 text-center text-neutral-400">
                  <Images size={40} className="mx-auto mb-3 opacity-30" />
                  <p className="text-sm">No slides yet. The shop page will show a static header.</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {slides.map(s => (
                    <div key={s.id} className="bg-white rounded-2xl border border-neutral-200 p-4 flex items-center gap-4">
                      <Image src={normalizeImageSrc(s.imageUrl)} alt={s.title ?? "Slide"} width={120} height={45} className="rounded-xl object-cover w-[120px] h-[45px]" />
                      <div className="flex-1 min-w-0">
                        <div className="font-medium text-neutral-800 truncate">{s.title ?? <span className="text-neutral-400 italic">No title</span>}</div>
                        <div className="text-xs text-neutral-400 truncate">{s.subtitle}</div>
                        {s.ctaLink && <div className="text-xs font-mono text-navy-500 mt-0.5">{s.ctaLink}</div>}
                      </div>
                      <span className={`px-2.5 py-1 rounded-full text-xs font-semibold border ${s.isActive ? "bg-emerald-50 text-emerald-700 border-emerald-200" : "bg-neutral-100 text-neutral-500 border-neutral-200"}`}>
                        {s.isActive ? "Active" : "Hidden"}
                      </span>
                      <div className="flex gap-2">
                        <button onClick={() => setModal({ type: "slide", data: s })} className="p-1.5 text-neutral-400 hover:text-navy-600 hover:bg-navy-50 rounded-lg"><Edit2 size={14} /></button>
                        <button onClick={() => {
                          // TODO(security): Replace native confirm() with custom modal dialog to avoid blocking main thread.
                          if (confirm("Delete this slide?")) run(() => deleteSlideAction(s.id), "Slide deleted.");
                        }}
                          className="p-1.5 text-neutral-400 hover:text-red-600 hover:bg-red-50 rounded-lg"><Trash2 size={14} /></button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* ── ORDERS ── */}
          {tab === "orders" && (
            <div>
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-lg font-bold text-neutral-800">All Orders</h2>
                <div className="text-sm text-neutral-400">{orders.length} total</div>
              </div>
              {orders.length === 0 ? (
                <div className="bg-white rounded-2xl border border-neutral-200 p-16 text-center text-neutral-400">
                  <ShoppingBag size={40} className="mx-auto mb-3 opacity-30" />
                  <p className="text-sm">No orders yet.</p>
                </div>
              ) : (
                <div className="bg-white rounded-2xl border border-neutral-200 overflow-hidden">
                  <table className="w-full text-sm">
                    <thead className="bg-neutral-50 border-b border-neutral-200">
                      <tr className="text-xs font-semibold text-neutral-500 uppercase tracking-wide">
                        <th className="px-4 py-3 text-left">Order</th>
                        <th className="px-4 py-3 text-left">Customer</th>
                        <th className="px-4 py-3 text-left">Items</th>
                        <th className="px-4 py-3 text-right">Total</th>
                        <th className="px-4 py-3 text-center">Status</th>
                        <th className="px-4 py-3 text-left">Date</th>
                        <th className="px-4 py-3 text-center">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-neutral-100">
                      {orders.map(o => (
                        <tr key={o.id} className="hover:bg-neutral-50">
                          <td className="px-4 py-3 font-mono text-xs text-neutral-500">#{o.id.slice(-8).toUpperCase()}</td>
                          <td className="px-4 py-3">
                            <div className="font-medium text-neutral-800">{o.user?.name ?? o.guestEmail ?? "Guest"}</div>
                            <div className="text-xs text-neutral-400">{o.user?.email ?? ""}</div>
                          </td>
                          <td className="px-4 py-3 text-neutral-500 text-xs">{o.items.length} item{o.items.length !== 1 ? "s" : ""}</td>
                          <td className="px-4 py-3 text-right font-semibold text-neutral-800">${Number(o.total).toFixed(2)}</td>
                          <td className="px-4 py-3 text-center">
                            <span className={`inline-flex px-2.5 py-1 rounded-full text-xs font-semibold border ${STATUS_COLORS[o.status] ?? ""}`}>
                              {o.status.charAt(0).toUpperCase() + o.status.slice(1)}
                            </span>
                          </td>
                          <td className="px-4 py-3 text-neutral-500 text-xs">{new Date(o.createdAt).toLocaleDateString()}</td>
                          <td className="px-4 py-3 text-center">
                            <button onClick={() => setOrderDetailId(o.id)} className="p-1.5 text-neutral-400 hover:text-navy-600 hover:bg-navy-50 rounded-lg"><Eye size={14} /></button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}

          {tab === "customers" && (
            <div>
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-lg font-bold text-neutral-800">All Customers</h2>
                <div className="text-sm text-neutral-400">{customers.length} total</div>
              </div>
              {customers.length === 0 ? (
                <div className="bg-white rounded-2xl border border-neutral-200 p-16 text-center text-neutral-400">
                  <Users size={40} className="mx-auto mb-3 opacity-30" />
                  <p className="text-sm">No customers yet.</p>
                </div>
              ) : (
                <div className="bg-white rounded-2xl border border-neutral-200 overflow-hidden">
                  <table className="w-full text-sm">
                    <thead className="bg-neutral-50 border-b border-neutral-200">
                      <tr className="text-xs font-semibold text-neutral-500 uppercase tracking-wide">
                        <th className="px-4 py-3 text-left">Customer</th>
                        <th className="px-4 py-3 text-left">Contact</th>
                        <th className="px-4 py-3 text-center">Orders</th>
                        <th className="px-4 py-3 text-right">Total Spent</th>
                        <th className="px-4 py-3 text-left">Last Order</th>
                        <th className="px-4 py-3 text-left">Member Since</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-neutral-100">
                      {customers.map(c => {
                        const totalSpent = c.orders.reduce((sum, o) => sum + Number(o.total), 0);
                        const lastOrder = c.orders[0];
                        return (
                          <tr key={c.id} className="hover:bg-neutral-50">
                            <td className="px-4 py-3">
                              <div className="font-medium text-neutral-800">{c.name}</div>
                              <div className="text-xs text-neutral-400 font-mono">ID: {c.id.slice(-8).toUpperCase()}</div>
                            </td>
                            <td className="px-4 py-3">
                              <div className="text-neutral-700">{c.email}</div>
                              {c.phone && <div className="text-xs text-neutral-400">{c.phone}</div>}
                            </td>
                            <td className="px-4 py-3 text-center">
                              <span className="inline-flex px-2.5 py-1 rounded-full text-xs font-semibold bg-navy-50 text-navy-700 border border-navy-200">
                                {c._count.orders}
                              </span>
                            </td>
                            <td className="px-4 py-3 text-right font-semibold text-neutral-800">${totalSpent.toFixed(2)}</td>
                            <td className="px-4 py-3">
                              {lastOrder && (
                                <div>
                                  <div className="text-xs text-neutral-500">{new Date(lastOrder.createdAt).toLocaleDateString()}</div>
                                  <span className={`inline-flex px-1.5 py-0.5 mt-1 rounded text-[10px] font-semibold border ${STATUS_COLORS[lastOrder.status] ?? ""}`}>
                                    {lastOrder.status}
                                  </span>
                                </div>
                              )}
                            </td>
                            <td className="px-4 py-3 text-xs text-neutral-500">{new Date(c.createdAt).toLocaleDateString()}</td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}

    </div>
  );
}
