import { api } from "./api";
import { MEDIA_ORIGIN } from "./media";

/* ------------------------------------------------------------------ */
/* Content types (see the API's "Section types" reference)             */
/* ------------------------------------------------------------------ */

export type RichTitle = { text: string; highlight?: string };
export type Cta = { label: string; href: string; openInNewTab?: boolean };
export type Img = { url: string; alt?: string };
export type Background = { type: "image" | "video"; url: string; posterUrl?: string; alt?: string };

export type SectionType =
  | "hero"
  | "page-hero"
  | "stats"
  | "feature-cards"
  | "cards-image"
  | "text-image"
  | "text-image-list"
  | "comparison-table"
  | "map-highlights"
  | "award-list"
  | "quote-cards"
  | "testimonial-cards"
  | "case-study-list"
  | "category-list"
  | "image-cards"
  | "roadmap-phases"
  | "article-listing"
  | "text-featured"
  | "listing-preview"
  | "office-list"
  | "office-map"
  | "map-embed"
  | "product-catalog"
  | "logo-grid"
  | "cta-banner"
  | "cta-image"
  | "cta-buttons"
  | "case-study"
  | "contact"
  | "footer"
  | "process-steps"
  | "service-card"
  | "service-listing";

/** Section content is validated by the API; on the client it's a loose JSON object. */
export type Content = Record<string, unknown>;

export type Status = "draft" | "in_review" | "published" | null;
type Who = { id: string; email: string } | null;

export type SectionState = {
  key: string;
  type: SectionType;
  name: string;
  order: number;
  isVisible: boolean;
  /** null on Global and on pages without regional versions. */
  inheritFromGlobal: boolean | null;
  content: {
    status: Status;
    source: "manual" | "ai" | null;
    draft: Content | null;
    published: Content | null;
    hasUnpublishedChanges: boolean;
    reviewComment: string | null;
    updatedBy: Who;
    updatedAt: string | null;
    submittedAt: string | null;
    publishedBy: Who;
    publishedAt: string | null;
  };
};

/** GET /admin/pages/:key — one page in one language (and region, for regional pages). */
export type EditorPage = {
  page?: { key: string; name: string; regional: boolean };
  region: { code: string; name: string; isDefault: boolean };
  language: string;
  sections: SectionState[];
};
export type PreviewSection = { key: string; type: SectionType; language: string; content: Content };
export type Preview = { region?: { code: string; name: string }; language: string | { code: string }; sections: PreviewSection[] };

/** GET /admin/pages — every CMS page and its sections. */
export type PageInfo = { key: string; name: string; regional: boolean; sections: { key: string; type: SectionType; name: string }[] };

/* ------------------------------------------------------------------ */
/* Endpoints (/admin/pages/:key/…)                                     */
/* ------------------------------------------------------------------ */

/** The section editor endpoints of one editable page (a CMS page or a service page). */
export type EditorApi = {
  get: (region: string, lang: string) => Promise<EditorPage>;
  preview: (region: string, lang: string) => Promise<Preview>;
  save: (key: string, region: string, lang: string, content: Content) => Promise<SectionState>;
  action: (key: string, action: "submit" | "publish" | "unpublish", region: string, lang: string) => Promise<SectionState>;
  reject: (key: string, region: string, lang: string, comment: string) => Promise<SectionState>;
  publishAll: (region: string, lang: string) => Promise<{ published: string[] }>;
  setInheritance: (key: string, region: string, inheritFromGlobal: boolean) => Promise<SectionState>;
  layout: (region: string, sections: { key: string; isVisible: boolean }[]) => Promise<EditorPage>;
};

/**
 * Editor endpoints under `base` that share the pages' shape (sections/:key/…, publish,
 * layout, preview). `getPath` is where the editor data is read: the page itself for
 * CMS pages, `<base>/page` for a service.
 */
