"use client";

/**
 * Product form (API reference: "How products work (admin panel)"). One screen, one Save:
 * the shared data (type, categories, origin, volumes, prices…), the text of each
 * language, media and every variant go in one request.
 *
 * - Prices are typed as 480.00 and sent in cents (48000).
 * - Variable products: pick 1-3 attributes and their values; the grid has a row per
 *   combination. Changing the values keeps existing rows (and their ids) and adds the
 *   new combinations; rows deleted by the editor stay deleted.
 * - Only languages whose text changed are sent (a language sent becomes a draft again).
 * - Publishing is per language and also puts pending shared changes live.
 * - Save sends back `version`; a 409 means someone else saved first (reload), or that
 *   variants live on the website would be removed (confirm, then resend).
 */
import { useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useId, useMemo, useRef, useState } from "react";
import { ApiError, errorMessage, fieldErrors, getAccessToken } from "@/app/(admin)/_lib/api";
import type { Img } from "@/app/(admin)/_lib/cms";
import { fileProblem, mediaUrl, uploadMedia, type Media } from "@/app/(admin)/_lib/media";
import {
  CURRENCIES,
  LENGTH_UNITS,
  MOQ_UNITS,
  PRICE_UNITS,
  WEIGHT_UNITS,
  isSlug,
  langBadge,
  productsApi,
  slugify,
  tr,
  type Attribute,
  type Product,
  type ProductBody,
  type ProductFile,
  type ProductText,
} from "@/app/(admin)/_lib/products";
import { qk, useAttributes, useCategories, useCertifications, useDetailLabels, useProduct } from "@/app/(admin)/_lib/queries";
import { refreshSiteContent } from "@/app/(admin)/_lib/siteCache";
import { useStore } from "@/app/(admin)/_lib/store";
import { isPreviewMessage, type FromPreview, type ToPreview } from "@/app/(site)/_lib/previewProtocol";
import { useActiveLangs } from "./CatalogPage";
import { Icon } from "./Icon";
import { MediaPicker } from "./MediaLibrary";
import { ConfirmDialog, Modal } from "./Modal";
import { SchemaField } from "./SchemaField";
import { PageHeader } from "./ui";

/* ------------------------------------------------------------------ */
/* Form state                                                          */
/* ------------------------------------------------------------------ */

type Row = {
  /** Client key (rows without an id are new). */
  key: string;
  id?: string;
  sku: string;
  attributeValues: Record<string, string>;
  market: string;
  selling: string;
  dims: { length: string; width: string; height: string; unit: (typeof LENGTH_UNITS)[number] };
  weight: { value: string; unit: (typeof WEIGHT_UNITS)[number] };
  image: Img | null;
  gallery: Img[];
  isDefault: boolean;
  isActive: boolean;
};

type TextForm = { name: string; shortDescription: string; description: string; details: Record<string, string>; seoTitle: string; seoDescription: string };

type Form = {
  type: "simple" | "variable";
  slug: string;
  categoryIds: string[];
  certificationIds: string[];
  originCountries: string[];
  farming: "organic" | "conventional";
  volumeMin: string;
  volumeMax: string;
  moqValue: string;
  moqUnit: (typeof MOQ_UNITS)[number];
  currency: (typeof CURRENCIES)[number];
  priceUnit: (typeof PRICE_UNITS)[number];
  priceVisibility: "show" | "on-request";
  featured: boolean;
  order: string;
  thumbnail: Img | null;
  gallery: Img[];
  files: ProductFile[];
  attributes: { attributeId: string; values: string[] }[];
  rows: Row[];
  texts: Record<string, TextForm>;
};

let keySeq = 0;
const newKey = () => `r${++keySeq}`;
const str = (n: number | null | undefined) => (n == null ? "" : String(n));
const num = (s: string) => (s.trim() === "" ? undefined : Number(s.replace(",", ".")));
/** "480.00" → 48000 (integer cents). */
const cents = (s: string) => (s.trim() === "" ? undefined : Math.round(Number(s.replace(",", ".")) * 100));
const fromCents = (n: number | null | undefined) => (n == null ? "" : (n / 100).toFixed(2));
const cleanImg = (i: Img | null | undefined): Img | undefined => (i?.url?.trim() ? { url: i.url.trim(), ...(i.alt?.trim() ? { alt: i.alt.trim().slice(0, 200) } : {}) } : undefined);

const emptyText = (): TextForm => ({ name: "", shortDescription: "", description: "", details: {}, seoTitle: "", seoDescription: "" });
const isEmptyText = (t?: TextForm) => !t || (![t.name, t.shortDescription, t.description, t.seoTitle, t.seoDescription].some((x) => x.trim()) && !Object.values(t.details).some((x) => x.trim()));

const emptyRow = (attributeValues: Record<string, string> = {}): Row => ({
  key: newKey(),
  sku: "",
  attributeValues,
  market: "",
  selling: "",
  dims: { length: "", width: "", height: "", unit: "cm" },
  weight: { value: "", unit: "kg" },
  image: null,
  gallery: [],
  isDefault: false,
  isActive: true,
});

const emptyForm = (): Form => ({
  type: "simple",
  slug: "",
  categoryIds: [],
  certificationIds: [],
  originCountries: [],
  farming: "conventional",
  volumeMin: "",
  volumeMax: "",
  moqValue: "",
  moqUnit: "mt",
  currency: "EUR",
  priceUnit: "kg",
  priceVisibility: "show",
  featured: false,
  order: "",
  thumbnail: null,
  gallery: [],
  files: [],
  attributes: [],
  rows: [{ ...emptyRow(), isDefault: true }],
  texts: { en: emptyText() },
});

function textFrom(t: ProductText | null | undefined): TextForm {
  return {
    name: t?.name ?? "",
    shortDescription: t?.shortDescription ?? "",
    description: t?.description ?? "",
    details: { ...(t?.details ?? {}) },
    seoTitle: t?.seo?.title ?? "",
    seoDescription: t?.seo?.description ?? "",
  };
}

function formFrom(p: Product): Form {
  const d = p.draft;
  return {
    type: d.type,
    slug: p.slug,
    categoryIds: [...d.categoryIds],
    certificationIds: [...(d.certificationIds ?? [])],
    originCountries: [...(d.originCountries ?? [])],
    farming: d.farming,
    volumeMin: str(d.volumeMt?.min),
    volumeMax: str(d.volumeMt?.max),
    moqValue: str(d.moq?.value),
    moqUnit: d.moq?.unit ?? "mt",
    currency: d.currency,
    priceUnit: d.priceUnit,
    priceVisibility: d.priceVisibility,
    featured: !!d.featured,
    order: str(d.order),
    thumbnail: d.thumbnail ?? null,
    gallery: [...(d.gallery ?? [])],
    files: [...(d.files ?? [])],
    attributes: (d.attributes ?? []).map((a) => ({ attributeId: a.attributeId, values: [...a.values] })),
    rows: d.variants.map((v) => ({
      key: newKey(),
      id: v.id,
      sku: v.sku,
      attributeValues: { ...v.attributeValues },
      market: fromCents(v.marketPrice),
      selling: fromCents(v.sellingPrice),
      dims: { length: str(v.dimensions?.length), width: str(v.dimensions?.width), height: str(v.dimensions?.height), unit: v.dimensions?.unit ?? "cm" },
      weight: { value: str(v.weight?.value), unit: v.weight?.unit ?? "kg" },
      image: v.image ?? null,
      gallery: [...(v.gallery ?? [])],
      isDefault: !!v.isDefault,
      isActive: v.isActive !== false,
    })),
    texts: Object.fromEntries(Object.entries(p.translations).map(([l, t]) => [l, textFrom(t.draft ?? t.published)])),
  };
}

