"use client";

/**
 * Product catalog lists (API reference: "Product catalog"): set up once, then picked in
 * the product form.
 *
 * - Categories: groups and the categories inside them (products use categories, not groups).
 * - Certifications, Attributes (with values, e.g. Packaging → 25 kg bag) and Detail labels
 *   (the "Used in:" lines under Product Details).
 *
 * Names are per language (English required). Items used by a product can't be deleted:
 * the API's 409 message names the products. A value's slug never changes once created.
 */
import { useQueryClient } from "@tanstack/react-query";
import { useState, type ReactNode } from "react";
import { errorMessage, fieldErrors, getAccessToken } from "@/app/(admin)/_lib/api";
import type { Img } from "@/app/(admin)/_lib/cms";
import {
  attributesApi,
  categoriesApi,
  certificationsApi,
  detailLabelsApi,
  isSlug,
  slugify,
  tr,
  type Attribute,
  type Category,
  type Certification,
  type DetailLabel,
  type Translations,
} from "@/app/(admin)/_lib/products";
import { qk, useAttributes, useCategories, useCertifications, useDetailLabels, useLanguages } from "@/app/(admin)/_lib/queries";
import { refreshSiteContent } from "@/app/(admin)/_lib/siteCache";
import { useStore } from "@/app/(admin)/_lib/store";
import { Icon } from "./Icon";
import { ConfirmDialog, Modal } from "./Modal";
import { SchemaField } from "./SchemaField";
import { PageHeader, Seg } from "./ui";

const TABS = ["Categories", "Certifications", "Attributes", "Detail labels"] as const;
type Tab = (typeof TABS)[number];
type ListKey = "categories" | "certifications" | "attributes" | "detail-labels";

/** Active languages, English first. */
export function useActiveLangs() {
  const { data } = useLanguages();
  const langs = (data ?? []).filter((l) => l.isActive).sort((a, b) => (a.code === "en" ? -1 : b.code === "en" ? 1 : a.sortOrder - b.sortOrder));
  return langs.length ? langs : [{ code: "en", name: "English", nativeName: "English", bcp47: "en", dir: "ltr" as const, isActive: true, sortOrder: 0, createdAt: "", updatedAt: "" }];
}

/** After a catalog change: reload the list, and clear the website's product cache (names show on product pages). */
function useAfterChange() {
  const qc = useQueryClient();
  return async (list: ListKey) => {
    await qc.invalidateQueries({ queryKey: qk.catalog(list) });
    const token = getAccessToken();
    if (token) void refreshSiteContent("products", token).catch(() => undefined);
  };
}