function sectionEditorApi(base: string, getPath: string, regional: boolean): EditorApi {
  const q = (region: string, lang?: string) => ({ ...(regional ? { region } : {}), ...(lang ? { lang } : {}) });
  return {
    get: (region, lang) => api<EditorPage>(getPath, { query: q(region, lang) }),
    preview: (region, lang) => api<Preview>(`${base}/preview`, { query: q(region, lang) }),
    save: (key, region, lang, content) => api<SectionState>(`${base}/sections/${key}/content`, { method: "PUT", query: q(region, lang), body: { content } }),
    action: (key, action, region, lang) => api<SectionState>(`${base}/sections/${key}/${action}`, { method: "POST", query: q(region, lang) }),
    reject: (key, region, lang, comment) => api<SectionState>(`${base}/sections/${key}/reject`, { method: "POST", query: q(region, lang), body: { comment } }),
    publishAll: (region, lang) => api<{ published: string[] }>(`${base}/publish`, { method: "POST", query: q(region, lang) }),
    setInheritance: (key, region, inheritFromGlobal) =>
      regional
        ? api<SectionState>(`${base}/sections/${key}/inheritance`, { method: "PATCH", query: q(region), body: { inheritFromGlobal } })
        : Promise.reject(new Error("This page has no regional versions")),
    layout: (region, sections) => api<EditorPage>(`${base}/layout`, { method: "PUT", query: q(region), body: { sections } }),
  };
}

/**
 * The editor endpoints of one CMS page. `region` is sent only for regional pages
 * (the home page): the other pages are the same everywhere and reject it.
 */
export function pageApi(pageKey: string, regional: boolean): EditorApi {
  const base = `/admin/pages/${encodeURIComponent(pageKey)}`;
  return sectionEditorApi(base, base, regional);
}

/** The editor endpoints of one service's card and page (/admin/services/:id/…). Services are the same in every region. */
export function serviceEditorApi(serviceId: string): EditorApi {
  const base = `/admin/services/${encodeURIComponent(serviceId)}`;
  return sectionEditorApi(base, `${base}/page`, false);
}

export const listPages = () => api<PageInfo[]>("/admin/pages");

/**
 * Keys of the inner CMS pages (API reference, "Section types"). The list is fixed by the
 * API; the editor route is prerendered for each one. A page the API adds later needs
 * its key here.
 */
export const INNER_PAGE_KEYS = [
  "about", "partners", "why-choose-us", "careers", "global-strategy", "awards", "testimonials", "partner-with-us",
  "product-services", "global-agriculture", "services", "industries-we-serve", "sustainability-esg", "social-responsibility",
  "roadmap", "thought-leadership-articles", "ai-innovation-lab", "media-insights", "unionists-magazine", "global-presence",
  "donations", "contact",
] as const;

/** Website path of a CMS page: the home page is /, the others use their key (/about, /services, …). */
export const pagePath = (pageKey: string) => (pageKey === "home" ? "/" : `/${pageKey}`);

/* ------------------------------------------------------------------ */
/* Form schema per content type                                        */
/* ------------------------------------------------------------------ */

export type Field =
  | { kind: "richTitle"; key: string; label: string; required?: boolean }
  | { kind: "text"; key: string; label: string; max: number; required?: boolean; multiline?: boolean; inputType?: "email" | "tel" | "text"; placeholder?: string; hint?: string }
  | { kind: "number"; key: string; label: string; min: number; max: number; integer?: boolean; required?: boolean; placeholder?: string }
  | { kind: "boolean"; key: string; label: string }
  | { kind: "link"; key: string; label: string; required?: boolean }
  | { kind: "select"; key: string; label: string; options: { value: string; label: string }[] }
  | { kind: "image"; key: string; label: string; required?: boolean }
  | { kind: "background"; key: string; label: string }
  | { kind: "cta"; key: string; label: string; required?: boolean }
  /** An object with its own fields (e.g. a featured card). Optional groups left empty are not sent. */
  | { kind: "group"; key: string; label: string; fields: Field[]; required?: boolean }
  /**
   * A repeatable list. `optional`: the API accepts the field missing but not an empty
   * list (e.g. "1-8 items, optional"), so an empty list is left out when saving.
   */
  | { kind: "list"; key: string; label: string; itemLabel: string; min: number; max: number; item: "cta" | { string: number } | Field[]; optional?: boolean };

