"use client";

/**
 * Article form (API reference: "How articles work (admin panel)"). One screen, one Save:
 * the shared fields (category, cover image, author, address) and the text of each
 * language go in one request.
 *
 * - Shared fields change on the website as soon as they're saved; text changes wait
 *   until that language is published.
 * - Only languages whose text changed are sent (a language sent becomes a draft again,
 *   the live text stays until published). "Remove text" sends null for a language.
 * - The body is a list of blocks: paragraph, heading (H2/H3), list, quote, image.
 * - Save sends back `version`; a 409 means someone else saved first (reload).
 */
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 } from "@/app/(admin)/_lib/api";
import {
  BLOCK_TYPES,
  articleLangBadge,
  articlesApi,
  sendArticle,
  type Article,
  type ArticleBlock,
  type ArticleSaveBody,
  type ArticleText,
  type BlockType,
} from "@/app/(admin)/_lib/articles";
import type { Img } from "@/app/(admin)/_lib/cms";
import { MEDIA_ORIGIN } from "@/app/(admin)/_lib/media";
import { isSlug, tr } from "@/app/(admin)/_lib/products";
import { qk, useArticle, useArticleCategories } from "@/app/(admin)/_lib/queries";
import { useStore } from "@/app/(admin)/_lib/store";
import { isPreviewMessage, type FromPreview, type ToPreview } from "@/app/(site)/_lib/previewProtocol";
import { refreshArticlesOnSite } from "./ArticlesList";
import { useActiveLangs } from "./CatalogPage";
import { Icon } from "./Icon";
import { ConfirmDialog, Modal } from "./Modal";
import { SchemaField } from "./SchemaField";
import { PageHeader } from "./ui";

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

/** One body block in the form: every field of every type, so switching type keeps the text. */
type BlockForm = { key: string; type: BlockType; text: string; level: 2 | 3; style: "bullet" | "numbered"; items: string; source: string; image: Img | null; caption: string };
type TextForm = { title: string; excerpt: string; body: BlockForm[]; seoTitle: string; seoDescription: string };
type Form = { categoryId: string; coverImage: Img | null; authorName: string; authorRole: string; slug: string; texts: Record<string, TextForm> };

let keySeq = 0;
const newKey = () => `b${++keySeq}`;
const emptyBlock = (type: BlockType): BlockForm => ({ key: newKey(), type, text: "", level: 2, style: "bullet", items: "", source: "", image: null, caption: "" });
const emptyText = (): TextForm => ({ title: "", excerpt: "", body: [emptyBlock("paragraph")], seoTitle: "", seoDescription: "" });
const isEmptyText = (t?: TextForm) =>
  !t || (![t.title, t.excerpt, t.seoTitle, t.seoDescription].some((x) => x.trim()) && !t.body.some((b) => b.text.trim() || b.items.trim() || b.image?.url || b.caption.trim()));
const emptyForm = (): Form => ({ categoryId: "", coverImage: null, authorName: "", authorRole: "", slug: "", texts: { en: emptyText() } });
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);

function blockFrom(b: ArticleBlock): BlockForm {
  const f = emptyBlock(b.type);
  switch (b.type) {
    case "paragraph":
      return { ...f, text: b.text ?? "" };
    case "heading":
      return { ...f, text: b.text ?? "", level: b.level === 3 ? 3 : 2 };
    case "list":
      return { ...f, items: (b.items ?? []).join("\n"), style: b.style === "numbered" ? "numbered" : "bullet" };
    case "quote":
      return { ...f, text: b.text ?? "", source: b.source ?? "" };
    case "image":
      return { ...f, image: b.url ? { url: b.url, ...(b.alt ? { alt: b.alt } : {}) } : null, caption: b.caption ?? "" };
  }
}

function blockBody(b: BlockForm): ArticleBlock {
  switch (b.type) {
    case "paragraph":
      return { type: "paragraph", text: b.text.trim() };
    case "heading":
      return { type: "heading", level: b.level, text: b.text.trim() };
    case "list":
      return { type: "list", style: b.style, items: b.items.split("\n").map((x) => x.trim()).filter(Boolean) };
    case "quote":
      return { type: "quote", text: b.text.trim(), ...(b.source.trim() ? { source: b.source.trim() } : {}) };
    case "image": {
      const img = cleanImg(b.image);
      return { type: "image", url: img?.url ?? "", ...(img?.alt ? { alt: img.alt } : {}), ...(b.caption.trim() ? { caption: b.caption.trim() } : {}) };
    }
  }
}