function textBody(t: TextForm): ProductText {
  const details = Object.fromEntries(Object.entries(t.details).filter(([, v]) => v.trim()).map(([k, v]) => [k, v.trim()]));
  const seo = { ...(t.seoTitle.trim() ? { title: t.seoTitle.trim() } : {}), ...(t.seoDescription.trim() ? { description: t.seoDescription.trim() } : {}) };
  return {
    name: t.name.trim(),
    ...(t.shortDescription.trim() ? { shortDescription: t.shortDescription.trim() } : {}),
    ...(t.description.trim() ? { description: t.description.trim() } : {}),
    ...(Object.keys(details).length ? { details } : {}),
    ...(Object.keys(seo).length ? { seo } : {}),
  };
}

/** The languages whose text differs from what was loaded. */
function changedLangs(f: Form, base: Form): string[] {
  return Object.keys(f.texts).filter((l) => !isEmptyText(f.texts[l]) && JSON.stringify(f.texts[l]) !== JSON.stringify(base.texts[l] ?? emptyText()));
}

function bodyFrom(f: Form, langs: string[]): ProductBody {
  const simple = f.type === "simple";
  const rows = simple ? f.rows.slice(0, 1) : f.rows;
  const min = num(f.volumeMin);
  const max = num(f.volumeMax);
  const moq = num(f.moqValue);
  const order = num(f.order);
  return {
    type: f.type,
    slug: f.slug.trim(),
    categoryIds: f.categoryIds,
    certificationIds: f.certificationIds,
    originCountries: f.originCountries,
    farming: f.farming,
    volumeMt: { min: min as number, ...(max !== undefined ? { max } : {}) },
    ...(moq !== undefined ? { moq: { value: moq, unit: f.moqUnit } } : {}),
    currency: f.currency,
    priceUnit: f.priceUnit,
    priceVisibility: f.priceVisibility,
    featured: f.featured,
    ...(order !== undefined ? { order } : {}),
    thumbnail: cleanImg(f.thumbnail) as Img,
    gallery: f.gallery.map(cleanImg).filter((x): x is Img => !!x),
    files: f.files.filter((x) => x.url.trim()).map((x) => ({ url: x.url.trim(), label: x.label.trim() })),
    attributes: simple ? [] : f.attributes,
    variants: rows.map((r) => {
      const l = num(r.dims.length);
      const w = num(r.dims.width);
      const h = num(r.dims.height);
      const wt = num(r.weight.value);
      const market = cents(r.market);
      const image = cleanImg(r.image);
      return {
        ...(r.id ? { id: r.id } : {}),
        sku: r.sku.trim().toUpperCase(),
        attributeValues: simple ? {} : r.attributeValues,
        ...(market !== undefined ? { marketPrice: market } : {}),
        sellingPrice: cents(r.selling) as number,
        ...(l !== undefined && w !== undefined && h !== undefined ? { dimensions: { length: l, width: w, height: h, unit: r.dims.unit } } : {}),
        ...(wt !== undefined ? { weight: { value: wt, unit: r.weight.unit } } : {}),
        ...(image ? { image } : {}),
        gallery: r.gallery.map(cleanImg).filter((x): x is Img => !!x),
        isDefault: simple ? true : r.isDefault,
        isActive: r.isActive,
      };
    }),
    ...(langs.length ? { translations: Object.fromEntries(langs.map((l) => [l, textBody(f.texts[l])])) } : {}),
  };
}

/* ------------------------------------------------------------------ */
/* Variant grid                                                        */
/* ------------------------------------------------------------------ */

type Attrs = Form["attributes"];

/** Every combination of the chosen values, in attribute order. */
function combos(attrs: Attrs): Record<string, string>[] {
  return attrs.reduce<Record<string, string>[]>((acc, a) => acc.flatMap((c) => a.values.map((v) => ({ ...c, [a.attributeId]: v }))), [{}]);
}
const comboKey = (av: Record<string, string>, attrs: Attrs) => attrs.map((a) => `${a.attributeId}=${av[a.attributeId] ?? ""}`).join("|");

/**
 * Rows after the attributes or values changed: existing rows adapt (a new attribute
 * gets its first value, a removed one is dropped), rows whose value was removed go,
 * and combinations that are new in this change get a row.
 */
function rebuildRows(prev: Attrs, next: Attrs, rows: Row[]): Row[] {
  if (!next.length || next.some((a) => !a.values.length)) return rows;
  const seen = new Set<string>();
  const kept: Row[] = [];
  for (const r of rows) {
    const av: Record<string, string> = {};
    for (const a of next) av[a.attributeId] = r.attributeValues[a.attributeId] ?? a.values[0];
    if (!next.every((a) => a.values.includes(av[a.attributeId]))) continue;
    const k = comboKey(av, next);
    if (seen.has(k)) continue;
    seen.add(k);
    kept.push({ ...r, attributeValues: av });
  }
  const before = new Set(combos(prev).map((c) => comboKey(c, next)));
  for (const c of combos(next)) {
    const k = comboKey(c, next);
    if (!seen.has(k) && !before.has(k)) {
      seen.add(k);
      kept.push(emptyRow(c));
    }
  }
  if (kept.length && !kept.some((r) => r.isDefault)) kept[0] = { ...kept[0], isDefault: true };
  return kept;
}

/* ------------------------------------------------------------------ */
/* Countries                                                           */
/* ------------------------------------------------------------------ */

const ISO =
  "AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW".split(
    " ",
  );
let regionNames: Intl.DisplayNames | null = null;
const countryName = (code: string) => {
  try {
    regionNames ??= new Intl.DisplayNames(["en"], { type: "region" });
    return regionNames.of(code) ?? code;
  } catch {
    return code;
  }
};

/* ------------------------------------------------------------------ */
/* Editor                                                              */
/* ------------------------------------------------------------------ */

const TABS = ["General", "Content", "Media", "Variants"] as const;
type Tab = (typeof TABS)[number];
const TAB_OF = (path: string): Tab => {
  const top = path.split(".")[0];
  if (top === "translations" || top === "source") return "Content";
  if (top === "thumbnail" || top === "gallery" || top === "files") return "Media";
  if (top === "attributes" || top === "variants") return "Variants";
  return "General";
};

export function ProductEditor({ id }: { id: string | null }) {
  const { data: product, error, isPending, refetch } = useProduct(id);
  if (id && isPending)
    return (
      <div className="page">
        <div className="card empty-card">
          <span className="spin dark" /> Loading product…
        </div>
      </div>
    );
  if (id && (error || !product))
    return (
      <div className="page">
        <div className="card empty-card">
          {error ? errorMessage(error) : "This product doesn't exist."}{" "}
          {error && (
            <button type="button" className="link" onClick={() => refetch()}>
              Retry
            </button>
          )}{" "}
          <Link href="/admin/products" className="link">
            Back to Products
          </Link>
        </div>
      </div>
    );
  return <ProductForm key={product?.id ?? "new"} product={product ?? null} />;
}