const title = (required = true): Field => ({ kind: "richTitle", key: "title", label: "Title", required });
const ctas = (max = 3, label = "Buttons", min = 0): Field => ({ kind: "list", key: "ctas", label, itemLabel: "Button", min, max, item: "cta" });
const body = (max: number, required = false, label = "Body"): Field => ({ kind: "text", key: "body", label, max, required, multiline: true });
const intro = (max = 1000) => body(max, false, "Intro text");
const text = (key: string, label: string, max: number, extra: Partial<Extract<Field, { kind: "text" }>> = {}): Field => ({ kind: "text", key, label, max, ...extra });
const image = (key = "image", label = "Image", required = true): Field => ({ kind: "image", key, label, required });
const position: Field = { kind: "select", key: "imagePosition", label: "Image position", options: [{ value: "left", label: "Left of the text" }, { value: "right", label: "Right of the text" }] };
const strings = (key: string, label: string, itemLabel: string, min: number, max: number, each: number, optional = false): Field => ({ kind: "list", key, label, itemLabel, min, max, item: { string: each }, optional });
const optionalCta = (label = "Button (optional)"): Field => ({ kind: "cta", key: "cta", label });

/** Fields of a feature-cards item (also used for text-image "features"). */
const featureItem = (full: boolean): Field[] => [
  text("title", "Title", 120, { required: true }),
  text("description", "Description", 300, { multiline: true }),
  ...(full
    ? ([
        strings("bullets", "Bullet points", "Bullet", 0, 8, 200, true),
        { kind: "boolean", key: "numbered", label: "Show the bullet points as numbered steps" },
        {
          kind: "list", key: "details", label: "Labelled lines", itemLabel: "Line", min: 0, max: 4, optional: true,
          item: [text("label", "Label", 40, { required: true, placeholder: "Goal:" }), text("text", "Text", 300, { required: true })],
        },
      ] as Field[])
    : []),
  image("icon", "Icon", false),
];