export function CatalogPage() {
  const [tab, setTab] = useState<Tab>("Categories");
  return (
    <div className="page">
      <PageHeader crumb="Website › Products" title="Product Catalog" desc="The lists products are built from: categories, certifications, attributes for variants, and detail labels. Names are translated per language." />
      <div style={{ marginBottom: 16 }}>
        <Seg label="Catalog list" options={TABS} value={tab} onChange={setTab} />
      </div>
      {tab === "Categories" && <CategoriesTab />}
      {tab === "Certifications" && <CertificationsTab />}
      {tab === "Attributes" && <AttributesTab />}
      {tab === "Detail labels" && <DetailLabelsTab />}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Shared bits                                                         */
/* ------------------------------------------------------------------ */

export function ListState({ pending, error, retry, cols, empty }: { pending: boolean; error: unknown; retry: () => void; cols: number; empty: string | null }) {
  if (pending)
    return (
      <tr>
        <td className="empty" colSpan={cols}>
          <span className="spin dark" /> Loading…
        </td>
      </tr>
    );
  if (error)
    return (
      <tr>
        <td className="empty" colSpan={cols}>
          {errorMessage(error)}{" "}
          <button type="button" className="link" onClick={retry}>
            Retry
          </button>
        </td>
      </tr>
    );
  if (empty)
    return (
      <tr>
        <td className="empty" colSpan={cols}>
          {empty}
        </td>
      </tr>
    );
  return null;
}

/** Up / down buttons: `onMove` gets the list's ids in the new order. */
export function MoveButtons({ ids, id, onMove, label }: { ids: string[]; id: string; onMove: (ids: string[]) => void; label: string }) {
  const i = ids.indexOf(id);
  const move = (d: -1 | 1) => {
    const next = [...ids];
    [next[i], next[i + d]] = [next[i + d], next[i]];
    onMove(next);
  };
  return (
    <span className="repeat-tools" style={{ display: "inline-flex", gap: 2 }}>
      <button type="button" className="btn-plain" aria-label={`Move ${label} up`} title="Move up" disabled={i <= 0} onClick={() => move(-1)}>
        ↑
      </button>
      <button type="button" className="btn-plain" aria-label={`Move ${label} down`} title="Move down" disabled={i < 0 || i >= ids.length - 1} onClick={() => move(1)}>
        ↓
      </button>
    </span>
  );
}

/** Language badges: which languages have a name. */
export function LangTags({ t }: { t: Translations<Record<string, unknown>> }) {
  return (
    <span className="sec-tags">
      {Object.keys(t).map((l) => (
        <span key={l} className="tag b">
          {l.toUpperCase()}
        </span>
      ))}
    </span>
  );
}

export const Active = ({ on }: { on: boolean }) => <span className={`tag ${on ? "g" : "n"}`}>{on ? "Active" : "Hidden"}</span>;

/** Reorder with an optimistic toast; errors are shown. */
function useReorder(list: ListKey) {
  const { toast } = useStore();
  const after = useAfterChange();
  return async (run: () => Promise<unknown>) => {
    try {
      await run();
      await after(list);
      toast("Order saved");
    } catch (e) {
      toast(errorMessage(e));
    }
  };
}

/** Delete with the API's 409 ("used by products: …") shown in the dialog. */
function DeleteDialog({ name, list, run, onClose }: { name: string; list: ListKey; run: () => Promise<unknown>; onClose: () => void }) {
  const { toast } = useStore();
  const after = useAfterChange();
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  return (
    <ConfirmDialog
      title={`Delete ${name}?`}
      confirmLabel="Delete"
      danger
      busy={busy}
      onClose={onClose}
      onConfirm={async () => {
        setBusy(true);
        setErr(null);
        try {
          await run();
          await after(list);
          toast(`Deleted ${name}`);
          onClose();
        } catch (e) {
          setErr(errorMessage(e));
        } finally {
          setBusy(false);
        }
      }}
    >
      It is removed in every language. Items still used by a product can&apos;t be deleted.
      {err && <div className="form-error">{err}</div>}
    </ConfirmDialog>
  );
}

/* ------------------------------------------------------------------ */
/* Item form (name per language, slug, image, active)                  */
/* ------------------------------------------------------------------ */

export type ItemForm = {
  slug: string;
  /** lang → { name|label, description } */
  t: Record<string, { text: string; description: string }>;
  image: Img | null;
  isActive: boolean;
  parentId: string | null;
};

export type ItemConfig = {
  /** "name" (categories, certifications, attributes) or "label" (detail labels, attribute values). */
  textKey: "name" | "label";
  textLabel: string;
  textMax: number;
  description?: boolean;
  image?: { key: "image" | "logo"; label: string };
  active?: boolean;
  /** Category groups to choose from (null: this is a group). */
  groups?: Category[];
};

export const toForm = (cfg: ItemConfig, item?: { slug: string; translations: Translations<Record<string, unknown>>; isActive?: boolean; parentId?: string | null } & Record<string, unknown>): ItemForm => ({
  slug: item?.slug ?? "",
  t: Object.fromEntries(
    Object.entries(item?.translations ?? {}).map(([l, v]) => [l, { text: String(v?.[cfg.textKey] ?? ""), description: String(v?.description ?? "") }]),
  ),
  image: (cfg.image && (item?.[cfg.image.key] as Img | null)) || null,
  isActive: item?.isActive ?? true,
  parentId: item?.parentId ?? null,
});

/** Translations for the API: languages with a name; on update, null for a language that was removed (never English). */
function translationsBody(cfg: ItemConfig, f: ItemForm, before?: ItemForm) {
  const out: Record<string, Record<string, string> | null> = {};
  for (const [l, v] of Object.entries(f.t)) {
    if (!v.text.trim()) continue;
    out[l] = { [cfg.textKey]: v.text.trim(), ...(cfg.description && v.description.trim() ? { description: v.description.trim() } : {}) };
  }
  if (before)
    for (const l of Object.keys(before.t)) {
      if (l !== "en" && !out[l]) out[l] = null;
      // Unchanged languages don't need sending.
      else if (out[l] && JSON.stringify(out[l]) === JSON.stringify(translationsBody(cfg, { ...before, t: { [l]: before.t[l] } })[l])) delete out[l];
    }
  return out;
}

export function ItemModal({
  title,
  cfg,
  initial,
  onClose,
  onSubmit,
  children,
}: {
  title: string;
  cfg: ItemConfig;
  initial?: ItemForm;
  onClose: () => void;
  /** Returns the saved item, or throws (field errors are shown). */
  onSubmit: (f: ItemForm) => Promise<unknown>;
  children?: ReactNode;
}) {
  const langs = useActiveLangs();
  const [f, setF] = useState<ItemForm>(initial ?? { slug: "", t: {}, image: null, isActive: true, parentId: null });
  const [lang, setLang] = useState("en");
  const [slugTouched, setSlugTouched] = useState(!!initial);
  const [errs, setErrs] = useState<Record<string, string>>({});
  const [err, setErr] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const cur = f.t[lang] ?? { text: "", description: "" };
  const setT = (patch: Partial<ItemForm["t"][string]>) => setF((x) => ({ ...x, t: { ...x.t, [lang]: { ...cur, ...patch } } }));
  const slug = slugTouched ? f.slug : slugify(f.t.en?.text ?? "");
  const slugProblem = slug && !isSlug(slug) ? "Lowercase letters and numbers joined by single hyphens." : null;
  const editing = !!initial;

  const submit = async () => {
    setBusy(true);
    setErr(null);
    try {
      await onSubmit({ ...f, slug });
      onClose();
    } catch (e) {
      setErrs(fieldErrors(e));
      setErr(errorMessage(e));
    } finally {
      setBusy(false);
    }
  };

  return (
    <Modal title={title} onClose={onClose} wide>
      <div className="field">
        <div className="seg" role="group" aria-label="Language">
          {langs.map((l) => (
            <button key={l.code} type="button" className={l.code === lang ? "on" : ""} aria-pressed={l.code === lang} title={l.name} onClick={() => setLang(l.code)}>
              {l.code.toUpperCase()}
              {f.t[l.code]?.text.trim() ? "" : l.code === "en" ? " *" : " ·"}
            </button>
          ))}
        </div>
        <div className="hint">English is required. A language left empty falls back to English on the website.</div>
      </div>
      <div className="field">
        <label htmlFor="ci-text">
          {cfg.textLabel} ({langs.find((l) => l.code === lang)?.name ?? lang})
          {lang === "en" && <span className="req"> *</span>}
        </label>
        <input id="ci-text" className="input" maxLength={cfg.textMax} value={cur.text} onChange={(e) => setT({ text: e.target.value })} aria-invalid={!!errs[`translations.${lang}.${cfg.textKey}`]} />
        {errs[`translations.${lang}.${cfg.textKey}`] && <div className="hint bad">{errs[`translations.${lang}.${cfg.textKey}`]}</div>}
      </div>
      {cfg.description && (
        <div className="field">
          <label htmlFor="ci-desc">Description (optional)</label>
          <textarea id="ci-desc" className="input" rows={3} maxLength={1000} value={cur.description} onChange={(e) => setT({ description: e.target.value })} />
        </div>
      )}
      <div className="form-grid">
        <div className="field">
          <label htmlFor="ci-slug">
            Slug <span className="req">*</span>
          </label>
          <input
            id="ci-slug"
            className="input input-sm"
            maxLength={80}
            value={slug}
            disabled={editing}
            onChange={(e) => {
              setSlugTouched(true);
              setF((x) => ({ ...x, slug: e.target.value.toLowerCase() }));
            }}
            aria-invalid={!!(slugProblem || errs.slug)}
          />
          {editing ? <div className="hint">Fixed once created (used in website filter links).</div> : (slugProblem || errs.slug) && <div className="hint bad">{slugProblem ?? errs.slug}</div>}
        </div>
        {cfg.groups && (
          <div className="field">
            <label htmlFor="ci-parent">Group</label>
            <select id="ci-parent" className="select input" value={f.parentId ?? ""} disabled={editing && !f.parentId} onChange={(e) => setF((x) => ({ ...x, parentId: e.target.value || null }))}>
              {(!editing || !f.parentId) && <option value="">— This is a group —</option>}
              {cfg.groups.map((g) => (
                <option key={g.id} value={g.id}>
                  {tr(g.translations, "en", "name")}
                </option>
              ))}
            </select>
          </div>
        )}
      </div>
      {cfg.image && (
        <SchemaField
          field={{ kind: "image", key: cfg.image.key, label: cfg.image.label }}
          value={f.image ?? {}}
          onChange={(v) => setF((x) => ({ ...x, image: v && typeof v === "object" && (v as Img).url ? (v as Img) : null }))}
          errors={errs}
          path={cfg.image.key}
        />
      )}
      {cfg.active && (
        <div className="field">
          <label className="check">
            <input type="checkbox" checked={f.isActive} onChange={(e) => setF((x) => ({ ...x, isActive: e.target.checked }))} />
            <span>Active (inactive items are hidden on the website)</span>
          </label>
        </div>
      )}
      {children}
      {err && <div className="form-error">{err}</div>}
      <div className="modal-actions">
        <button type="button" className="btn btn-outline btn-sm" onClick={onClose}>
          Cancel
        </button>
        <button type="button" className="btn btn-primary btn-sm" disabled={busy || !slug || !!slugProblem || !f.t.en?.text.trim()} onClick={submit}>
          {busy ? <span className="spin" /> : editing ? "Save" : "Create"}
        </button>
      </div>
    </Modal>
  );
}

/** Create / update body of a catalog item. */
export function itemBody(cfg: ItemConfig, f: ItemForm, before?: ItemForm): Record<string, unknown> {
  const body: Record<string, unknown> = {};
  const t = translationsBody(cfg, f, before);
  if (!before) body.slug = f.slug;
  if (!before || Object.keys(t).length) body.translations = t;
  if (cfg.image) {
    const img = f.image?.url ? { url: f.image.url, ...(f.image.alt?.trim() ? { alt: f.image.alt.trim() } : {}) } : null;
    if (!before || JSON.stringify(img) !== JSON.stringify(before.image?.url ? { url: before.image.url, ...(before.image.alt?.trim() ? { alt: before.image.alt.trim() } : {}) } : null)) {
      if (img || before) body[cfg.image.key] = img;
    }
  }
  if (cfg.active && (!before || f.isActive !== before.isActive)) body.isActive = f.isActive;
  if (cfg.groups && (!before ? f.parentId : f.parentId !== before.parentId)) body.parentId = f.parentId;
  return body;
}

/* ------------------------------------------------------------------ */
/* Categories                                                          */
/* ------------------------------------------------------------------ */

function CategoriesTab() {
  const { data, error, isPending, refetch } = useCategories();
  const after = useAfterChange();
  const { toast } = useStore();
  const reorder = useReorder("categories");
  const [open, setOpen] = useState<{ item?: Category; parentId?: string | null } | null>(null);
  const [deleting, setDeleting] = useState<Category | null>(null);
  const groups = data ?? [];
  const cfg: ItemConfig = { textKey: "name", textLabel: "Name", textMax: 120, description: true, image: { key: "image", label: "Image (optional)" }, active: true, groups };

  const row = (c: Category, ids: string[], depth: number) => (
    <tr key={c.id}>
      <td style={{ paddingLeft: 16 + depth * 28 }}>
        <b style={{ fontWeight: depth ? 500 : 600 }}>{tr(c.translations, "en", "name")}</b>
        {depth === 0 && <span className="tag n" style={{ marginLeft: 8 }}>Group</span>}
      </td>
      <td style={{ color: "var(--muted)" }}>{c.slug}</td>
      <td>
        <LangTags t={c.translations} />
      </td>
      <td>
        <Active on={c.isActive} />
      </td>
      <td>
        <div style={{ display: "flex", gap: 6, justifyContent: "flex-end", alignItems: "center" }}>
          <MoveButtons ids={ids} id={c.id} label={tr(c.translations, "en", "name")} onMove={(next) => reorder(() => categoriesApi.reorder(next))} />
          {depth === 0 && (
            <button type="button" className="btn-plain" onClick={() => setOpen({ parentId: c.id })}>
              <Icon name="plus" size={14} /> Category
            </button>
          )}
          <button type="button" className="btn btn-outline btn-sm" onClick={() => setOpen({ item: c })}>
            Edit
          </button>
          <button type="button" className="btn-plain danger" onClick={() => setDeleting(c)}>
            Delete
          </button>
        </div>
      </td>
    </tr>
  );

  return (
    <div className="card">
      <div className="card-h">
        <div>
          <h3>Categories</h3>
          <div className="sub">Groups and the categories inside them. Products are filed under categories; the website&apos;s filters list them by group.</div>
        </div>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => setOpen({ parentId: null })}>
          <Icon name="plus" size={14} />
          New group
        </button>
      </div>
      <div className="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Name (English)</th>
              <th>Slug</th>
              <th>Languages</th>
              <th>Website</th>
              <th>
                <span className="sr-only">Actions</span>
              </th>
            </tr>
          </thead>
          <tbody>
            <ListState pending={isPending} error={error} retry={refetch} cols={5} empty={groups.length ? null : "No categories yet. Start with a group (e.g. Agricultural & Food Ingredients)."} />
            {groups.map((g) => [row(g, groups.map((x) => x.id), 0), ...(g.children ?? []).map((c) => row(c, (g.children ?? []).map((x) => x.id), 1))])}
          </tbody>
        </table>
      </div>
      {open && (
        <ItemModal
          title={open.item ? `Edit ${tr(open.item.translations, "en", "name")}` : open.parentId ? `New category in ${tr(groups.find((g) => g.id === open.parentId)?.translations, "en", "name")}` : "New group"}
          cfg={cfg}
          initial={open.item ? toForm(cfg, open.item as never) : { slug: "", t: {}, image: null, isActive: true, parentId: open.parentId ?? null }}
          onClose={() => setOpen(null)}
          onSubmit={async (f) => {
            if (open.item) await categoriesApi.update(open.item.id, itemBody(cfg, f, toForm(cfg, open.item as never)));
            else await categoriesApi.create(itemBody(cfg, f));
            await after("categories");
            toast(open.item ? "Saved" : "Created");
          }}
        />
      )}
      {deleting && <DeleteDialog name={tr(deleting.translations, "en", "name")} list="categories" run={() => categoriesApi.remove(deleting.id)} onClose={() => setDeleting(null)} />}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Certifications and detail labels (flat sortable lists)              */
/* ------------------------------------------------------------------ */

function FlatTab<T extends Certification | DetailLabel>({
  list,
  title,
  sub,
  newLabel,
  cfg,
  query,
  api,
  emptyText,
}: {
  list: "certifications" | "detail-labels";
  title: string;
  sub: string;
  newLabel: string;
  cfg: ItemConfig;
  query: { data?: T[]; error: unknown; isPending: boolean; refetch: () => void };
  api: typeof certificationsApi | typeof detailLabelsApi;
  emptyText: string;
}) {
  const after = useAfterChange();
  const { toast } = useStore();
  const reorder = useReorder(list);
  const [open, setOpen] = useState<{ item?: T } | null>(null);
  const [deleting, setDeleting] = useState<T | null>(null);
  const items = query.data ?? [];
  const ids = items.map((x) => x.id);
  const name = (x: T) => tr(x.translations as Translations<Record<string, unknown>>, "en", cfg.textKey);

  return (
    <div className="card">
      <div className="card-h">
        <div>
          <h3>{title}</h3>
          <div className="sub">{sub}</div>
        </div>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => setOpen({})}>
          <Icon name="plus" size={14} />
          {newLabel}
        </button>
      </div>
      <div className="table-wrap">
        <table>
          <thead>
            <tr>
              <th>{cfg.textLabel} (English)</th>
              <th>Slug</th>
              <th>Languages</th>
              {cfg.active && <th>Website</th>}
              <th>
                <span className="sr-only">Actions</span>
              </th>
            </tr>
          </thead>
          <tbody>
            <ListState pending={query.isPending} error={query.error} retry={query.refetch} cols={cfg.active ? 5 : 4} empty={items.length ? null : emptyText} />
            {items.map((x) => (
              <tr key={x.id}>
                <td>
                  <b style={{ fontWeight: 500 }}>{name(x)}</b>
                </td>
                <td style={{ color: "var(--muted)" }}>{x.slug}</td>
                <td>
                  <LangTags t={x.translations as Translations<Record<string, unknown>>} />
                </td>
                {cfg.active && (
                  <td>
                    <Active on={(x as Certification).isActive} />
                  </td>
                )}
                <td>
                  <div style={{ display: "flex", gap: 6, justifyContent: "flex-end", alignItems: "center" }}>
                    <MoveButtons ids={ids} id={x.id} label={name(x)} onMove={(next) => reorder(() => api.reorder(next))} />
                    <button type="button" className="btn btn-outline btn-sm" onClick={() => setOpen({ item: x })}>
                      Edit
                    </button>
                    <button type="button" className="btn-plain danger" onClick={() => setDeleting(x)}>
                      Delete
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {open && (
        <ItemModal
          title={open.item ? `Edit ${name(open.item)}` : newLabel}
          cfg={cfg}
          initial={open.item ? toForm(cfg, open.item as never) : undefined}
          onClose={() => setOpen(null)}
          onSubmit={async (f) => {
            if (open.item) await api.update(open.item.id, itemBody(cfg, f, toForm(cfg, open.item as never)));
            else await api.create(itemBody(cfg, f));
            await after(list);
            toast(open.item ? "Saved" : "Created");
          }}
        />
      )}
      {deleting && <DeleteDialog name={name(deleting)} list={list} run={() => api.remove(deleting.id)} onClose={() => setDeleting(null)} />}
    </div>
  );
}

function CertificationsTab() {
  const query = useCertifications();
  return (
    <FlatTab
      list="certifications"
      title="Certifications"
      sub="Shown on product pages and as a filter in the catalogue (e.g. Halal, ISO 22000)."
      newLabel="New certification"
      cfg={{ textKey: "name", textLabel: "Name", textMax: 120, description: true, image: { key: "logo", label: "Logo (optional)" }, active: true }}
      query={query}
      api={certificationsApi}
      emptyText="No certifications yet."
    />
  );
}

function DetailLabelsTab() {
  const query = useDetailLabels();
  return (
    <FlatTab
      list="detail-labels"
      title="Detail labels"
      sub={'The labelled lines under "Product Details" (e.g. Used in, Shelf life). Each product fills in its own text per language.'}
      newLabel="New detail label"
      cfg={{ textKey: "label", textLabel: "Label", textMax: 80 }}
      query={query}
      api={detailLabelsApi}
      emptyText="No detail labels yet."
    />
  );
}

/* ------------------------------------------------------------------ */
/* Attributes (with their values)                                      */
/* ------------------------------------------------------------------ */

function AttributesTab() {
  const { data, error, isPending, refetch } = useAttributes();
  const after = useAfterChange();
  const { toast } = useStore();
  const reorder = useReorder("attributes");
  const [open, setOpen] = useState<{ id?: string } | null>(null);
  const [deleting, setDeleting] = useState<Attribute | null>(null);
  const items = data ?? [];
  const ids = items.map((x) => x.id);
  const cfg: ItemConfig = { textKey: "name", textLabel: "Name", textMax: 80, description: true };
  const editing = open?.id ? items.find((x) => x.id === open.id) : undefined;

  return (
    <div className="card">
      <div className="card-h">
        <div>
          <h3>Attributes</h3>
          <div className="sub">What variants differ by (e.g. Packaging, Grade), each with its values. Products pick 1-3 attributes and sell a variant per combination.</div>
        </div>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => setOpen({})}>
          <Icon name="plus" size={14} />
          New attribute
        </button>
      </div>
      <div className="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Name (English)</th>
              <th>Slug</th>
              <th>Values</th>
              <th>Languages</th>
              <th>
                <span className="sr-only">Actions</span>
              </th>
            </tr>
          </thead>
          <tbody>
            <ListState pending={isPending} error={error} retry={refetch} cols={5} empty={items.length ? null : "No attributes yet. Add one (e.g. Packaging) to sell variants."} />
            {items.map((a) => (
              <tr key={a.id}>
                <td>
                  <b style={{ fontWeight: 500 }}>{tr(a.translations, "en", "name")}</b>
                </td>
                <td style={{ color: "var(--muted)" }}>{a.slug}</td>
                <td style={{ whiteSpace: "normal" }}>
                  <span className="sec-tags" style={{ flexWrap: "wrap" }}>
                    {a.values.map((v) => (
                      <span key={v.id} className="tag n">
                        {tr(v.translations, "en", "label")}
                      </span>
                    ))}
                  </span>
                </td>
                <td>
                  <LangTags t={a.translations} />
                </td>
                <td>
                  <div style={{ display: "flex", gap: 6, justifyContent: "flex-end", alignItems: "center" }}>
                    <MoveButtons ids={ids} id={a.id} label={tr(a.translations, "en", "name")} onMove={(next) => reorder(() => attributesApi.reorder(next))} />
                    <button type="button" className="btn btn-outline btn-sm" onClick={() => setOpen({ id: a.id })}>
                      Edit
                    </button>
                    <button type="button" className="btn-plain danger" onClick={() => setDeleting(a)}>
                      Delete
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {open && (
        <ItemModal
          key={open.id ?? "new"}
          title={editing ? `Edit ${tr(editing.translations, "en", "name")}` : "New attribute"}
          cfg={cfg}
          initial={editing ? toForm(cfg, editing as never) : undefined}
          onClose={() => setOpen(null)}
          onSubmit={async (f) => {
            if (editing) {
              await attributesApi.update(editing.id, itemBody(cfg, f, toForm(cfg, editing as never)));
              await after("attributes");
              toast("Saved");
            } else {
              const created = await attributesApi.create(itemBody(cfg, f));
              await after("attributes");
              toast("Created. Now add its values.");
              // Keep going: reopen in edit mode to add values.
              setTimeout(() => setOpen({ id: created.id }), 0);
            }
          }}
        >
          {editing ? <ValuesEditor attr={editing} /> : <div className="hint">Values (e.g. 25 kg bag, 1 MT big bag) are added after creating the attribute.</div>}
        </ItemModal>
      )}
      {deleting && <DeleteDialog name={tr(deleting.translations, "en", "name")} list="attributes" run={() => attributesApi.remove(deleting.id)} onClose={() => setDeleting(null)} />}
    </div>
  );
}

/** The values of an attribute: label per language, add, reorder, delete. Saved one by one. */
function ValuesEditor({ attr }: { attr: Attribute }) {
  const langs = useActiveLangs();
  const after = useAfterChange();
  const { toast } = useStore();
  const [lang, setLang] = useState("en");
  const [drafts, setDrafts] = useState<Record<string, string>>({});
  const [adding, setAdding] = useState({ slug: "", label: "", slugTouched: false });
  const [busy, setBusy] = useState<string | null>(null);
  const [err, setErr] = useState<string | null>(null);
  const values = [...attr.values].sort((a, b) => a.order - b.order);
  const ids = values.map((v) => v.id);
  const newSlug = adding.slugTouched ? adding.slug : slugify(adding.label);

  const run = async (label: string, fn: () => Promise<unknown>, done: string) => {
    setBusy(label);
    setErr(null);
    try {
      await fn();
      await after("attributes");
      toast(done);
      return true;
    } catch (e) {
      setErr(errorMessage(e));
      return false;
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="field">
      <div className="fs-title">Values</div>
      <div className="row-between" style={{ marginBottom: 8 }}>
        <div className="seg" role="group" aria-label="Value language">
          {langs.map((l) => (
            <button key={l.code} type="button" className={l.code === lang ? "on" : ""} aria-pressed={l.code === lang} onClick={() => setLang(l.code)}>
              {l.code.toUpperCase()}
            </button>
          ))}
        </div>
        <span className="hint">A value&apos;s slug never changes once created.</span>
      </div>
      {values.map((v) => {
        const key = `${v.id}:${lang}`;
        const current = v.translations[lang]?.label ?? "";
        const text = drafts[key] ?? current;
        return (
          <div key={v.id} className="repeat" style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <code style={{ fontSize: 12, color: "var(--muted)", minWidth: 110 }}>{v.slug}</code>
            <input
              className="input input-sm"
              aria-label={`${v.slug} label (${lang})`}
              maxLength={80}
              placeholder={lang === "en" ? "Label" : `${tr(v.translations, "en", "label")} (English)`}
              value={text}
              onChange={(e) => setDrafts((d) => ({ ...d, [key]: e.target.value }))}
            />
            <button
              type="button"
              className="btn btn-outline btn-sm"
              disabled={!!busy || text.trim() === current || (lang === "en" && !text.trim())}
              onClick={async () => {
                const ok = await run(`save:${v.id}`, () => attributesApi.updateValue(attr.id, v.id, { translations: { [lang]: text.trim() ? { label: text.trim() } : null } }), "Value saved");
                if (ok) setDrafts((d) => Object.fromEntries(Object.entries(d).filter(([k]) => k !== key)));
              }}
            >
              {busy === `save:${v.id}` ? <span className="spin dark" /> : "Save"}
            </button>
            <MoveButtons ids={ids} id={v.id} label={v.slug} onMove={(next) => run("order", () => attributesApi.reorderValues(attr.id, next), "Order saved")} />
            <button type="button" className="btn-plain danger" disabled={!!busy} title="Delete value" aria-label={`Delete ${v.slug}`} onClick={() => run(`del:${v.id}`, () => attributesApi.removeValue(attr.id, v.id), "Value deleted")}>
              <Icon name="x" size={14} />
            </button>
          </div>
        );
      })}
      <div className="repeat" style={{ display: "flex", gap: 8, alignItems: "center" }}>
        <input className="input input-sm" aria-label="New value label (English)" placeholder="New value, English label (e.g. 25 kg bag)" maxLength={80} value={adding.label} onChange={(e) => setAdding((a) => ({ ...a, label: e.target.value }))} />
        <input
          className="input input-sm"
          aria-label="New value slug"
          placeholder="slug"
          maxLength={80}
          style={{ maxWidth: 160 }}
          value={newSlug}
          onChange={(e) => setAdding((a) => ({ ...a, slug: e.target.value.toLowerCase(), slugTouched: true }))}
        />
        <button
          type="button"
          className="btn btn-primary btn-sm"
          disabled={!!busy || !adding.label.trim() || !newSlug || !isSlug(newSlug)}
          onClick={async () => {
            const ok = await run("add", () => attributesApi.addValue(attr.id, { slug: newSlug, translations: { en: { label: adding.label.trim() } } }), "Value added");
            if (ok) setAdding({ slug: "", label: "", slugTouched: false });
          }}
        >
          {busy === "add" ? <span className="spin" /> : "Add"}
        </button>
      </div>
      {err && <div className="form-error">{err}</div>}
    </div>
  );
}
