"use client";

import { useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { errorMessage, fieldErrors, getAccessToken } from "@/app/(admin)/_lib/api";
import { refreshSitePage } from "@/app/(admin)/_lib/siteCache";
import { cleanForSchema, withValidPlaceholderLinks, fieldsForDesign, pageApi, pagePath, schemaFor, statusInfo, type Content, type EditorApi, type EditorPage, type SectionState } from "@/app/(admin)/_lib/cms";
import type { PageSection } from "@/app/(site)/_lib/pageContent";
import { qk, useAllRegions, useLanguages, usePageEditor, usePagePreview } from "@/app/(admin)/_lib/queries";
import { useStore } from "@/app/(admin)/_lib/store";
import { DESIGN_FIELDS } from "@/app/(site)/_components/pages/designFields";
import { PAGE_DEFAULTS, isCmsConnected } from "@/app/(site)/_components/pages/registry";
import { Icon } from "./Icon";
import { ConfirmDialog, Modal } from "./Modal";
import { PreviewSection } from "./PreviewSection";
import { SchemaField } from "./SchemaField";
import { SitePreview, type SitePreviewHandle } from "./SitePreview";
import { PageHeader } from "./ui";

const PREVIEW_WIDTH = 1280;
type Errors = Record<string, string>;
const same = (a: unknown, b: unknown) => JSON.stringify(a ?? {}) === JSON.stringify(b ?? {});
const when = (iso: string | null) =>
  iso
    ? new Date(iso).toLocaleString(undefined, {
        dateStyle: "medium",
        timeStyle: "short",
      })
    : "";

type Props = {
  /** CMS page key: "home", "product-services", … */
  pageKey: string;
  /** Page name shown as the title. */
  name: string;
  /** Regional pages (the home page) have a version per region; the others are the same everywhere. */
  regional: boolean;
  /** Breadcrumb above the title. */
  crumb: ReactNode;
  desc?: string;
  /**
   * The rest is for pages that aren't a CMS page (a service: card + page). Defaults
   * all follow from `pageKey` for CMS pages.
   */
  /** Editor endpoints. Default: the CMS page `pageKey`. */
  api?: EditorApi;
  /** Whether the website renders this content. Default: the page is in the website's registry. */
  connected?: boolean;
  /** Website renderers for the preview (/cms-preview/<key>); null = simplified preview. Default: `pageKey` for connected inner pages. */
  previewKey?: string | null;
  /** Entry of DESIGN_FIELDS. Default: `pageKey`. */
  designKey?: string;
  /** Built-in website content, for "Import website content". Default: PAGE_DEFAULTS[pageKey]. */
  defaults?: PageSection[];
  /** Website address. Default: pagePath(pageKey). */
  sitePath?: string;
  /** Clears the website's cache after a change it shows. Default: refreshSitePage(pageKey). */
  refresh?: (accessToken: string) => Promise<boolean>;
  /** Replaces the standard notes under the language bar. */
  notes?: ReactNode;
  /** Extra buttons in the header. */
  actions?: ReactNode;
};

/**
 * Section editor for one CMS page: section list (order, visibility), the form of the
 * selected section with its workflow (draft → review → published) and a live preview.
 */
export function PageEditor({ pageKey, name, regional, crumb, desc, api: customApi, connected: connectedProp, previewKey, designKey, defaults: defaultsProp, sitePath, refresh, notes, actions }: Props) {
  const qc = useQueryClient();
  const { region: storedRegion, setRegion, toast } = useStore();
  const { data: regions, error: regionsError } = useAllRegions();
  const { data: langs } = useLanguages();
  const cms = useMemo(() => customApi ?? pageApi(pageKey, regional), [customApi, pageKey, regional]);

  // Non-regional pages are edited in Global's languages.
  const region = (regional ? regions?.find((r) => r.code === storedRegion) : undefined) ?? regions?.find((r) => r.isDefault) ?? null;
  const rc = region?.code ?? (regional ? storedRegion : "global");
  const [langPick, setLangPick] = useState<string | null>(null);
  const lang = region ? (langPick && region.languages.includes(langPick) ? langPick : region.defaultLanguage) : null;
  const langInfo = langs?.find((l) => l.code === lang);
  const langName = (c: string) => langs?.find((l) => l.code === c)?.name ?? c.toUpperCase();

  const page = usePageEditor(pageKey, cms, rc, lang);
  const preview = usePagePreview(pageKey, cms, rc, lang);
  const sections = [...(page.data?.sections ?? [])].sort((a, b) => a.order - b.order);
  const isGlobal = !regional || !!region?.isDefault;
  const connected = connectedProp ?? isCmsConnected(pageKey);
  // Inner pages the website reads from the CMS are previewed by the website itself
  // (exact design); the home page and pages not connected yet use the simplified preview.
  const frameKey = previewKey === undefined ? (connected && pageKey !== "home" ? pageKey : null) : previewKey;
  const framed = frameKey !== null;
  const defaults = defaultsProp ?? PAGE_DEFAULTS[pageKey];
  const defaultOf = (key: string) => defaults?.find((d) => d.key === key)?.content as Content | undefined;

  const [sel, setSel] = useState<string | null>(null);
  const section = sections.find((s) => s.key === sel) ?? sections[0];

  /* ---------- local edits (kept per page+region+language+section) ---------- */

  const ctxKey = (key: string) => `${pageKey}:${rc}:${lang}:${key}`;
  const [edits, setEdits] = useState<Record<string, Content>>({});
  const [errs, setErrs] = useState<Record<string, Errors>>({});
  const ck = section && lang ? ctxKey(section.key) : "";
  const base: Content = (section?.content.draft ?? section?.content.published ?? {}) as Content;
  const form: Content = edits[ck] ?? base;
  const dirty = !!edits[ck] && !same(edits[ck], base);
  const anyDirty = Object.keys(edits).length > 0;
  const locked = !!section && !isGlobal && section.inheritFromGlobal === true;
  // Saved content is cleaned against the API's full schema; the form shows only what the website's design uses.
  const allFields = section ? schemaFor(section.type) : [];
  const fields = section ? fieldsForDesign(allFields, DESIGN_FIELDS[designKey ?? pageKey]?.[section.key]) : [];

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

  const setForm = (v: Content) => setEdits((e) => ({ ...e, [ck]: v }));
  const without = <T,>(m: Record<string, T>) => Object.fromEntries(Object.entries(m).filter(([k]) => k !== ck));
  const discard = () => {
    setEdits(without);
    setErrs(without);
  };

  /* ---------- server actions ---------- */

  const [busy, setBusy] = useState<string | null>(null);

  const putSection = (s: SectionState) => qc.setQueryData<EditorPage>(qk.page(pageKey, rc, lang!), (h) => (h ? { ...h, sections: h.sections.map((x) => (x.key === s.key ? s : x)) } : h));
  const refreshPreview = () => qc.invalidateQueries({ queryKey: ["admin", "preview", pageKey] });
  /** After a change to what the website shows: clear the website's cache of this page. Never fails the change itself. */
  const refreshSite = async () => {
    const token = getAccessToken();
    if (!token) return;
    try {
      if (!(await (refresh ? refresh(token) : refreshSitePage(pageKey, token)))) console.warn(`[cms] could not refresh the website cache for "${pageKey}"`);
    } catch (e) {
      console.warn(`[cms] could not refresh the website cache for "${pageKey}":`, e);
    }
  };

  /** Save local edits (if any), then optionally run a workflow action. */
  const run = async (label: string, action?: "submit" | "publish" | "unpublish") => {
    if (!section || !lang) return;
    setBusy(label);
    try {
      let s = section;
      if (dirty && action !== "unpublish") {
        s = await cms.save(section.key, rc, lang, cleanForSchema(form, allFields));
        discard();
      }
      if (action) s = await cms.action(section.key, action, rc, lang);
      putSection(s);
      refreshPreview();
      if (action === "publish" || action === "unpublish") await refreshSite();
      toast(
        {
          "Save draft": "Draft saved",
          Submit: "Sent for review",
          Publish: "Published to the website",
          Unpublish: "Removed from the website (draft kept)",
        }[label] ?? "Saved",
      );
    } catch (e) {
      const fe = fieldErrors(e, "content.");
      setErrs((x) => ({ ...x, [ck]: fe }));
      toast(Object.keys(fe).length ? "Some fields need fixing" : errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const [rejecting, setRejecting] = useState(false);
  const [comment, setComment] = useState("");
  const reject = async () => {
    if (!section || !lang) return;
    setBusy("Reject");
    try {
      putSection(await cms.reject(section.key, rc, lang, comment.trim()));
      toast("Sent back with your comment");
      setRejecting(false);
      setComment("");
    } catch (e) {
      toast(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const [confirmAll, setConfirmAll] = useState(false);
  const doPublishAll = async () => {
    if (!lang) return;
    setBusy("Publish all");
    try {
      const r = await cms.publishAll(rc, lang);
      await qc.invalidateQueries({ queryKey: qk.page(pageKey, rc, lang) });
      refreshPreview();
      if (r.published.length) await refreshSite();
      toast(r.published.length ? `Published ${r.published.length} section${r.published.length === 1 ? "" : "s"}` : "Nothing to publish");
      setConfirmAll(false);
    } catch (e) {
      toast(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };
  const pending = sections.filter((s) => s.content.hasUnpublishedChanges && !(s.inheritFromGlobal === true && !isGlobal));

  /* ---------- import the website's built-in content into empty sections ---------- */

  const empty = sections.filter((s) => !s.content.draft && !s.content.published && !!defaultOf(s.key));
  const canImport = !!defaults && isGlobal && lang === "en" && empty.length > 0;
  const [confirmImport, setConfirmImport] = useState(false);
  const doImport = async () => {
    if (!lang) return;
    setBusy("Import");
    const failed: string[] = [];
    for (const s of empty) {
      try {
        putSection(await cms.save(s.key, rc, lang, cleanForSchema(withValidPlaceholderLinks(defaultOf(s.key)), schemaFor(s.type))));
      } catch (e) {
        failed.push(`${s.name}: ${errorMessage(e)}`);
      }
    }
    refreshPreview();
    setBusy(null);
    setConfirmImport(false);
    const done = empty.length - failed.length;
    toast(failed.length ? `Imported ${done}, ${failed.length} failed: ${failed[0]}` : `Imported ${done} section${done === 1 ? "" : "s"} as drafts. Review, then publish.`);
  };

  const [inheritAsk, setInheritAsk] = useState<boolean | null>(null);
  const doInherit = async (inherit: boolean) => {
    if (!section) return;
    setBusy("Inherit");
    try {
      await cms.setInheritance(section.key, rc, inherit);
      await qc.invalidateQueries({ queryKey: ["admin", "page", pageKey, rc] });
      qc.invalidateQueries({ queryKey: qk.regions() });
      refreshPreview();
      await refreshSite();
      toast(inherit ? "Now showing Global's content" : "Override created: Global's content copied into drafts");
      setInheritAsk(null);
    } catch (e) {
      toast(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  /* ---------- layout: order + visibility ---------- */

  const saveLayout = async (next: SectionState[]) => {
    const key = qk.page(pageKey, rc, lang!);
    const prev = qc.getQueryData<EditorPage>(key);
    qc.setQueryData<EditorPage>(key, (h) => (h ? { ...h, sections: next.map((s, i) => ({ ...s, order: i })) } : h));
    try {
      await cms.layout(
        rc,
        next.map((s) => ({ key: s.key, isVisible: s.isVisible })),
      );
      qc.invalidateQueries({
        queryKey: ["admin", "page", pageKey, rc],
        predicate: (q) => q.queryKey[4] !== lang,
      });
      refreshPreview();
      void refreshSite();
    } catch (e) {
      if (prev) qc.setQueryData(key, prev);
      toast(errorMessage(e));
    }
  };
  const move = (from: string, to: string) => {
    if (from === to) return;
    const order = sections.map((s) => s.key);
    order.splice(order.indexOf(from), 1);
    order.splice(order.indexOf(to), 0, from);
    saveLayout(order.map((k) => sections.find((s) => s.key === k)!));
    toast("Section order updated");
  };
  const toggleVisible = (key: string) => saveLayout(sections.map((s) => (s.key === key ? { ...s, isVisible: !s.isVisible } : s)));

  const [drag, setDrag] = useState<string | null>(null);
  const [over, setOver] = useState<string | null>(null);
  const onSecKey = (e: KeyboardEvent, key: string, i: number) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      select(key, true);
    } else if (e.altKey && (e.key === "ArrowUp" || e.key === "ArrowDown")) {
      e.preventDefault();
      const j = e.key === "ArrowUp" ? i - 1 : i + 1;
      if (j >= 0 && j < sections.length) move(key, sections[j].key);
    }
  };

  /* ---------- preview ---------- */

  const scrollRef = useRef<HTMLDivElement>(null);
  const pvRef = useRef<HTMLDivElement>(null);
  const frameRef = useRef<SitePreviewHandle>(null);
  const [scale, setScale] = useState(0.4);
  const [pvHeight, setPvHeight] = useState(0);
  useEffect(() => {
    const sc = scrollRef.current;
    if (!sc) return;
    const fit = () => {
      setScale(sc.clientWidth / PREVIEW_WIDTH);
      if (pvRef.current) setPvHeight(pvRef.current.offsetHeight);
    };
    const ro = new ResizeObserver(fit);
    ro.observe(sc);
    if (pvRef.current) ro.observe(pvRef.current);
    fit();
    return () => ro.disconnect();
  }, [page.isSuccess]);

  const scrollPreviewTo = (top: number) =>
    scrollRef.current?.scrollTo({
      top: Math.max(0, top * scale - 10),
      behavior: "smooth",
    });

  const select = (key: string, scroll: boolean) => {
    setSel(key);
    if (!scroll) return;
    if (framed) {
      frameRef.current?.reveal(key);
      return;
    }
    const sc = scrollRef.current;
    const el = pvRef.current?.querySelector<HTMLElement>(`section[data-s="${key}"]`);
    if (!sc || !el) return;
    sc.scrollTo({
      top: el.offsetTop * (sc.clientWidth / PREVIEW_WIDTH) - 10,
      behavior: "smooth",
    });
    el.classList.remove("flash");
    void el.offsetWidth; // restart the CSS animation
    el.classList.add("flash");
  };

  // Preview = server preview, with the section being edited shown from the unsaved form.
  const typeOf = (key: string) => sections.find((s) => s.key === key)?.type;
  const pvSections = (preview.data?.sections ?? []).map((p) => {
    const edited = lang ? edits[ctxKey(p.key)] : undefined;
    return edited ? { ...p, content: edited, dirty: true } : { ...p, dirty: false };
  });

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

  if (regionsError)
    return (
      <div className="page">
        <div className="card empty-card">{errorMessage(regionsError)}</div>
      </div>
    );

  const st = section?.content;
  const info = st ? statusInfo(st) : null;
  const canSubmit = !locked && (dirty || (st?.status === "draft" && st.hasUnpublishedChanges));
  const canPublish = !locked && (dirty || st?.status === "in_review" || (st?.status === "draft" && st.source !== "ai" && st.hasUnpublishedChanges));
  const canUnpublish = !locked && !!st?.published;
  const path = sitePath ?? pagePath(pageKey);
  const site = regional ? `unionists.com/${region?.slug ?? ""}` : `unionists.com${path}`;
  const nothingLive = connected && !regional && !!page.data && sections.every((s) => !s.content.published);
  const sectionDefault = section ? defaultOf(section.key) : undefined;

  return (
    <div className="page">
      <PageHeader crumb={regional ? `${crumb} › ${region?.name ?? "…"}` : crumb} title={name} desc={desc ?? "Edit each section per language. Changes go live only when published."}>
        {canImport && (
          <button
            type="button"
            className="btn btn-outline btn-sm"
            disabled={!!busy}
            onClick={() => setConfirmImport(true)}
            title="Copy the content the website shows today into the empty sections, as drafts"
          >
            <Icon name="file" size={14} />
            Import website content ({empty.length})
          </button>
        )}
        {actions}
        <button type="button" className="btn btn-primary btn-sm" disabled={!pending.length || !!busy} onClick={() => setConfirmAll(true)}>
          <Icon name="upload" size={14} />
          Publish all changes{pending.length ? ` (${pending.length})` : ""}
        </button>
      </PageHeader>

      <div className="card ed-bar">
        {regional && (
          <div className="grp">
            <label htmlFor="ed-region">Region</label>
            <select id="ed-region" className="select" value={rc} onChange={(e) => setRegion(e.target.value)} disabled={!regions}>
              {(regions ?? []).map((x) => (
                <option key={x.code} value={x.code}>
                  {x.name}
                  {x.isActive ? "" : " (inactive)"}
                </option>
              ))}
            </select>
          </div>
        )}
        <div className="grp">
          <label>Language</label>
          <div className="seg" role="group" aria-label="Language">
            {(region?.languages ?? []).map((l) => (
              <button key={l} type="button" className={l === lang ? "on" : ""} aria-pressed={l === lang} title={langName(l)} onClick={() => setLangPick(l)}>
                {l.toUpperCase()}
                {l === region?.defaultLanguage ? "★" : ""}
              </button>
            ))}
          </div>
        </div>
        <span className="ed-url">
          Site:{" "}
          <Link href={regional ? `/${region?.slug ?? ""}` : path} target="_blank" className="link">
            <b>{site}</b>
          </Link>{" "}
          · {lang ? langName(lang) : ""}
        </span>
      </div>

      {notes !== undefined ? (
        notes
      ) : (
        <>
          {!connected && (
            <div className="info-note" style={{ marginBottom: 16 }}>
              The website&apos;s {name} page doesn&apos;t read the CMS yet. You can prepare and publish content here; it appears on the website once the page is connected.
            </div>
          )}
          {connected && !regional && lang && lang !== "en" && (
            <div className="info-note" style={{ marginBottom: 16 }}>
              The website shows inner pages in English for now. {langName(lang)} content is saved and published here, and appears once inner pages get language versions.
            </div>
          )}

          {nothingLive && (
            <div className="info-note" style={{ marginBottom: 16 }}>
              Nothing on this page is published yet, so the website shows its built-in content. Once a section is published, the website shows only the published sections: get every section ready,
              then use <b>Publish all changes</b>.
            </div>
          )}
        </>
      )}

      {page.error ? (
        <div className="card empty-card">
          {errorMessage(page.error)}{" "}
          <button type="button" className="link" onClick={() => page.refetch()}>
            Retry
          </button>
        </div>
      ) : !page.data || !section ? (
        <div className="card empty-card">
          <span className="spin dark" /> Loading {name}…
        </div>
      ) : (
        <div className="editor">
          {/* Section list */}
          <div className="card">
            <div className="card-h">
              <div>
                <h3>Sections</h3>
                <div className="sub">
                  {sections.filter((s) => s.isVisible).length} of {sections.length} visible · drag to reorder
                </div>
              </div>
            </div>
            <div className="sec-list" role="listbox" aria-label="Sections. Alt plus arrow keys reorder.">
              {sections.map((s, i) => {
                const inf = statusInfo(s.content);
                const inherited = !isGlobal && s.inheritFromGlobal === true;
                const hasEdits = !!edits[ctxKey(s.key)];
                return (
                  <div
                    key={s.key}
                    role="option"
                    aria-selected={s.key === section.key}
                    tabIndex={0}
                    draggable
                    className={`sec${s.key === section.key ? " on" : ""}${s.isVisible ? "" : " hidden"}${drag === s.key ? " dragging" : ""}${over === s.key && drag !== s.key ? " over" : ""}`}
                    onClick={() => select(s.key, true)}
                    onKeyDown={(e) => onSecKey(e, s.key, i)}
                    onDragStart={(e) => {
                      setDrag(s.key);
                      e.dataTransfer.effectAllowed = "move";
                      e.dataTransfer.setData("text/plain", s.key);
                    }}
                    onDragEnd={() => {
                      setDrag(null);
                      setOver(null);
                    }}
                    onDragOver={(e) => {
                      if (!drag) return;
                      e.preventDefault();
                      if (over !== s.key) setOver(s.key);
                    }}
                    onDragLeave={() => setOver((o) => (o === s.key ? null : o))}
                    onDrop={(e) => {
                      e.preventDefault();
                      if (drag) move(drag, s.key);
                      setDrag(null);
                      setOver(null);
                    }}
                  >
                    <span className="grip">
                      <Icon name="grip" size={16} />
                    </span>
                    <span className="num">{i + 1}</span>
                    <div className="nm">
                      <b>
                        {s.name}
                        {hasEdits && <span className="edit-dot" title="Unsaved edits" />}
                      </b>
                      <span className="sec-tags">
                        {inherited ? <span className="tag n">Inherited</span> : <span className={`tag ${inf.tone}`}>{inf.label}</span>}
                        {!isGlobal && !inherited && <span className="tag b">Override</span>}
                        {s.content.source === "ai" && <span className="tag a">AI</span>}
                      </span>
                    </div>
                    <button
                      type="button"
                      className="vis"
                      title={s.isVisible ? "Hide on the website" : "Show on the website"}
                      aria-label={`${s.isVisible ? "Hide" : "Show"} ${s.name}`}
                      onClick={(e) => {
                        e.stopPropagation();
                        toggleVisible(s.key);
                      }}
                    >
                      <Icon name={s.isVisible ? "eye" : "eyeoff"} size={16} />
                    </button>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Form */}
          <div className="card form-panel">
            <div className="card-h">
              <div>
                <h3>{section.name}</h3>
                <div className="sub">
                  {info && <span className={`tag ${info.tone}`}>{info.label}</span>} {st?.updatedAt && `Saved ${when(st.updatedAt)}${st.updatedBy ? ` by ${st.updatedBy.email}` : ""}`}
                </div>
              </div>
            </div>
            <div className="card-b">
              {!isGlobal && section.inheritFromGlobal !== null && (
                <div className="inherit-box">
                  <label className="toggle">
                    <input type="checkbox" aria-label="Inherit from Global" checked={section.inheritFromGlobal} disabled={busy === "Inherit"} onChange={(e) => setInheritAsk(e.target.checked)} />
                    <span />
                  </label>
                  <div>
                    <b>Inherit from Global</b>
                    <span>
                      {section.inheritFromGlobal
                        ? `${region?.name} shows Global's ${section.name}. Turn off to write a ${region?.name} version.`
                        : `${region?.name} has its own version. Turn on to show Global's again (this version is kept).`}
                    </span>
                  </div>
                </div>
              )}

              {st?.reviewComment && st.status === "draft" && (
                <div className="review-note" role="note">
                  <b>Changes requested</b>
                  <span>{st.reviewComment}</span>
                </div>
              )}
              {st?.status === "in_review" && (
                <div className="info-note">
                  Waiting for review
                  {st.submittedAt ? ` since ${when(st.submittedAt)}` : ""}. Publish to approve, or reject with a comment.
                </div>
              )}
              {!st?.status && !locked && (
                <div className="info-note">
                  Nothing is written in {lang ? langName(lang) : "this language"} yet.{" "}
                  {regional ? "The website falls back to the region's default language, then English." : "The website falls back to English."}
                  {sectionDefault && !edits[ck] && (
                    <>
                      {" "}
                      <button type="button" className="link" onClick={() => setForm(sectionDefault)}>
                        Start from the website&apos;s current content
                      </button>
                    </>
                  )}
                </div>
              )}
              {fields.length === 0 && <div className="info-note">This panel has no form for “{section.type}” sections yet.</div>}

              <fieldset disabled={locked} className={locked ? "locked" : ""} style={{ border: 0, minWidth: 0 }}>
                <legend className="sr-only">{section.name} fields</legend>
                {fields.map((f) => (
                  <SchemaField key={f.key} field={f} value={form[f.key]} onChange={(v) => setForm({ ...form, [f.key]: v })} errors={errs[ck] ?? {}} path={f.key} disabled={locked} />
                ))}
              </fieldset>
            </div>
            {!locked && (
              <div className="ed-actions">
                {dirty && (
                  <button type="button" className="btn-plain" onClick={discard}>
                    Discard
                  </button>
                )}
                <button type="button" className="btn btn-outline btn-sm" disabled={!dirty || !!busy} onClick={() => run("Save draft")}>
                  {busy === "Save draft" ? <span className="spin dark" /> : "Save draft"}
                </button>
                <button type="button" className="btn btn-outline btn-sm" disabled={!canSubmit || !!busy} onClick={() => run("Submit", "submit")} title="Send for review">
                  {busy === "Submit" ? <span className="spin dark" /> : "Submit"}
                </button>
                {st?.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" /> : st?.status === "in_review" && !dirty ? "Approve & publish" : dirty ? "Save & publish" : "Publish"}
                </button>
                {canUnpublish && (
                  <button type="button" className="btn-plain danger" disabled={!!busy} onClick={() => run("Unpublish", "unpublish")}>
                    Unpublish
                  </button>
                )}
              </div>
            )}
          </div>

          {/* Live preview */}
          <div className="card pv-card">
            <div className="pv-chrome">
              <i />
              <i />
              <i />
              <div className="pv-url">
                {site} · {lang ? langName(lang) : ""} · preview (drafts)
                {preview.isFetching ? " · updating…" : ""}
              </div>
            </div>
            <div className="pv-scroll" ref={scrollRef}>
              {frameKey !== null && !preview.error && pvSections.length > 0 ? (
                <SitePreview
                  ref={frameRef}
                  pageKey={frameKey}
                  sections={pvSections.map((p) => ({
                    key: p.key,
                    content: p.content,
                    dirty: p.dirty,
                  }))}
                  selected={section.key}
                  lang={langInfo?.bcp47 ?? lang ?? undefined}
                  dir={langInfo?.dir ?? (lang === "ar" ? "rtl" : "ltr")}
                  scale={scale}
                  width={PREVIEW_WIDTH}
                  onSelect={(key) => select(key, false)}
                  onScrollTo={scrollPreviewTo}
                />
              ) : (
                <div className="pv-stage" style={{ height: pvHeight * scale }}>
                  <div className="pv" ref={pvRef} dir={langInfo?.dir ?? (lang === "ar" ? "rtl" : "ltr")} lang={langInfo?.bcp47 ?? lang ?? undefined} style={{ transform: `scale(${scale})` }}>
                    {preview.error ? (
                      <div className="pv-empty">{errorMessage(preview.error)}</div>
                    ) : pvSections.length === 0 ? (
                      <div className="pv-empty">{preview.isPending ? "Loading preview…" : "Nothing to show: every section is hidden or empty."}</div>
                    ) : (
                      pvSections.map((p) => (
                        <PreviewSection
                          key={p.key}
                          sectionKey={p.key}
                          type={typeOf(p.key) ?? p.type}
                          content={p.content}
                          dirty={p.dirty}
                          selected={p.key === section.key}
                          onSelect={() => select(p.key, false)}
                        />
                      ))
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {rejecting && (
        <Modal title={`Reject ${section?.name}`} onClose={() => setRejecting(false)}>
          <div className="field">
            <label htmlFor="rj-comment">What needs to change? The editor sees this.</label>
            <textarea id="rj-comment" 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>
      )}

      {confirmAll && (
        <ConfirmDialog title="Publish all changes?" confirmLabel={`Publish ${pending.length}`} busy={busy === "Publish all"} onConfirm={doPublishAll} onClose={() => setConfirmAll(false)}>
          Every section with unpublished changes in {regional ? `${region?.name} · ` : ""}
          {lang ? langName(lang) : ""} goes live now: <b>{pending.map((s) => s.name).join(", ")}</b>. Unsaved edits in the form are not included.
          {connected && !regional && sections.some((s) => !s.content.published && !pending.includes(s)) && (
            <> Sections that are still empty won&apos;t appear on the website once anything on this page is published.</>
          )}
        </ConfirmDialog>
      )}

      {confirmImport && (
        <ConfirmDialog title="Import website content?" confirmLabel={`Import ${empty.length}`} busy={busy === "Import"} onConfirm={doImport} onClose={() => setConfirmImport(false)}>
          The content the website shows today is saved as drafts in these empty sections: <b>{empty.map((s) => s.name).join(", ")}</b>. Nothing goes live until you publish.
        </ConfirmDialog>
      )}

      {inheritAsk !== null && section && (
        <ConfirmDialog
          title={inheritAsk ? `Show Global's ${section.name}?` : `Override ${section.name} for ${region?.name}?`}
          confirmLabel={inheritAsk ? "Inherit from Global" : "Create override"}
          busy={busy === "Inherit"}
          onConfirm={() => doInherit(inheritAsk)}
          onClose={() => setInheritAsk(null)}
        >
          {inheritAsk
            ? `${region?.name}'s own version is kept but the website shows Global's content again.`
            : `The first time, Global's content is copied into unpublished drafts for every ${region?.name} language. The website keeps showing Global until you publish.`}
        </ConfirmDialog>
      )}
    </div>
  );
}