export const SCHEMAS: Record<SectionType, Field[]> = {
  hero: [
    title(),
    text("subtitle", "Subtitle", 500, { multiline: true }),
    { kind: "background", key: "background", label: "Background" },
    ctas(),
  ],
  "page-hero": [text("title", "Page heading", 200, { required: true }), text("breadcrumb", "Breadcrumb (last item)", 60, { required: true, hint: 'Shown as "Home > …".' })],
  stats: [
    {
      kind: "list", key: "items", label: "Figures", itemLabel: "Figure", min: 1, max: 8,
      item: [text("value", "Value", 20, { required: true, placeholder: "€150B+" }), text("label", "Label", 120), image("icon", "Icon", false)],
    },
  ],
  "feature-cards": [
    title(false),
    intro(),
    { kind: "list", key: "items", label: "Cards", itemLabel: "Card", min: 1, max: 12, item: featureItem(true) },
    ctas(),
  ],
  "cards-image": [
    title(),
    intro(),
    { kind: "list", key: "items", label: "Text cards (half before the image, half after)", itemLabel: "Card", min: 2, max: 8, item: [text("title", "Title", 120, { required: true }), text("description", "Description", 500, { required: true, multiline: true })] },
    image(),
  ],
  "text-image": [
    title(),
    text("lead", "Lead line (emphasised, under the title)", 500, { multiline: true }),
    body(3000, true),
    { kind: "list", key: "stats", label: "Figures under the text", itemLabel: "Figure", min: 0, max: 6, optional: true, item: [text("label", "Label", 60, { required: true, placeholder: "600+ Hubs" }), image("icon", "Icon", false)] },
    { kind: "list", key: "features", label: "Points under the text", itemLabel: "Point", min: 0, max: 6, optional: true, item: featureItem(false) },
    { ...(ctas() as Extract<Field, { kind: "list" }>), optional: true },
    image(),
    position,
  ],
  "text-image-list": [
    title(),
    body(3000, false, "Intro text"),
    strings("bullets", "List", "Item", 1, 10, 300),
    text("note", "Closing line (emphasised)", 500, { multiline: true }),
    { ...(ctas() as Extract<Field, { kind: "list" }>), optional: true },
    image(),
    position,
  ],
  "comparison-table": [
    title(),
    intro(),
    strings("columns", "Column headings (the first heads the row labels)", "Column", 2, 5, 80),
    { kind: "list", key: "rows", label: "Rows", itemLabel: "Row", min: 1, max: 15, item: [strings("cells", "Cells (first = row label, one per column)", "Cell", 2, 5, 300)] },
  ],
  "map-highlights": [
    title(),
    intro(),
    image("image", "Map picture"),
    {
      kind: "list", key: "items", label: "Cards on the map (each area once)", itemLabel: "Card", min: 1, max: 4,
      item: [
        { kind: "select", key: "area", label: "Area", options: [{ value: "americas", label: "Americas" }, { value: "europe", label: "Europe" }, { value: "middle-east-africa", label: "Middle East & Africa" }, { value: "asia-pacific", label: "Asia-Pacific" }] },
        text("title", "Title", 120, { required: true }),
        text("description", "Description", 300, { required: true, multiline: true }),
      ],
    },
  ],
  "award-list": [
    title(),
    intro(),
    {
      kind: "list", key: "items", label: "Awards", itemLabel: "Award", min: 1, max: 30,
      item: [text("year", "Year", 20, { required: true, placeholder: "2024–2025" }), text("title", "Title", 160, { required: true }), text("badge", "Badge (next to the year)", 40, { placeholder: "Nominations" }), text("description", "Description", 500, { multiline: true }), image("image", "Laurel picture", false)],
    },
  ],
  "quote-cards": [
    title(),
    intro(),
    { kind: "list", key: "items", label: "Quotes", itemLabel: "Quote", min: 1, max: 12, item: [text("quote", "Quote", 600, { required: true, multiline: true }), text("source", "Source (the website adds the dash)", 120, { required: true })] },
  ],
  "testimonial-cards": [
    title(),
    intro(),
    {
      kind: "list", key: "items", label: "Reviews", itemLabel: "Review", min: 1, max: 12,
      item: [text("quote", "Quote", 600, { required: true, multiline: true }), text("name", "Name", 120, { required: true }), text("role", "Role", 160, { placeholder: "Director at Acme" }), { kind: "number", key: "rating", label: "Stars (1-5, empty to hide)", min: 1, max: 5, integer: true }],
    },
    ctas(),
  ],
  "case-study-list": [
    title(),
    intro(),
    {
      kind: "list", key: "items", label: "Case studies (image side alternates)", itemLabel: "Case study", min: 1, max: 10,
      item: [text("title", "Title", 200, { required: true }), body(3000, true), strings("bullets", "Bullet points", "Bullet", 0, 10, 300), image(), optionalCta()],
    },
    ctas(3, "Buttons under the list"),
  ],
  "category-list": [
    title(),
    intro(),
    {
      kind: "list", key: "items", label: "Categories (image side and background alternate)", itemLabel: "Category", min: 1, max: 10,
      item: [
        text("title", "Title", 160, { required: true }),
        { kind: "list", key: "entries", label: "Entries", itemLabel: "Entry", min: 1, max: 20, item: [text("label", "Label (bold)", 120, { required: true }), text("detail", "Detail (in brackets)", 300)] },
        image(),
        optionalCta(),
      ],
    },
  ],
  "image-cards": [
    title(),
    intro(),
    {
      kind: "list", key: "items", label: "Cards", itemLabel: "Card", min: 1, max: 12,
      item: [image(), text("label", "Small label above the title", 60), text("title", "Title", 160, { required: true }), text("description", "Description", 500, { multiline: true }), optionalCta()],
    },
  ],
  "roadmap-phases": [
    title(),
    intro(),
    {
      kind: "list", key: "items", label: "Phases", itemLabel: "Phase", min: 1, max: 8,
      item: [
        text("label", "Label", 40, { required: true, placeholder: "Phase 1" }),
        text("period", "Period", 60, { required: true, placeholder: "2025-2026 (Current phase)" }),
        text("title", "Title", 160, { required: true }),
        text("subtitle", "Subtitle", 300, { multiline: true }),
        { kind: "list", key: "points", label: "Points", itemLabel: "Point", min: 1, max: 10, item: [text("title", "Title (bold)", 120, { required: true }), text("description", "Description", 300, { multiline: true })] },
        image(),
      ],
    },
  ],
  "article-listing": [
    text("heading", "Heading (for screen readers and SEO)", 120, { required: true }),
    text("allFilterLabel", "First filter tab (all categories)", 40, { required: true }),
    text("noResultsText", "Text when a category has no articles", 200),
  ],
  "text-featured": [
    title(),
    body(3000, true),
    {
      kind: "group", key: "featured", label: "Featured card (leave empty to hide)",
      fields: [image(), text("label", "Label", 60, { placeholder: "Featured Article" }), text("title", "Title", 160, { required: true }), text("description", "Description", 500, { multiline: true }), optionalCta()],
    },
  ],
  "listing-preview": [
    title(),
    body(1000),
    { kind: "number", key: "count", label: "How many of the latest items to show", min: 1, max: 12, integer: true, required: true },
    optionalCta("Button (e.g. View All, optional)"),
    text("noResultsText", "Text when there are no items yet", 200),
  ],
  "office-list": [
    title(),
    intro(),
    {
      kind: "list", key: "items", label: "Offices", itemLabel: "Office", min: 1, max: 30,
      item: [
        text("location", "Location", 120, { required: true, placeholder: "Amsterdam, Netherlands" }),
        text("name", "Name", 120, { required: true, placeholder: "Global Headquarters" }),
        text("description", "Description", 200, { multiline: true }),
        { kind: "group", key: "position", label: "Map pin (optional)", fields: [{ kind: "number", key: "lat", label: "Latitude", min: -90, max: 90 }, { kind: "number", key: "lng", label: "Longitude", min: -180, max: 180 }] },
      ],
    },
  ],
  "office-map": [title(), intro()],
  "map-embed": [text("label", "Map name (for screen readers)", 160, { required: true }), text("embedUrl", "Embed URL (Google Maps or OpenStreetMap)", 2000, { required: true, placeholder: "https://www.google.com/maps/embed?…" })],
  "product-catalog": [
    text("searchPlaceholder", "Search placeholder", 60, { required: true }),
    text("filtersLabel", "Filters button (small screens)", 40, { required: true }),
    {
      kind: "group", key: "filterHeadings", label: "Filter headings", required: true,
      fields: [text("category", "Category", 60, { required: true }), text("originCountry", "Origin country", 60, { required: true }), text("productType", "Product type", 60, { required: true }), text("volume", "Volume", 60, { required: true }), text("certifications", "Certifications", 60, { required: true })],
    },
    { kind: "group", key: "productTypeLabels", label: "Product type options", required: true, fields: [text("all", "All", 40, { required: true }), text("organic", "Organic", 40, { required: true }), text("conventional", "Conventional", 40, { required: true })] },
    {
      kind: "group", key: "volumeLabels", label: "Volume options (metric tonnes)", required: true,
      fields: [text("upTo10", "Up to 10", 40, { required: true }), text("from10To50", "10 to 50", 40, { required: true }), text("from50To100", "50 to 100", 40, { required: true }), text("from100To500", "100 to 500", 40, { required: true }), text("over500", "Over 500", 40, { required: true })],
    },
    text("seeMoreLabel", '"See more" link', 40, { required: true }),
    text("noResultsText", "Text when no product matches", 200),
  ],
  "logo-grid": [
    title(),
    intro(),
    { kind: "list", key: "logos", label: "Logos", itemLabel: "Logo", min: 0, max: 50, item: [image("image", "Logo image"), text("name", "Name", 120, { required: true }), { kind: "link", key: "href", label: "Link" }] },
  ],
  "cta-banner": [title(), body(1000), { kind: "cta", key: "cta", label: "Button", required: true }],
  "cta-image": [title(), body(1000), ctas(3, "Buttons", 1), image(), position],
  "cta-buttons": [title(), body(1000), ctas(3, "Buttons", 1)],
  "case-study": [title(), body(3000, true), strings("bullets", "Bullet points", "Bullet", 0, 10, 300), image(), ctas()],
  contact: [
    title(),
    body(1000, false, "Intro"),
    text("phone", "Phone", 40, { inputType: "tel" }),
    text("email", "Email", 254, { inputType: "email" }),
    { kind: "list", key: "emails", label: "Labelled emails (shown instead of Email)", itemLabel: "Email", min: 0, max: 8, optional: true, item: [text("label", "Label", 80, { required: true, placeholder: "Media & PR" }), text("email", "Email", 254, { required: true, inputType: "email" })] },
    text("address", "Address", 300, { multiline: true }),
    { kind: "link", key: "mapUrl", label: "Map link" },
    text("formTitle", "Form title", 120),
    {
      kind: "list", key: "inquiryTypes", label: "Inquiry types (form dropdown; empty hides it)", itemLabel: "Option", min: 0, max: 12, optional: true,
      item: [
        text("key", "Key (sent with the form)", 40, { required: true, placeholder: "general", hint: "Lowercase letters, digits and hyphens. Keep it the same in every language; the label is what visitors see." }),
        text("label", "Label", 80, { required: true, placeholder: "General Inquiry" }),
      ],
    },
    strings("meetingDateOptions", "Meeting date options (empty hides the dropdown)", "Option", 0, 12, 60, true),
    strings("meetingTimeOptions", "Meeting time options (empty hides the dropdown)", "Option", 0, 24, 20, true),
    text("submitLabel", "Submit button label", 60, { required: true }),
    ctas(),
  ],
  footer: [
    text("description", "Description", 1000, { multiline: true }),
    {
      kind: "list", key: "linkGroups", label: "Link groups", itemLabel: "Group", min: 0, max: 6,
      item: [text("title", "Group title", 60, { required: true }), { kind: "list", key: "links", label: "Links", itemLabel: "Link", min: 1, max: 12, item: "cta" }],
    },
    { kind: "list", key: "socialLinks", label: "Social links", itemLabel: "Social link", min: 0, max: 12, item: "cta" },
    text("copyright", "Copyright", 200),
  ],
  "process-steps": [
    title(),
    intro(),
    {
      kind: "list", key: "items", label: "Steps on the timeline", itemLabel: "Step", min: 2, max: 8,
      item: [text("label", "Label", 40, { required: true, placeholder: "Step 1" }), text("title", "Title", 120, { required: true }), text("description", "Description", 500, { multiline: true })],
    },
  ],
  "service-card": [
    image(),
    text("title", "Title", 160, { required: true }),
    text("description", "Description", 500, { multiline: true }),
    text("ctaLabel", "Button text", 40, { required: true, placeholder: "Read More" }),
    { kind: "link", key: "href", label: "Button link (leave empty to open the service's own page)" },
  ],
  // The cards under a division come from the Services folder: the API adds them as `services`.
  "service-listing": [title(), body(1000)],
};