const textFrom = (t: ArticleText | null | undefined): TextForm =>
  t
    ? { title: t.title ?? "", excerpt: t.excerpt ?? "", body: (t.body ?? []).map(blockFrom), seoTitle: t.seo?.title ?? "", seoDescription: t.seo?.description ?? "" }
    : emptyText();

function formFrom(a: Article): Form {
  return {
    categoryId: a.categoryId ?? "",
    coverImage: a.coverImage ?? null,
    authorName: a.author?.name ?? "",
    authorRole: a.author?.role ?? "",
    slug: a.slug,
    // The draft is what the editor works on; a language with only live text starts from that.
    texts: Object.fromEntries(Object.entries(a.translations).map(([l, t]) => [l, textFrom(t.draft ?? t.published)])),
  };
}

function textBody(t: TextForm): ArticleText {
  const seo = { ...(t.seoTitle.trim() ? { title: t.seoTitle.trim() } : {}), ...(t.seoDescription.trim() ? { description: t.seoDescription.trim() } : {}) };
  return { title: t.title.trim(), excerpt: t.excerpt.trim(), body: t.body.map(blockBody), ...(Object.keys(seo).length ? { seo } : {}) };
}

/** Languages whose text differs from the loaded version (and isn't empty). */
const changedLangs = (f: Form, base: Form) => Object.keys(f.texts).filter((l) => !isEmptyText(f.texts[l]) && JSON.stringify(f.texts[l]) !== JSON.stringify(base.texts[l]));

function bodyFrom(f: Form, langs: string[], removed: string[], article: Article | null): ArticleSaveBody {
  const translations: ArticleSaveBody["translations"] = {};
  for (const l of langs) translations[l] = textBody(f.texts[l]);
  for (const l of removed) translations[l] = null;
  const slug = f.slug.trim();
  return {
    categoryId: f.categoryId,
    coverImage: cleanImg(f.coverImage) as Img,
    author: f.authorName.trim() ? { name: f.authorName.trim(), ...(f.authorRole.trim() ? { role: f.authorRole.trim() } : {}) } : null,
    // New: left out to make it from the English title. Saved: sent only when changed.
    ...(slug && slug !== article?.slug ? { slug } : {}),
    translations,
  };
}

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

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