function ProductForm({ product }: { product: Product | null }) {
  // Ids per form: a hidden earlier form (kept by the router) must not share them.
  const uid = useId();
  const qc = useQueryClient();
  const router = useRouter();
  const { toast } = useStore();
  const langs = useActiveLangs();
  const { data: groups } = useCategories();
  const { data: certs } = useCertifications();
  const { data: attributes } = useAttributes();
  const { data: labels } = useDetailLabels();

  const base = useMemo(() => (product ? formFrom(product) : emptyForm()), [product]);
  const [f, setF] = useState<Form>(base);
  // A newer version arrived (saved, published, reloaded): the form shows it. Tab and language stay.
  const [shownBase, setShownBase] = useState(base);
  if (shownBase !== base) {
    setShownBase(base);
    setF(base);
  }
  const [tab, setTab] = useState<Tab>("General");
  const [lang, setLang] = useState("en");
  const [errs, setErrs] = useState<Record<string, string>>({});
  const [formError, setFormError] = useState<string | null>(null);
  const [conflict, setConflict] = useState(false);
  const [confirmRemovals, setConfirmRemovals] = useState<string | null>(null);
  const [busy, setBusy] = useState<string | null>(null);
  const [slugTouched, setSlugTouched] = useState(!!product);
  const [rejecting, setRejecting] = useState(false);
  const [comment, setComment] = useState("");
  const [previewing, setPreviewing] = useState(false);

  // After "Create product" the router keeps this /new form mounted but hidden; once the
  // product's own page is shown, empty it so the next "New product" starts clean.
  const pathname = usePathname();
  const [createdAt, setCreatedAt] = useState<string | null>(null);
  if (createdAt && pathname !== createdAt) {
    setCreatedAt(null);
    setF(emptyForm());
    setSlugTouched(false);
    setErrs({});
    setFormError(null);
    setTab("General");
  }

  const slug = slugTouched ? f.slug : slugify(f.texts.en?.name ?? "").slice(0, 100);
  const form = { ...f, slug };
  const dirty = JSON.stringify(form) !== JSON.stringify({ ...base, slug: product ? base.slug : slug });
  const set = (patch: Partial<Form>) => setF((x) => ({ ...x, ...patch }));

  useEffect(() => {
    if (!dirty) return;
    const warn = (e: BeforeUnloadEvent) => e.preventDefault();
    addEventListener("beforeunload", warn);
    return () => removeEventListener("beforeunload", warn);
  }, [dirty]);

  const errCount = (t: Tab) => Object.keys(errs).filter((p) => TAB_OF(p) === t).length;
  const err = (path: string) => errs[path];

  /* ---------- save + workflow ---------- */

  const after = (p: Product) => {
    qc.setQueryData(qk.product(p.id), p);
    qc.invalidateQueries({ queryKey: qk.products() });
  };
  const refreshSite = async () => {
    const token = getAccessToken();
    if (token) await refreshSiteContent("products", token).catch(() => undefined);
  };

  /** Saves when needed; returns the saved product (or the loaded one when nothing changed). */
  const save = async (opts: { confirmRemovals?: boolean } = {}): Promise<Product | null> => {
    if (product && !dirty && !opts.confirmRemovals) return product;
    setErrs({});
    setFormError(null);
    const body = bodyFrom(form, changedLangs(form, base));
    try {
      const p = product ? await productsApi.save(product.id, { ...body, version: product.version, ...(opts.confirmRemovals ? { confirmRemovals: true } : {}) }) : await productsApi.create(body);
      after(p);
      if (!product) {
        setCreatedAt(pathname);
        router.replace(`/admin/products/${p.id}`);
      }
      return p;
    } catch (e) {
      if (e instanceof ApiError && e.status === 409 && /live on the website/i.test(e.message)) setConfirmRemovals(e.message);
      else if (e instanceof ApiError && e.status === 409 && /someone else/i.test(e.message)) setConflict(true);
      else {
        const fe = fieldErrors(e);
        setErrs(fe);
        setFormError(Object.keys(fe).length ? `${Object.keys(fe).length} field${Object.keys(fe).length === 1 ? "" : "s"} need fixing.` : errorMessage(e));
        const first = Object.keys(fe)[0];
        if (first) {
          setTab(TAB_OF(first));
          const l = /^translations\.([^.]+)\./.exec(first)?.[1];
          if (l) setLang(l);
        }
      }
      return null;
    }
  };

  const run = async (label: string, action?: "submit" | "publish" | "unpublish", opts: { confirmRemovals?: boolean } = {}) => {
    setBusy(label);
    try {
      let p = action === "unpublish" ? product : await save(opts);
      if (!p) return;
      if (action) {
        p = await productsApi.action(p.id, action, lang);
        after(p);
      }
      if (action === "publish" || action === "unpublish") await refreshSite();
      toast({ Save: product ? "Saved" : "Product created as a draft", Submit: "Sent for review", Publish: "Published to the website", Unpublish: "Removed from the website in this language" }[label] ?? "Saved");
    } catch (e) {
      toast(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const reject = async () => {
    if (!product) return;
    setBusy("Reject");
    try {
      after(await productsApi.reject(product.id, lang, comment.trim()));
      toast("Sent back with your comment");
      setRejecting(false);
      setComment("");
    } catch (e) {
      toast(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const reload = async () => {
    if (!product) return;
    setConflict(false);
    await qc.invalidateQueries({ queryKey: qk.product(product.id) });
    toast("Reloaded the latest version");
  };

  /* ---------- per-language state ---------- */

  const t = product?.translations[lang];
  const badge = langBadge(t?.status ?? "missing", t?.hasUnpublishedChanges);
  const langDirty = JSON.stringify(f.texts[lang] ?? emptyText()) !== JSON.stringify(base.texts[lang] ?? emptyText()) && !isEmptyText(f.texts[lang]);
  const canSubmit = !!product && (dirty || (t?.status === "draft" && t.hasUnpublishedChanges));
  const canPublish = !!product && (dirty || t?.status === "in_review" || (t?.status === "draft" && t.source !== "ai") || (t?.status === "published" && product.hasUnpublishedSharedChanges));
  const canUnpublish = !!product && !!t?.published;

  const text = f.texts[lang] ?? emptyText();
  const setText = (patch: Partial<TextForm>) => set({ texts: { ...f.texts, [lang]: { ...text, ...patch } } });
  const langName = (c: string) => langs.find((l) => l.code === c)?.name ?? c.toUpperCase();

  /* ---------- render ---------- */

  return (
    <div className="page">
      <PageHeader
        crumb={
          <>
            Website ›{" "}
            <Link href="/admin/products" className="link" style={{ fontSize: "inherit" }}>
              Products
            </Link>
          </>
        }
        title={f.texts.en?.name || (product ? product.slug : "New product")}
        desc={product ? "Shared data, variants and media are saved for every language; text is published per language." : "Fill in the product, then create it as a draft. Nothing is on the website until published."}
      >
        {product?.isLive && (
          <Link href={`/products/${product.slug}`} target="_blank" className="btn btn-outline btn-sm">
            <Icon name="eye" size={14} />
            View on website
          </Link>
        )}
        {product && (
          <button type="button" className="btn btn-outline btn-sm" disabled={!!busy} onClick={() => setPreviewing(true)} title="The product page with drafts, as the website would show it">
            <Icon name="eye" size={14} />
            Preview
          </button>
        )}
        <button type="button" className="btn btn-primary btn-sm" disabled={!!busy || (!!product && !dirty)} onClick={() => run("Save")}>
          {busy === "Save" ? <span className="spin" /> : product ? "Save" : "Create product"}
        </button>
      </PageHeader>

      {conflict && (
        <div className="review-note" role="alert" style={{ marginBottom: 16 }}>
          <b>Someone else saved this product first.</b>
          <span>
            Reload it and apply your changes again (your unsaved changes are lost).{" "}
            <button type="button" className="link" onClick={reload}>
              Reload
            </button>
          </span>
        </div>
      )}
      {product?.status === "archived" && <div className="info-note" style={{ marginBottom: 16 }}>This product is archived: it isn&apos;t on the website in any language. Unarchive it from the Products list.</div>}

      {/* Language + workflow bar */}
      {product && (
        <div className="card ed-bar">
          <div className="grp">
            <label>Language</label>
            <div className="seg" role="group" aria-label="Language">
              {langs.map((l) => {
                const b = langBadge(product.translations[l.code]?.status ?? "missing", product.translations[l.code]?.hasUnpublishedChanges);
                return (
                  <button key={l.code} type="button" className={l.code === lang ? "on" : ""} aria-pressed={l.code === lang} title={`${l.name}: ${b.label}`} onClick={() => setLang(l.code)}>
                    {l.code.toUpperCase()}
                    <span className={`status-dot ${b.tone}`} style={{ marginLeft: 6 }} />
                  </button>
                );
              })}
            </div>
          </div>
          <span className={`tag ${badge.tone}`}>
            {langName(lang)}: {badge.label}
          </span>
          {product.hasUnpublishedSharedChanges && <span className="tag a">Shared changes (prices, variants, images) go live with the next publish</span>}
          {product.isLive ? <span className="tag g">On the website</span> : <span className="tag n">Not on the website</span>}
          <div className="ed-actions" style={{ marginLeft: "auto", border: 0, padding: 0 }}>
            <button type="button" className="btn btn-outline btn-sm" disabled={!canSubmit || !!busy} onClick={() => run("Submit", "submit")} title="Send this language for review">
              {busy === "Submit" ? <span className="spin dark" /> : "Submit"}
            </button>
            {t?.status === "in_review" && (
              <button type="button" className="btn btn-outline btn-sm danger" disabled={!!busy} onClick={() => setRejecting(true)}>
                Reject
              </button>
            )}
            <button type="button" className="btn btn-primary btn-sm" disabled={!canPublish || !!busy} onClick={() => run("Publish", "publish")}>
              {busy === "Publish" ? <span className="spin" /> : t?.status === "in_review" && !dirty ? `Approve & publish ${lang.toUpperCase()}` : dirty ? `Save & publish ${lang.toUpperCase()}` : `Publish ${lang.toUpperCase()}`}
            </button>
            {canUnpublish && (
              <button type="button" className="btn-plain danger" disabled={!!busy} onClick={() => run("Unpublish", "unpublish")}>
                Unpublish
              </button>
            )}
          </div>
        </div>
      )}
      {t?.reviewComment && t.status === "draft" && (
        <div className="review-note" role="note" style={{ marginBottom: 16 }}>
          <b>Changes requested ({langName(lang)})</b>
          <span>{t.reviewComment}</span>
        </div>
      )}

      {formError && (
        <div className="form-error" role="alert" style={{ marginBottom: 16 }}>
          {formError}
          {Object.keys(errs).length > 0 && (
            <ul style={{ margin: "6px 0 0 18px", listStyle: "disc" }}>
              {Object.entries(errs)
                .slice(0, 8)
                .map(([p, m]) => (
                  <li key={p}>
                    {p}: {m}
                  </li>
                ))}
            </ul>
          )}
        </div>
      )}

      <div className="seg" role="tablist" aria-label="Product form" style={{ marginBottom: 16 }}>
        {TABS.map((x) => (
          <button key={x} type="button" role="tab" aria-selected={tab === x} className={tab === x ? "on" : ""} onClick={() => setTab(x)}>
            {x === "Variants" ? "Prices & variants" : x}
            {errCount(x) > 0 && (
              <span className="tag r" style={{ marginLeft: 6 }}>
                {errCount(x)}
              </span>
            )}
          </button>
        ))}
      </div>

      <div className="card">
        <div className="card-b">
          {tab === "General" && (
            <>
              <div className="form-grid">
                <div className="field">
                  <label htmlFor={`${uid}-type`}>Type</label>
                  <select
                    id={`${uid}-type`}
                    className="select input"
                    value={f.type}
                    onChange={(e) => {
                      const type = e.target.value as Form["type"];
                      if (type === "simple" && f.rows.length > 1) {
                        toast("Delete variant rows until one is left, then switch to simple.");
                        return;
                      }
                      set({ type, ...(type === "simple" ? { attributes: [], rows: f.rows.slice(0, 1).map((r) => ({ ...r, attributeValues: {}, isDefault: true })) } : {}) });
                    }}
                  >
                    <option value="simple">Simple (one variant)</option>
                    <option value="variable">With variants (1-3 attributes)</option>
                  </select>
                </div>
                <div className="field">
                  <label htmlFor={`${uid}-slug`}>
                    Address <span className="req">*</span>
                  </label>
                  <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                    <span style={{ color: "var(--muted)" }}>/products/</span>
                    <input
                      id={`${uid}-slug`}
                      className="input"
                      maxLength={100}
                      value={slug}
                      onChange={(e) => {
                        setSlugTouched(true);
                        set({ slug: e.target.value.toLowerCase() });
                      }}
                      aria-invalid={!!err("slug") || (!!slug && !isSlug(slug))}
                    />
                  </div>
                  {product && slug !== product.slug && product.isLive && <div className="hint">The old address keeps working and redirects here.</div>}
                  <FieldError msg={err("slug") ?? (slug && !isSlug(slug) ? "Lowercase letters and numbers joined by hyphens." : undefined)} />
                </div>
              </div>

              <div className="field">
                <div className="lbl">
                  Categories (1-5) <span className="req">*</span>
                </div>
                {(groups ?? []).length === 0 && (
                  <div className="hint">
                    No categories yet: add them in <Link href="/admin/catalog" className="link">Product Catalog</Link>.
                  </div>
                )}
                {(groups ?? []).map((g) => (
                  <div key={g.id} style={{ marginBottom: 8 }}>
                    <div className="hint" style={{ marginBottom: 6 }}>
                      {tr(g.translations, "en", "name")}
                    </div>
                    <div className="chip-set">
                      {(g.children ?? []).map((c) => {
                        const on = f.categoryIds.includes(c.id);
                        return (
                          <label key={c.id} className={`chip-check${on ? " on" : ""}`}>
                            <input
                              type="checkbox"
                              checked={on}
                              disabled={!on && f.categoryIds.length >= 5}
                              onChange={(e) => set({ categoryIds: e.target.checked ? [...f.categoryIds, c.id] : f.categoryIds.filter((x) => x !== c.id) })}
                            />
                            {tr(c.translations, "en", "name")}
                            {!c.isActive && " (hidden)"}
                          </label>
                        );
                      })}
                    </div>
                  </div>
                ))}
                <FieldError msg={err("categoryIds")} />
              </div>

              <div className="field">
                <div className="lbl">Certifications</div>
                <div className="chip-set">
                  {(certs ?? []).map((c) => {
                    const on = f.certificationIds.includes(c.id);
                    return (
                      <label key={c.id} className={`chip-check${on ? " on" : ""}`}>
                        <input type="checkbox" checked={on} onChange={(e) => set({ certificationIds: e.target.checked ? [...f.certificationIds, c.id] : f.certificationIds.filter((x) => x !== c.id) })} />
                        {tr(c.translations, "en", "name")}
                      </label>
                    );
                  })}
                  {(certs ?? []).length === 0 && <span className="hint">None in the catalog yet.</span>}
                </div>
                <FieldError msg={err("certificationIds")} />
              </div>

              <Countries value={f.originCountries} onChange={(originCountries) => set({ originCountries })} error={err("originCountries")} />

              <div className="form-grid">
                <div className="field">
                  <label htmlFor={`${uid}-farming`}>Farming</label>
                  <select id={`${uid}-farming`} className="select input" value={f.farming} onChange={(e) => set({ farming: e.target.value as Form["farming"] })}>
                    <option value="conventional">Conventional</option>
                    <option value="organic">Organic</option>
                  </select>
                </div>
                <div className="field">
                  <div className="lbl">
                    Available volume (metric tonnes) <span className="req">*</span>
                  </div>
                  <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    <input className="input input-sm" aria-label="Minimum volume (MT)" inputMode="decimal" placeholder="Min" value={f.volumeMin} onChange={(e) => set({ volumeMin: e.target.value })} />
                    <span>–</span>
                    <input className="input input-sm" aria-label="Maximum volume (MT)" inputMode="decimal" placeholder="No limit" value={f.volumeMax} onChange={(e) => set({ volumeMax: e.target.value })} />
                  </div>
                  <FieldError msg={err("volumeMt") ?? err("volumeMt.min") ?? err("volumeMt.max")} />
                </div>
                <div className="field">
                  <div className="lbl">Minimum order (optional)</div>
                  <div style={{ display: "flex", gap: 8 }}>
                    <input className="input input-sm" aria-label="Minimum order quantity" inputMode="decimal" placeholder="e.g. 10" value={f.moqValue} onChange={(e) => set({ moqValue: e.target.value })} />
                    <select className="select" aria-label="Minimum order unit" value={f.moqUnit} onChange={(e) => set({ moqUnit: e.target.value as Form["moqUnit"] })}>
                      {MOQ_UNITS.map((u) => (
                        <option key={u} value={u}>
                          {u === "mt" ? "MT" : u}
                        </option>
                      ))}
                    </select>
                  </div>
                  <FieldError msg={err("moq") ?? err("moq.value")} />
                </div>
                <div className="field">
                  <div className="lbl">Prices</div>
                  <div style={{ display: "flex", gap: 8 }}>
                    <select className="select" aria-label="Currency" value={f.currency} onChange={(e) => set({ currency: e.target.value as Form["currency"] })}>
                      {CURRENCIES.map((c) => (
                        <option key={c}>{c}</option>
                      ))}
                    </select>
                    <select className="select" aria-label="Price per" value={f.priceUnit} onChange={(e) => set({ priceUnit: e.target.value as Form["priceUnit"] })}>
                      {PRICE_UNITS.map((u) => (
                        <option key={u} value={u}>
                          per {u === "mt" ? "MT" : u}
                        </option>
                      ))}
                    </select>
                    <select className="select" aria-label="Price visibility" value={f.priceVisibility} onChange={(e) => set({ priceVisibility: e.target.value as Form["priceVisibility"] })}>
                      <option value="show">Show prices</option>
                      <option value="on-request">Price on request</option>
                    </select>
                  </div>
                  <div className="hint">
                    The amounts (selling and market price) are set per variant in the{" "}
                    <button type="button" className="link" onClick={() => setTab("Variants")}>
                      Prices &amp; variants
                    </button>{" "}
                    tab.
                  </div>
                </div>
                <div className="field">
                  <label className="check">
                    <input type="checkbox" checked={f.featured} onChange={(e) => set({ featured: e.target.checked })} />
                    <span>Featured (listed first)</span>
                  </label>
                </div>
                <div className="field">
                  <label htmlFor={`${uid}-order`}>Order (optional, lowest first)</label>
                  <input id={`${uid}-order`} className="input input-sm" type="number" min={0} step={1} value={f.order} onChange={(e) => set({ order: e.target.value })} style={{ maxWidth: 160 }} />
                  <FieldError msg={err("order")} />
                </div>
              </div>
            </>
          )}

          {tab === "Content" && (
            <>
              <div className="field">
                <div className="seg" role="group" aria-label="Language">
                  {langs.map((l) => {
                    const b = langBadge(product?.translations[l.code]?.status ?? "missing", product?.translations[l.code]?.hasUnpublishedChanges);
                    const n = Object.keys(errs).filter((p) => p.startsWith(`translations.${l.code}.`)).length;
                    return (
                      <button key={l.code} type="button" className={l.code === lang ? "on" : ""} aria-pressed={l.code === lang} title={`${l.name}: ${b.label}`} onClick={() => setLang(l.code)}>
                        {l.code.toUpperCase()} <span className={`tag ${b.tone}`}>{b.label}</span>
                        {n > 0 && <span className="tag r">{n}</span>}
                      </button>
                    );
                  })}
                </div>
                <div className="hint">
                  {langName(lang)}
                  {langDirty ? " · edited (saved as a draft of this language)" : ""}. Languages left empty fall back to English on the website.
                </div>
              </div>
              <TextField id={`${uid}-name`} label="Name" required={lang === "en"} max={160} value={text.name} onChange={(name) => setText({ name })} error={err(`translations.${lang}.name`)} />
              <TextField
                id={`${uid}-short`}
                label="Short description (card text)"
                max={300}
                multiline
                value={text.shortDescription}
                onChange={(shortDescription) => setText({ shortDescription })}
                error={err(`translations.${lang}.shortDescription`)}
              />
              <TextField
                id={`${uid}-desc`}
                label="Description (paragraphs separated by a blank line)"
                max={10000}
                multiline
                rows={8}
                value={text.description}
                onChange={(description) => setText({ description })}
                error={err(`translations.${lang}.description`)}
              />
              {(labels ?? []).length > 0 && <div className="fs-title">Product details lines</div>}
              {(labels ?? []).map((l) => (
                <TextField
                  key={l.id}
                  id={`${uid}-detail-${l.id}`}
                  label={tr(l.translations, lang, "label")}
                  max={300}
                  value={text.details[l.id] ?? ""}
                  onChange={(v) => setText({ details: { ...text.details, [l.id]: v } })}
                  error={err(`translations.${lang}.details.${l.id}`)}
                />
              ))}
              <div className="fs-title">Search engines</div>
              <TextField id={`${uid}-seo-title`} label="SEO title" max={70} value={text.seoTitle} onChange={(seoTitle) => setText({ seoTitle })} error={err(`translations.${lang}.seo.title`)} />
              <TextField
                id={`${uid}-seo-desc`}
                label="SEO description"
                max={160}
                multiline
                value={text.seoDescription}
                onChange={(seoDescription) => setText({ seoDescription })}
                error={err(`translations.${lang}.seo.description`)}
              />
            </>
          )}

          {tab === "Media" && (
            <>
              <SchemaField
                field={{ kind: "image", key: "thumbnail", label: "Listing thumbnail (catalogue card)", required: true }}
                value={f.thumbnail ?? {}}
                onChange={(v) => set({ thumbnail: v as Img })}
                errors={errs}
                path="thumbnail"
              />
              <ImageList label="Product gallery (shown before a variant is picked)" max={12} value={f.gallery} onChange={(gallery) => set({ gallery })} errors={errs} path="gallery" />
              <FileList value={f.files} onChange={(files) => set({ files })} errors={errs} />
            </>
          )}

          {tab === "Variants" && (
            <Variants form={f} set={set} attributes={attributes ?? []} errs={errs} productId={product?.id} currency={f.currency} priceUnit={f.priceUnit} onRequest={f.priceVisibility === "on-request"} />
          )}
        </div>
        <div className="ed-actions">
          {dirty && product && (
            <button type="button" className="btn-plain" onClick={() => setF(base)}>
              Discard changes
            </button>
          )}
          <button type="button" className="btn btn-primary btn-sm" disabled={!!busy || (!!product && !dirty)} onClick={() => run("Save")}>
            {busy === "Save" ? <span className="spin" /> : product ? "Save" : "Create product"}
          </button>
        </div>
      </div>

      {confirmRemovals && (
        <ConfirmDialog
          title="Remove these variants from the website?"
          confirmLabel="Remove and save"
          danger
          busy={busy === "Save"}
          onClose={() => setConfirmRemovals(null)}
          onConfirm={async () => {
            setConfirmRemovals(null);
            await run("Save", undefined, { confirmRemovals: true });
          }}
        >
          {confirmRemovals}
        </ConfirmDialog>
      )}
      {rejecting && (
        <Modal title={`Reject the ${langName(lang)} text`} onClose={() => setRejecting(false)}>
          <div className="field">
            <label htmlFor={`${uid}-reject`}>What needs to change? The editor sees this.</label>
            <textarea id={`${uid}-reject`} className="input" rows={4} maxLength={500} value={comment} onChange={(e) => setComment(e.target.value)} />
          </div>
          <div className="modal-actions">
            <button type="button" className="btn btn-outline btn-sm" onClick={() => setRejecting(false)}>
              Cancel
            </button>
            <button type="button" className="btn btn-danger btn-sm" disabled={!comment.trim() || busy === "Reject"} onClick={reject}>
              {busy === "Reject" ? <span className="spin" /> : "Reject"}
            </button>
          </div>
        </Modal>
      )}
      {previewing && product && <ProductPreview id={product.id} lang={lang} langName={langName(lang)} dirty={dirty} onClose={() => setPreviewing(false)} />}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Fields                                                              */
/* ------------------------------------------------------------------ */

function FieldError({ msg }: { msg?: string | null }) {
  return msg ? <div className="hint bad">{msg}</div> : null;
}

function TextField({
  id,
  label,
  value,
  onChange,
  max,
  required,
  multiline,
  rows = 3,
  error,
}: {
  id: string;
  label: string;
  value: string;
  onChange: (v: string) => void;
  max: number;
  required?: boolean;
  multiline?: boolean;
  rows?: number;
  error?: string;
}) {
  return (
    <div className="field">
      <label htmlFor={id}>
        {label}
        {required && <span className="req"> *</span>}
        {value.length >= max * 0.8 && <span className={`counter${value.length > max ? " bad" : ""}`}>{`${value.length}/${max}`}</span>}
      </label>
      {multiline ? (
        <textarea id={id} className="input" rows={rows} maxLength={max} value={value} onChange={(e) => onChange(e.target.value)} aria-invalid={!!error} />
      ) : (
        <input id={id} className="input" maxLength={max} value={value} onChange={(e) => onChange(e.target.value)} aria-invalid={!!error} />
      )}
      <FieldError msg={error} />
    </div>
  );
}

function Countries({ value, onChange, error }: { value: string[]; onChange: (v: string[]) => void; error?: string }) {
  // Ids per form: a hidden earlier form (kept by the router) must not share them.
  const uid = useId();
  const [q, setQ] = useState("");
  const add = (raw: string) => {
    const s = raw.trim();
    const code = ISO.find((c) => c === s.toUpperCase() || countryName(c).toLowerCase() === s.toLowerCase());
    if (code && !value.includes(code) && value.length < 30) onChange([...value, code]);
    setQ("");
  };
  return (
    <div className="field">
      <label htmlFor={`${uid}-origin`}>Origin countries</label>
      <div className="chip-set" style={{ marginBottom: value.length ? 8 : 0 }}>
        {value.map((c) => (
          <span key={c} className="chip-check on">
            {countryName(c)} ({c})
            <button type="button" aria-label={`Remove ${countryName(c)}`} onClick={() => onChange(value.filter((x) => x !== c))} style={{ display: "inline-grid", marginLeft: 2 }}>
              <Icon name="x" size={12} />
            </button>
          </span>
        ))}
      </div>
      <input
        id={`${uid}-origin`}
        className="input input-sm"
        list={`${uid}-countries`}
        placeholder="Type a country and press Enter"
        value={q}
        onChange={(e) => {
          const v = e.target.value;
          // Picking from the list fills in "Name (XX)".
          const m = /\(([A-Z]{2})\)$/.exec(v);
          if (m) add(m[1]);
          else setQ(v);
        }}
        onKeyDown={(e) => {
          if (e.key === "Enter") {
            e.preventDefault();
            add(q);
          }
        }}
        style={{ maxWidth: 360 }}
      />
      <datalist id={`${uid}-countries`}>
        {ISO.filter((c) => !value.includes(c)).map((c) => (
          <option key={c} value={`${countryName(c)} (${c})`} />
        ))}
      </datalist>
      <FieldError msg={error} />
    </div>
  );
}

/** A list of images (gallery), each picked or uploaded like any image field. */
function ImageList({ label, max, value, onChange, errors, path }: { label: string; max: number; value: Img[]; onChange: (v: Img[]) => void; errors: Record<string, string>; path: string }) {
  const move = (i: number, d: -1 | 1) => {
    const next = [...value];
    [next[i], next[i + d]] = [next[i + d], next[i]];
    onChange(next);
  };
  return (
    <div className="field">
      <div className="fs-title">
        {label} ({value.length} of max {max})
      </div>
      <FieldError msg={errors[path]} />
      {value.map((img, i) => (
        <div className="repeat" key={i}>
          <div className="repeat-h">
            <b>Image {i + 1}</b>
            <span className="repeat-tools">
              <button type="button" aria-label={`Move image ${i + 1} up`} disabled={i === 0} onClick={() => move(i, -1)}>
                ↑
              </button>
              <button type="button" aria-label={`Move image ${i + 1} down`} disabled={i === value.length - 1} onClick={() => move(i, 1)}>
                ↓
              </button>
              <button type="button" aria-label={`Remove image ${i + 1}`} onClick={() => onChange(value.filter((_, j) => j !== i))}>
                <Icon name="x" size={14} />
              </button>
            </span>
          </div>
          <SchemaField field={{ kind: "image", key: String(i), label: "Image" }} value={img} onChange={(v) => onChange(value.map((x, j) => (j === i ? (v as Img) : x)))} errors={errors} path={`${path}.${i}`} />
        </div>
      ))}
      {value.length < max && (
        <button type="button" className="btn-plain" style={{ color: "var(--blue)" }} onClick={() => onChange([...value, { url: "" }])}>
          <Icon name="plus" size={15} />
          Add image
        </button>
      )}
    </div>
  );
}

/** Downloadable PDFs (spec sheets): each a file from the media library and its button label. */
function FileList({ value, onChange, errors }: { value: ProductFile[]; onChange: (v: ProductFile[]) => void; errors: Record<string, string> }) {
  // Ids per form: a hidden earlier form (kept by the router) must not share them.
  const uid = useId();
  const [picking, setPicking] = useState<number | null>(null);
  const [uploading, setUploading] = useState<number | null>(null);
  const [problem, setProblem] = useState<string | null>(null);
  const inputs = useRef<Record<number, HTMLInputElement | null>>({});
  const setAt = (i: number, patch: Partial<ProductFile>) => onChange(value.map((x, j) => (j === i ? { ...x, ...patch } : x)));
  const upload = async (i: number, file?: File) => {
    if (!file) return;
    const p = fileProblem(file, "document");
    if (p) return setProblem(p);
    setProblem(null);
    setUploading(i);
    try {
      const m = await uploadMedia(file, file.name.replace(/\.[^.]+$/, ""));
      setAt(i, { url: mediaUrl(m), ...(value[i].label ? {} : { label: "Spec sheet" }) });
    } catch (e) {
      setProblem(errorMessage(e));
    } finally {
      setUploading(null);
    }
  };
  return (
    <div className="field">
      <div className="fs-title">Downloads (PDF, {value.length} of max 5)</div>
      <div className="hint" style={{ marginBottom: 8 }}>
        Each file shows as a download button on the product page (e.g. &quot;Spec sheet&quot;). PDFs up to 20 MB.
      </div>
      {value.map((file, i) => (
        <div className="repeat" key={i}>
          <div className="repeat-h">
            <b>File {i + 1}</b>
            <span className="repeat-tools">
              <button type="button" aria-label={`Remove file ${i + 1}`} onClick={() => onChange(value.filter((_, j) => j !== i))}>
                <Icon name="x" size={14} />
              </button>
            </span>
          </div>
          <div className="form-grid">
            <div className="field">
              <label htmlFor={`${uid}-file-label-${i}`}>Button label</label>
              <input id={`${uid}-file-label-${i}`} className="input input-sm" maxLength={80} placeholder="Spec sheet" value={file.label} onChange={(e) => setAt(i, { label: e.target.value })} />
              <FieldError msg={errors[`files.${i}.label`]} />
            </div>
            <div className="field">
              <label htmlFor={`${uid}-file-url-${i}`}>File</label>
              <input id={`${uid}-file-url-${i}`} className="input input-sm" placeholder="https://…/spec.pdf" value={file.url} onChange={(e) => setAt(i, { url: e.target.value })} />
              <div className="dz-hint">
                {uploading === i ? (
                  <>
                    <span className="spin dark" /> Uploading…
                  </>
                ) : (
                  <>
                    <button type="button" className="link" onClick={() => inputs.current[i]?.click()}>
                      Upload a PDF
                    </button>{" "}
                    or{" "}
                    <button type="button" className="link" onClick={() => setPicking(i)}>
                      choose from library
                    </button>
                  </>
                )}
              </div>
              <input
                ref={(el) => {
                  inputs.current[i] = el;
                }}
                type="file"
                accept="application/pdf"
                hidden
                onChange={(e) => {
                  void upload(i, e.target.files?.[0]);
                  e.target.value = "";
                }}
              />
              <FieldError msg={errors[`files.${i}.url`] ?? errors[`files.${i}`]} />
            </div>
          </div>
        </div>
      ))}
      {problem && <FieldError msg={problem} />}
      <FieldError msg={errors.files} />
      {value.length < 5 && (
        <button type="button" className="btn-plain" style={{ color: "var(--blue)" }} onClick={() => onChange([...value, { url: "", label: "" }])}>
          <Icon name="plus" size={15} />
          Add file
        </button>
      )}
      {picking !== null && (
        <MediaPicker
          kind="document"
          onClose={() => setPicking(null)}
          onPick={(m: Media) => {
            setAt(picking, { url: mediaUrl(m), ...(value[picking].label ? {} : { label: m.title || "Spec sheet" }) });
            setPicking(null);
          }}
        />
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Variants                                                            */
/* ------------------------------------------------------------------ */

function Variants({
  form: f,
  set,
  attributes,
  errs,
  productId,
  currency,
  priceUnit,
  onRequest,
}: {
  form: Form;
  set: (patch: Partial<Form>) => void;
  attributes: Attribute[];
  errs: Record<string, string>;
  productId?: string;
  currency: string;
  priceUnit: string;
  onRequest: boolean;
}) {
  const uid = useId();
  const [skuCheck, setSkuCheck] = useState<Record<string, string | null>>({});
  const attrById = (id: string) => attributes.find((a) => a.id === id);
  const valueLabel = (attrId: string, slug: string) => tr(attrById(attrId)?.values.find((v) => v.slug === slug)?.translations, "en", "label") || slug;

  const setAttrs = (next: Attrs) => set({ attributes: next, rows: rebuildRows(f.attributes, next, f.rows) });
  const toggleAttr = (a: Attribute, on: boolean) => setAttrs(on ? [...f.attributes, { attributeId: a.id, values: a.values[0] ? [a.values[0].slug] : [] }] : f.attributes.filter((x) => x.attributeId !== a.id));
  const toggleValue = (attrId: string, slug: string, on: boolean) => {
    const a = attrById(attrId);
    setAttrs(
      f.attributes.map((x) => {
        if (x.attributeId !== attrId) return x;
        const vals = on ? [...x.values, slug] : x.values.filter((v) => v !== slug);
        // Keep the catalog's value order.
        return { ...x, values: (a?.values.map((v) => v.slug) ?? vals).filter((v) => vals.includes(v)) };
      }),
    );
  };
  const setRow = (key: string, patch: Partial<Row>) => set({ rows: f.rows.map((r) => (r.key === key ? { ...r, ...patch } : r)) });
  const setDefault = (key: string) => set({ rows: f.rows.map((r) => ({ ...r, isDefault: r.key === key })) });
  const removeRow = (key: string) => {
    const rows = f.rows.filter((r) => r.key !== key);
    if (rows.length && !rows.some((r) => r.isDefault)) rows[0] = { ...rows[0], isDefault: true };
    set({ rows });
  };
  const missing = f.type === "variable" && f.attributes.length && f.attributes.every((a) => a.values.length) ? combos(f.attributes).filter((c) => !f.rows.some((r) => comboKey(r.attributeValues, f.attributes) === comboKey(c, f.attributes))) : [];

  const checkSku = async (key: string, sku: string) => {
    const s = sku.trim().toUpperCase();
    if (!s) return setSkuCheck((x) => ({ ...x, [key]: null }));
    if (f.rows.some((r) => r.key !== key && r.sku.trim().toUpperCase() === s)) return setSkuCheck((x) => ({ ...x, [key]: "Another row of this product has this SKU." }));
    try {
      const r = await productsApi.skuCheck(s, productId);
      setSkuCheck((x) => ({ ...x, [key]: r.available ? null : `Already used by product "${r.usedBy}".` }));
    } catch {
      /* the save reports it anyway */
    }
  };

  const rows = f.type === "simple" ? f.rows.slice(0, 1) : f.rows;
  const rowIndex = (key: string) => f.rows.findIndex((r) => r.key === key);

  return (
    <>
      {f.type === "variable" && (
        <div className="field">
          <div className="fs-title">Attributes (1-3) and the values on sale</div>
          {attributes.length === 0 && (
            <div className="hint">
              No attributes yet: add them in <Link href="/admin/catalog" className="link">Product Catalog</Link>.
            </div>
          )}
          {attributes.map((a) => {
            const chosen = f.attributes.find((x) => x.attributeId === a.id);
            return (
              <div key={a.id} className="repeat">
                <label className="check" style={{ marginBottom: chosen ? 10 : 0 }}>
                  <input type="checkbox" checked={!!chosen} disabled={!chosen && f.attributes.length >= 3} onChange={(e) => toggleAttr(a, e.target.checked)} />
                  <span>
                    <b>{tr(a.translations, "en", "name")}</b>
                  </span>
                </label>
                {chosen && (
                  <div className="chip-set">
                    {a.values.map((v) => {
                      const on = chosen.values.includes(v.slug);
                      return (
                        <label key={v.id} className={`chip-check${on ? " on" : ""}`}>
                          <input type="checkbox" checked={on} onChange={(e) => toggleValue(a.id, v.slug, e.target.checked)} />
                          {tr(v.translations, "en", "label")}
                        </label>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
          <FieldError msg={errs.attributes} />
          {f.attributes.map((a, i) => (
            <FieldError key={a.attributeId} msg={errs[`attributes.${i}`] ?? errs[`attributes.${i}.values`]} />
          ))}
        </div>
      )}

      <div className="row-between" style={{ margin: "8px 0 10px" }}>
        <div className="fs-title" style={{ margin: 0 }}>
          {f.type === "simple" ? "The variant" : `Variants (${rows.length} of max 100): one per combination sold`}
        </div>
        {missing.length > 0 && (
          <button type="button" className="btn-plain" style={{ color: "var(--blue)" }} onClick={() => set({ rows: [...f.rows, ...missing.map((c) => emptyRow(c))] })}>
            <Icon name="plus" size={15} />
            Add missing combinations ({missing.length})
          </button>
        )}
      </div>
      {onRequest && <div className="info-note">Prices are on request: they are stored but not shown on the website.</div>}
      <FieldError msg={errs.variants} />
      {rows.map((r) => {
        const i = rowIndex(r.key);
        const e = (k: string) => errs[`variants.${i}.${k}`];
        const title = f.type === "simple" ? "" : f.attributes.map((a) => valueLabel(a.attributeId, r.attributeValues[a.attributeId] ?? "")).join(" × ");
        const sell = cents(r.selling);
        const market = cents(r.market);
        return (
          <div key={r.key} className="repeat" style={{ opacity: r.isActive ? 1 : 0.7 }}>
            <div className="repeat-h">
              <b style={{ color: "var(--ink)", fontSize: 13 }}>{title || (f.type === "simple" ? "Variant" : `Row ${i + 1}`)}</b>
              <span style={{ display: "flex", gap: 12, alignItems: "center" }}>
                {f.type === "variable" && (
                  <label className="check small">
                    <input type="radio" name={`${uid}-default`} checked={r.isDefault} onChange={() => setDefault(r.key)} />
                    <span>Default</span>
                  </label>
                )}
                <label className="check small" title="Inactive variants aren't sold on the website">
                  <input type="checkbox" checked={r.isActive} onChange={(ev) => setRow(r.key, { isActive: ev.target.checked })} />
                  <span>Active</span>
                </label>
                {f.type === "variable" && (
                  <span className="repeat-tools">
                    <button type="button" aria-label={`Delete ${title || "row"}`} title="Delete this row (combination not sold)" onClick={() => removeRow(r.key)}>
                      <Icon name="x" size={14} />
                    </button>
                  </span>
                )}
              </span>
            </div>
            <FieldError msg={errs[`variants.${i}`] ?? e("attributeValues")} />
            <div className="form-grid" style={{ gridTemplateColumns: "repeat(3, minmax(0, 1fr))" }}>
              <div className="field">
                <label htmlFor={`${uid}-sku-${r.key}`}>
                  SKU <span className="req">*</span>
                </label>
                <input
                  id={`${uid}-sku-${r.key}`}
                  className="input input-sm"
                  maxLength={40}
                  placeholder="BP-25-A"
                  value={r.sku}
                  onChange={(ev) => setRow(r.key, { sku: ev.target.value.toUpperCase() })}
                  onBlur={(ev) => void checkSku(r.key, ev.target.value)}
                  aria-invalid={!!(e("sku") || skuCheck[r.key])}
                />
                <FieldError msg={e("sku") ?? skuCheck[r.key]} />
              </div>
              <div className="field">
                <label htmlFor={`${uid}-mp-${r.key}`}>
                  Market price ({currency} / {priceUnit})
                </label>
                <input id={`${uid}-mp-${r.key}`} className="input input-sm" inputMode="decimal" placeholder="520.00" value={r.market} onChange={(ev) => setRow(r.key, { market: ev.target.value })} />
                <FieldError msg={e("marketPrice")} />
              </div>
              <div className="field">
                <label htmlFor={`${uid}-sp-${r.key}`}>
                  Selling price ({currency} / {priceUnit}) <span className="req">*</span>
                </label>
                <input id={`${uid}-sp-${r.key}`} className="input input-sm" inputMode="decimal" placeholder="480.00" value={r.selling} onChange={(ev) => setRow(r.key, { selling: ev.target.value })} />
                <FieldError msg={e("sellingPrice") ?? (sell !== undefined && market !== undefined && sell > market ? "The selling price can't be higher than the market price." : undefined)} />
              </div>
              <div className="field">
                <div className="lbl">Size (L × W × H)</div>
                <div style={{ display: "flex", gap: 4 }}>
                  {(["length", "width", "height"] as const).map((k) => (
                    <input key={k} className="input input-sm" aria-label={k} inputMode="decimal" placeholder={k[0].toUpperCase()} value={r.dims[k]} onChange={(ev) => setRow(r.key, { dims: { ...r.dims, [k]: ev.target.value } })} />
                  ))}
                  <select className="select" aria-label="Size unit" value={r.dims.unit} onChange={(ev) => setRow(r.key, { dims: { ...r.dims, unit: ev.target.value as Row["dims"]["unit"] } })}>
                    {LENGTH_UNITS.map((u) => (
                      <option key={u}>{u}</option>
                    ))}
                  </select>
                </div>
                <FieldError msg={e("dimensions") ?? e("dimensions.length") ?? e("dimensions.width") ?? e("dimensions.height")} />
              </div>
              <div className="field">
                <div className="lbl">Weight</div>
                <div style={{ display: "flex", gap: 4 }}>
                  <input className="input input-sm" aria-label="Weight" inputMode="decimal" placeholder="25" value={r.weight.value} onChange={(ev) => setRow(r.key, { weight: { ...r.weight, value: ev.target.value } })} />
                  <select className="select" aria-label="Weight unit" value={r.weight.unit} onChange={(ev) => setRow(r.key, { weight: { ...r.weight, unit: ev.target.value as Row["weight"]["unit"] } })}>
                    {WEIGHT_UNITS.map((u) => (
                      <option key={u}>{u}</option>
                    ))}
                  </select>
                </div>
                <FieldError msg={e("weight") ?? e("weight.value")} />
              </div>
            </div>
            <details>
              <summary className="link" style={{ marginBottom: 8 }}>
                Image and gallery{r.image?.url ? " · image set" : ""}
                {r.gallery.length ? ` · ${r.gallery.length} in gallery` : ""}
              </summary>
              <SchemaField
                field={{ kind: "image", key: "image", label: "Variant image (default: the listing thumbnail)" }}
                value={r.image ?? {}}
                onChange={(v) => setRow(r.key, { image: (v as Img)?.url ? (v as Img) : null })}
                errors={errs}
                path={`variants.${i}.image`}
              />
              <ImageList label="Variant gallery (default: the product gallery)" max={10} value={r.gallery} onChange={(gallery) => setRow(r.key, { gallery })} errors={errs} path={`variants.${i}.gallery`} />
            </details>
          </div>
        );
      })}
      {f.type === "variable" && f.attributes.length === 0 && <div className="hint">Choose at least one attribute and its values to build the variants.</div>}
    </>
  );
}

/* ------------------------------------------------------------------ */
/* Preview                                                             */
/* ------------------------------------------------------------------ */

const PREVIEW_WIDTH = 1280;

/** The product page with drafts (GET /admin/products/:id/preview), rendered by the website in an iframe. */
function ProductPreview({ id, lang, langName, dirty, onClose }: { id: string; lang: string; langName: string; dirty: boolean; onClose: () => void }) {
  const frame = useRef<HTMLIFrameElement>(null);
  const box = useRef<HTMLDivElement>(null);
  const [data, setData] = useState<unknown>(null);
  const [error, setError] = useState<string | null>(null);
  const [height, setHeight] = useState(900);
  const [scale, setScale] = useState(0.5);

  useEffect(() => {
    let live = true;
    productsApi
      .preview(id, lang)
      .then((d) => live && setData(d))
      .catch((e) => live && setError(errorMessage(e)));
    return () => {
      live = false;
    };
  }, [id, lang]);

  useEffect(() => {
    const el = box.current;
    if (!el) return;
    const ro = new ResizeObserver(() => setScale(el.clientWidth / PREVIEW_WIDTH));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  useEffect(() => {
    const send = () => data && frame.current?.contentWindow?.postMessage({ type: "cms-preview:product", product: data } satisfies ToPreview, location.origin);
    const onMessage = (e: MessageEvent) => {
      if (e.origin !== location.origin || e.source !== frame.current?.contentWindow || !isPreviewMessage(e.data)) return;
      const m = e.data as FromPreview;
      if (m.type === "cms-preview:ready") send();
      else if (m.type === "cms-preview:height") setHeight(m.height);
    };
    addEventListener("message", onMessage);
    send();
    return () => removeEventListener("message", onMessage);
  }, [data]);

  return (
    <Modal title={`Preview · ${langName}`} onClose={onClose} wide>
      {dirty && <div className="info-note" style={{ marginBottom: 12 }}>Unsaved changes aren&apos;t in the preview: save first.</div>}
      {error ? (
        <div className="form-error">{error}</div>
      ) : (
        <div ref={box} style={{ height: Math.min(height * scale, 640), overflow: "auto", border: "1px solid var(--line)", borderRadius: 8, position: "relative" }}>
          {!data && (
            <div className="ml-empty">
              <span className="spin dark" /> Loading preview…
            </div>
          )}
          <div style={{ height: height * scale }}>
            <iframe
              ref={frame}
              src="/cms-preview/product"
              title="Product page preview"
              style={{ width: PREVIEW_WIDTH, height, border: 0, transform: `scale(${scale})`, transformOrigin: "0 0", display: data ? "block" : "none" }}
            />
          </div>
        </div>
      )}
    </Modal>
  );
}