/** Form fields of a section type (an empty form for a type this panel doesn't know yet). */
export const schemaFor = (type: string): Field[] => SCHEMAS[type as SectionType] ?? [];

/**
 * The fields of a schema that the section's website design shows (see DESIGN_FIELDS):
 * "items" keeps the whole field, "items.title" keeps one field of a list's items or a
 * group. Without a list, every field is kept.
 */
export function fieldsForDesign(fields: Field[], used: string[] | undefined): Field[] {
  if (!used) return fields;
  const out: Field[] = [];
  for (const f of fields) {
    if (used.includes(f.key)) {
      out.push(f);
      continue;
    }
    const sub = used.filter((u) => u.startsWith(`${f.key}.`)).map((u) => u.slice(f.key.length + 1));
    if (!sub.length) continue;
    if (f.kind === "list" && Array.isArray(f.item)) out.push({ ...f, item: fieldsForDesign(f.item, sub) });
    else if (f.kind === "group") out.push({ ...f, fields: fieldsForDesign(f.fields, sub) });
    else out.push(f);
  }
  return out;
}

/** Empty value for a new list item. */
export function emptyItem(item: Extract<Field, { kind: "list" }>["item"]): unknown {
  if (item === "cta") return { label: "", href: "" };
  if (!Array.isArray(item)) return "";
  const o: Record<string, unknown> = {};
  for (const f of item) if (f.kind === "list") o[f.key] = f.min > 0 ? Array.from({ length: f.min }, () => emptyItem(f.item)) : [];
  return o;
}