function ArticleForm({ article }: { article: Article | 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: categories } = useArticleCategories();

  const base = useMemo(() => (article ? formFrom(article) : emptyForm()), [article]);
  const [f, setF] = useState<Form>(base);
  // A newer version arrived (saved, published, reloaded): the form shows it. The language stays.
  const [shownBase, setShownBase] = useState(base);
  if (shownBase !== base) {
    setShownBase(base);
    setF(base);
  }
  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 [busy, setBusy] = useState<string | null>(null);
  const [rejecting, setRejecting] = useState(false);
  const [comment, setComment] = useState("");
  const [removing, setRemoving] = useState(false);
  const [previewing, setPreviewing] = useState(false);

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

  const dirty = JSON.stringify(f) !== JSON.stringify(base);
  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 err = (path: string) => errs[path];

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

  const after = (a: Article) => {
    qc.setQueryData(qk.article(a.id), a);
    qc.invalidateQueries({ queryKey: qk.articles() });
  };

  /** Saves when needed; returns the saved article (or the loaded one when nothing changed). */
  const save = async (removed: string[] = []): Promise<Article | null> => {
    if (article && !dirty && !removed.length) return article;
    setErrs({});
    setFormError(null);
    // New: English always goes (required), so its empty fields are reported one by one.
    const langsToSend = article ? changedLangs(f, base).filter((l) => !removed.includes(l)) : Object.keys(f.texts).filter((l) => l === "en" || !isEmptyText(f.texts[l]));
    const body = bodyFrom(f, langsToSend, removed, article);
    try {
      const a = article
        ? await sendArticle((b) => articlesApi.save(article.id, { ...b, version: article.version }), body, MEDIA_ORIGIN)
        : await sendArticle(articlesApi.create, body, MEDIA_ORIGIN);
      after(a);
      // Shared fields (category, cover, author, address) change on the website at once.
      if (a.live) refreshArticlesOnSite();
      if (!article) {
        setCreatedAt(pathname);
        router.replace(`/admin/articles/${a.id}`);
      }
      return a;
    } catch (e) {
      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 l = /^translations\.([^.]+)\./.exec(Object.keys(fe)[0] ?? "")?.[1];
        if (l) setLang(l);
      }
      return null;
    }
  };

  const run = async (label: string, action?: "submit" | "publish" | "unpublish") => {
    setBusy(label);
    try {
      let a = action === "unpublish" ? article : await save();
      if (!a) return;
      // Saving only shared fields leaves a published language as it is: nothing left to publish.
      if (action === "publish" && a.translations[lang]?.status === "published") {
        toast("Saved: the change is on the website");
        return;
      }
      if (action) {
        a = await articlesApi.action(a.id, action, lang);
        after(a);
      }
      if (action === "publish" || action === "unpublish") refreshArticlesOnSite();
      toast({ Save: article ? "Saved" : "Article 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 (!article) return;
    setBusy("Reject");
    try {
      after(await articlesApi.reject(article.id, lang, comment.trim()));
      toast("Sent back with your comment");
      setRejecting(false);
      setComment("");
    } catch (e) {
      toast(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const removeLang = async () => {
    setBusy("Remove");
    try {
      const a = await save([lang]);
      if (!a) return;
      if (a.liveLanguages.includes(lang) || article?.liveLanguages.includes(lang)) refreshArticlesOnSite();
      toast(`${langName(lang)} text removed`);
      setRemoving(false);
      setLang("en");
    } finally {
      setBusy(null);
    }
  };

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

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

  const t = article?.translations[lang];
  const live = !!article?.liveLanguages.includes(lang);
  const badge = articleLangBadge(t?.status ?? "missing", live);
  const canSubmit = !!article && (dirty || t?.status === "draft");
  const canPublish = !!article && (dirty || t?.status === "in_review" || (t?.status === "draft" && t.source !== "ai"));
  const canUnpublish = !!article && !!t?.published && live;

  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();
  const tp = `translations.${lang}`;

  const activeCats = (categories ?? []).filter((c) => c.isActive || c.id === f.categoryId);
  const slugProblem = f.slug && !isSlug(f.slug) ? "Lowercase letters and numbers joined by single hyphens (3-120)." : null;

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

  return (
    <div className="page">
      <PageHeader
        crumb={
          <>
            Website ›{" "}
            <Link href="/admin/articles" className="link" style={{ fontSize: "inherit" }}>
              Articles
            </Link>
          </>
        }
        title={f.texts.en?.title || (article ? article.slug : "New article")}
        desc={article ? "Category, cover image, author and address are shared by every language and change on the website when saved; text is published per language." : "Write the English text, then create the article as a draft. Nothing is on the website until a language is published."}
      >
        {article?.live && (
          <Link href={`/articles/${article.slug}`} target="_blank" className="btn btn-outline btn-sm">
            <Icon name="eye" size={14} />
            View on website
          </Link>
        )}
        {article && (
          <button type="button" className="btn btn-outline btn-sm" disabled={!!busy} onClick={() => setPreviewing(true)} title="The article 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 || (!!article && !dirty) || !!slugProblem} onClick={() => run("Save")}>
          {busy === "Save" ? <span className="spin" /> : article ? "Save" : "Create article"}
        </button>
      </PageHeader>

      {conflict && (
        <div className="review-note" role="alert" style={{ marginBottom: 16 }}>
          <b>Someone else saved this article 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>
      )}
      {article?.status === "archived" && <div className="info-note" style={{ marginBottom: 16 }}>This article is archived: it isn&apos;t on the website in any language. Restore it from the Articles list.</div>}

      {/* Language + workflow bar */}
      {article && (
        <div className="card ed-bar">
          <div className="grp">
            <label>Language</label>
            <div className="seg" role="group" aria-label="Language">
              {langs.map((l) => {
                const b = articleLangBadge(article.translations[l.code]?.status ?? "missing", article.liveLanguages.includes(l.code));
                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 === "g" ? "pub" : ""}`} style={{ marginLeft: 6, opacity: b.tone === "n" ? 0.3 : 1 }} />
                  </button>
                );
              })}
            </div>
          </div>
          <span className={`tag ${badge.tone}`}>
            {langName(lang)}: {badge.label}
          </span>
          {article.live ? <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 || !!slugProblem} 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>
      )}

      {/* Shared fields */}
      <div className="card" style={{ marginBottom: 16 }}>
        <div className="card-h">
          <div>
            <h3>Article</h3>
            <div className="sub">Shared by every language.</div>
          </div>
        </div>
        <div className="card-b">
          <div className="form-grid">
            <div className="field">
              <label htmlFor={`${uid}-cat`}>
                Category <span className="req">*</span>
              </label>
              <select id={`${uid}-cat`} className="select input" value={f.categoryId} onChange={(e) => set({ categoryId: e.target.value })} aria-invalid={!!err("categoryId")}>
                <option value="">— Choose a category —</option>
                {activeCats.map((c) => (
                  <option key={c.id} value={c.id}>
                    {tr(c.translations, "en", "name")}
                    {c.isActive ? "" : " (inactive)"}
                  </option>
                ))}
              </select>
              {err("categoryId") ? (
                <div className="hint bad">{err("categoryId")}</div>
              ) : (
                categories?.length === 0 && (
                  <div className="hint">
                    No categories yet: add them under{" "}
                    <Link href="/admin/articles" className="link">
                      Articles › Categories
                    </Link>
                    .
                  </div>
                )
              )}
            </div>
            <div className="field">
              <label htmlFor={`${uid}-slug`}>Address</label>
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ color: "var(--muted)", whiteSpace: "nowrap" }}>/articles/</span>
                <input
                  id={`${uid}-slug`}
                  className="input"
                  maxLength={120}
                  placeholder={article ? "" : "made from the English title"}
                  value={f.slug}
                  onChange={(e) => set({ slug: e.target.value.toLowerCase() })}
                  aria-invalid={!!(slugProblem || err("slug"))}
                />
              </div>
              {slugProblem || err("slug") ? (
                <div className="hint bad">{slugProblem ?? err("slug")}</div>
              ) : (
                article?.firstPublishedAt && <div className="hint">Changing it keeps the old address working (it redirects here).</div>
              )}
            </div>
            <div className="field">
              <label htmlFor={`${uid}-author`}>Author (optional)</label>
              <input id={`${uid}-author`} className="input" maxLength={120} placeholder="Name" value={f.authorName} onChange={(e) => set({ authorName: e.target.value })} aria-invalid={!!err("author.name")} />
              {err("author.name") && <div className="hint bad">{err("author.name")}</div>}
            </div>
            <div className="field">
              <label htmlFor={`${uid}-role`}>Author&apos;s role</label>
              <input id={`${uid}-role`} className="input" maxLength={120} placeholder="Head of Research" value={f.authorRole} disabled={!f.authorName.trim()} onChange={(e) => set({ authorRole: e.target.value })} />
            </div>
          </div>
          <SchemaField
            field={{ kind: "image", key: "coverImage", label: "Cover image (card and article page, max 10 MB)", required: true }}
            value={f.coverImage ?? {}}
            onChange={(v) => set({ coverImage: v && typeof v === "object" && (v as Img).url ? (v as Img) : null })}
            errors={errs}
            path="coverImage"
          />
        </div>
      </div>

      {/* Text of the selected language */}
      <div className="card">
        <div className="card-h">
          <div>
            <h3>Text · {langName(lang)}</h3>
            <div className="sub">
              {article ? "Saving keeps the live text on the website until this language is published again." : "Other languages can be added once the article exists."}
              {lang !== "en" && !article?.translations[lang] && !f.texts[lang] && " Empty languages fall back to English on the website."}
            </div>
          </div>
          {article && lang !== "en" && article.translations[lang] && (
            <button type="button" className="btn-plain danger" disabled={!!busy} onClick={() => setRemoving(true)}>
              Remove {langName(lang)} text
            </button>
          )}
        </div>
        <div className="card-b">
          <TextField id={`${uid}-title`} label="Title" required max={200} value={text.title} onChange={(title) => setText({ title })} error={err(`${tp}.title`)} />
          <TextField
            id={`${uid}-excerpt`}
            label="Excerpt (card text and the lead under the title)"
            required
            multiline
            max={400}
            value={text.excerpt}
            onChange={(excerpt) => setText({ excerpt })}
            error={err(`${tp}.excerpt`)}
          />
          <BodyEditor blocks={text.body} onChange={(body) => setText({ body })} errs={errs} path={`${tp}.body`} />
          <div className="fs-title" style={{ marginTop: 8 }}>
            Search engines (optional)
          </div>
          <div className="form-grid">
            <TextField id={`${uid}-seo-t`} label="SEO title (default: the title)" max={70} value={text.seoTitle} onChange={(seoTitle) => setText({ seoTitle })} error={err(`${tp}.seo.title`)} />
            <TextField
              id={`${uid}-seo-d`}
              label="SEO description (default: the excerpt)"
              multiline
              rows={2}
              max={160}
              value={text.seoDescription}
              onChange={(seoDescription) => setText({ seoDescription })}
              error={err(`${tp}.seo.description`)}
            />
          </div>
        </div>
      </div>

      {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>
      )}
      {removing && (
        <ConfirmDialog title={`Remove the ${langName(lang)} text?`} confirmLabel={`Remove ${langName(lang)}`} danger busy={busy === "Remove"} onConfirm={removeLang} onClose={() => setRemoving(false)}>
          The {langName(lang)} draft and live text are deleted; visitors in that language see the English article. Other unsaved changes are saved too.
        </ConfirmDialog>
      )}
      {previewing && article && <ArticlePreview id={article.id} lang={lang} langName={langName(lang)} dirty={dirty} onClose={() => setPreviewing(false)} />}
    </div>
  );
}

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

function TextField({
  id,
  label,
  value,
  onChange,
  max,
  required,
  multiline,
  rows = 3,
  error,
  hint,
}: {
  id: string;
  label: string;
  value: string;
  onChange: (v: string) => void;
  max: number;
  required?: boolean;
  multiline?: boolean;
  rows?: number;
  error?: string;
  hint?: 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} />
      )}
      {error ? <div className="hint bad">{error}</div> : hint && <div className="hint">{hint}</div>}
    </div>
  );
}

const LABEL: Record<BlockType, string> = Object.fromEntries(BLOCK_TYPES.map((b) => [b.type, b.label])) as Record<BlockType, string>;

/** The article body: blocks in order, each with its own fields; add, move, remove. */
function BodyEditor({ blocks, onChange, errs, path }: { blocks: BlockForm[]; onChange: (b: BlockForm[]) => void; errs: Record<string, string>; path: string }) {
  const uid = useId();
  const setBlock = (i: number, patch: Partial<BlockForm>) => onChange(blocks.map((b, j) => (j === i ? { ...b, ...patch } : b)));
  const move = (i: number, d: -1 | 1) => {
    const next = [...blocks];
    [next[i], next[i + d]] = [next[i + d], next[i]];
    onChange(next);
  };
  /** The API's messages for one block (e.g. translations.en.body.2.text). */
  const blockErr = (i: number) =>
    Object.entries(errs)
      .filter(([p]) => p === `${path}.${i}` || p.startsWith(`${path}.${i}.`))
      .map(([, m]) => m)
      .join("; ");

  return (
    <div className="field">
      <div className="fs-title">
        Body <span className="req">*</span> ({blocks.length} block{blocks.length === 1 ? "" : "s"})
      </div>
      {errs[path] && <div className="hint bad">{errs[path]}</div>}
      {blocks.map((b, i) => {
        // From the position, not b.key: keys come from a counter that differs between server and browser.
        const id = `${uid}-block-${i}`;
        const e = blockErr(i);
        return (
          <div className="repeat" key={b.key}>
            <div className="repeat-h">
              <b>
                {LABEL[b.type]} · {i + 1}
              </b>
              <span className="repeat-tools">
                <button type="button" title="Move up" aria-label={`Move block ${i + 1} up`} disabled={i === 0} onClick={() => move(i, -1)}>
                  ↑
                </button>
                <button type="button" title="Move down" aria-label={`Move block ${i + 1} down`} disabled={i === blocks.length - 1} onClick={() => move(i, 1)}>
                  ↓
                </button>
                <button type="button" title="Remove" aria-label={`Remove block ${i + 1}`} onClick={() => onChange(blocks.filter((_, j) => j !== i))}>
                  <Icon name="x" size={14} />
                </button>
              </span>
            </div>
            {b.type === "paragraph" && (
              <div className="field">
                <textarea id={id} aria-label={`Paragraph ${i + 1}`} className="input" rows={5} maxLength={5000} value={b.text} onChange={(ev) => setBlock(i, { text: ev.target.value })} />
                <div className="hint">Plain text. A blank line starts a new paragraph.</div>
              </div>
            )}
            {b.type === "heading" && (
              <div style={{ display: "flex", gap: 8 }}>
                <select className="select input" style={{ width: 150 }} aria-label="Heading level" value={b.level} onChange={(ev) => setBlock(i, { level: Number(ev.target.value) === 3 ? 3 : 2 })}>
                  <option value={2}>Section (H2)</option>
                  <option value={3}>Subsection (H3)</option>
                </select>
                <input id={id} aria-label={`Heading ${i + 1}`} className="input" maxLength={200} value={b.text} onChange={(ev) => setBlock(i, { text: ev.target.value })} />
              </div>
            )}
            {b.type === "list" && (
              <div className="field">
                <select className="select input" style={{ width: 170, marginBottom: 8 }} aria-label="List style" value={b.style} onChange={(ev) => setBlock(i, { style: ev.target.value === "numbered" ? "numbered" : "bullet" })}>
                  <option value="bullet">Bullet points</option>
                  <option value="numbered">Numbered</option>
                </select>
                <textarea id={id} aria-label={`List ${i + 1} items`} className="input" rows={4} value={b.items} onChange={(ev) => setBlock(i, { items: ev.target.value })} />
                <div className="hint">One item per line (up to 50).</div>
              </div>
            )}
            {b.type === "quote" && (
              <>
                <div className="field">
                  <textarea id={id} aria-label={`Quote ${i + 1}`} className="input" rows={3} maxLength={1000} value={b.text} onChange={(ev) => setBlock(i, { text: ev.target.value })} />
                </div>
                <div className="field">
                  <input aria-label={`Quote ${i + 1} source`} className="input input-sm" maxLength={200} placeholder="Who said it (optional)" value={b.source} onChange={(ev) => setBlock(i, { source: ev.target.value })} />
                </div>
              </>
            )}
            {b.type === "image" && (
              <>
                <SchemaField field={{ kind: "image", key: "image", label: "Image (max 10 MB)", required: true }} value={b.image ?? {}} onChange={(v) => setBlock(i, { image: v && typeof v === "object" && (v as Img).url ? (v as Img) : null })} errors={{}} path={`${path}.${i}`} />
                <div className="field">
                  <input aria-label={`Image ${i + 1} caption`} className="input input-sm" maxLength={300} placeholder="Caption (optional)" value={b.caption} onChange={(ev) => setBlock(i, { caption: ev.target.value })} />
                </div>
              </>
            )}
            {e && <div className="hint bad">{e}</div>}
          </div>
        );
      })}
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, alignItems: "center" }}>
        <span style={{ color: "var(--muted)", fontSize: 12 }}>Add:</span>
        {BLOCK_TYPES.map((x) => (
          <button key={x.type} type="button" className="btn btn-outline btn-sm" onClick={() => onChange([...blocks, emptyBlock(x.type)])}>
            <Icon name="plus" size={13} />
            {x.label}
          </button>
        ))}
      </div>
    </div>
  );
}

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

const PREVIEW_WIDTH = 1280;

/** The article page with drafts (GET /admin/articles/:id/preview), rendered by the website in an iframe. */
function ArticlePreview({ 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;
    articlesApi
      .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:article", article: 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/article"
              title="Article page preview"
              style={{ width: PREVIEW_WIDTH, height, border: 0, transform: `scale(${scale})`, transformOrigin: "0 0", display: data ? "block" : "none" }}
            />
          </div>
        </div>
      )}
    </Modal>
  );
}