/**
 * Prepare form state for the API: trim strings and drop empty optional values
 * (the API rejects e.g. `phone: ""` or `highlight: ""`, which must be 1+ chars).
 * Required-but-empty values also disappear, so the API reports them as missing.
 */
export function cleanContent(v: unknown): unknown {
  if (typeof v === "string") return v.trim() === "" ? undefined : v.trim();
  if (Array.isArray(v)) return v.map(cleanContent).filter((x) => x !== undefined);
  if (v && typeof v === "object") {
    const out: Record<string, unknown> = {};
    for (const [k, x] of Object.entries(v)) {
      const c = cleanContent(x);
      if (c !== undefined) out[k] = c;
    }
    // An image/cta/title object with nothing left in it is "not set".
    const keys = Object.keys(out);
    if (keys.length === 0 || (keys.length === 1 && keys[0] === "openInNewTab") || (keys.length === 1 && keys[0] === "type")) return undefined;
    return out;
  }
  if (typeof v === "number" && Number.isNaN(v)) return undefined;
  return v === null ? undefined : v;
}

/**
 * The website's built-in content uses "#" for links with no destination yet, which the
 * API rejects (it accepts only named anchors). "#top" behaves the same in a browser
 * (scrolls to the top of the page), so imports send that instead.
 */
export function withValidPlaceholderLinks<T>(v: T): T {
  if (Array.isArray(v)) return v.map(withValidPlaceholderLinks) as T;
  if (v && typeof v === "object")
    return Object.fromEntries(
      Object.entries(v).map(([k, x]) => [k, (k === "href" || k === "mapUrl") && x === "#" ? "#top" : withValidPlaceholderLinks(x)]),
    ) as T;
  return v;
}

/**
 * cleanContent, then apply what the form shows but the state may not hold yet:
 * - a select left untouched saves its first option (the one displayed);
 * - optional lists that ended up empty are left out (see Field "list" `optional`).
 */
export function cleanForSchema(v: unknown, fields: Field[]): Content {
  return finalize((cleanContent(v) ?? {}) as Content, fields);
}

function finalize(o: Record<string, unknown>, fields: Field[]): Record<string, unknown> {
  // The API rejects fields the type doesn't have (e.g. the `services` a service-listing
  // section carries on the website). Without a schema, keep everything.
  const known = new Set(fields.map((f) => f.key));
  const out = fields.length ? Object.fromEntries(Object.entries(o).filter(([k]) => known.has(k))) : { ...o };
  for (const f of fields) {
    const x = out[f.key];
    if (f.kind === "select" && x === undefined) out[f.key] = f.options[0].value;
    else if (f.kind === "list") {
      if (!Array.isArray(x)) continue;
      if (x.length === 0 && f.optional) delete out[f.key];
      else if (Array.isArray(f.item)) {
        const sub = f.item;
        out[f.key] = x.map((it) => (it && typeof it === "object" ? finalize(it as Record<string, unknown>, sub) : it));
      }
    } else if (f.kind === "group" && x && typeof x === "object") {
      out[f.key] = finalize(x as Record<string, unknown>, f.fields);
    }
  }
  return out;
}

/* ------------------------------------------------------------------ */
/* Paths                                                               */
/* ------------------------------------------------------------------ */

export type Path = (string | number)[];

export function getAt(obj: unknown, path: Path): unknown {
  let o = obj;
  for (const p of path) {
    if (o == null || typeof o !== "object") return undefined;
    o = (o as Record<string | number, unknown>)[p];
  }
  return o;
}

/** Immutable set: returns a copy of `obj` with `value` at `path`, creating containers as needed. */
export function setAt<T>(obj: T, path: Path, value: unknown): T {
  if (path.length === 0) return value as T;
  const [head, ...rest] = path;
  const base = (obj ?? (typeof head === "number" ? [] : {})) as Record<string | number, unknown> | unknown[];
  const copy = (Array.isArray(base) ? [...base] : { ...base }) as Record<string | number, unknown>;
  copy[head] = setAt(copy[head], rest, value);
  return copy as T;
}

/* ------------------------------------------------------------------ */
/* Media                                                               */
/* ------------------------------------------------------------------ */

const SITE = (process.env.NEXT_PUBLIC_SITE_URL ?? "").replace(/\/+$/, "");

/**
 * Absolute URL for displaying an image in the admin, or null when it can't be shown.
 * /uploads/… lives on the media host (the API); other relative paths are website assets.
 */
export function resolveMedia(url: unknown): string | null {
  if (typeof url !== "string" || !url.trim()) return null;
  const u = url.trim();
  // The API's own address for uploads (http://localhost:4012/uploads/…) isn't reachable from a browser.
  const upload = /^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?(\/uploads\/.*)$/i.exec(u);
  if (upload) return MEDIA_ORIGIN + upload[1];
  if (/^https?:\/\//i.test(u)) return u;
  if (u.startsWith("/uploads/")) return MEDIA_ORIGIN + u;
  if (u.startsWith("/") && SITE) return SITE + u;
  // Same app: website assets are served by this origin too.
  if (u.startsWith("/") && typeof window !== "undefined") return window.location.origin + u;
  return null;
}

/* ------------------------------------------------------------------ */
/* Status display                                                      */
/* ------------------------------------------------------------------ */

export function statusInfo(s: SectionState["content"]): { label: string; tone: "g" | "a" | "b" | "n" | "r" } {
  if (s.status === "published") return { label: "Published", tone: "g" };
  if (s.status === "in_review") return { label: "In review", tone: "a" };
  if (s.status === "draft") return { label: s.reviewComment ? "Changes requested" : s.published ? "Draft changes" : "Draft", tone: s.reviewComment ? "r" : "b" };
  return { label: "Not written", tone: "n" };
}
