import type { SupportedLocale } from "@/app/lib/i18n/locales"; // Assembles/parses the `content` JSON blob mobile-api's Message.content carries // (locale -> translated text), per spec "The Portal Manages Translations Across // Areas": "assembling them into the `content` JSON blob". /** * Builds the `content` blob from the add/edit form's per-locale text fields. * Only the RUNTIME locale list is considered (add-admin-locale-management: the * list comes from LocalesProvider, not a hardcoded array); an * empty/whitespace-only value is omitted rather than stored as `""`, so the * list's filled/empty indicator can tell "translated" from "blank" * unambiguously. */ export function buildContentBlob( perLocale: Record, locales: SupportedLocale[], ): string { const filled: Record = {}; for (const { code } of locales) { const value = perLocale[code]?.trim(); if (value) filled[code] = value; } return JSON.stringify(filled); } /** Parses a stored `content` blob back into a locale->text record for the edit * form's prefill and the list's filled/empty indicator. Never throws: malformed * or non-object content resolves to `{}` rather than breaking the page. */ export function parseContentBlob(content: string | null | undefined): Record { if (!content) return {}; try { const parsed = JSON.parse(content); if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { return parsed as Record; } return {}; } catch { return {}; } } /** Renders a value that may arrive as either a plain display string or a raw * locale-JSON blob (e.g. seeded data that skipped the backend's display-string * normalisation) as a single displayable string. Prefers `en_US`, falls back to * the first locale present, and passes a plain string through unchanged. Never * throws and never renders raw JSON. */ export function displayLocaleName(value: string | null | undefined): string { const parsed = parseContentBlob(value); const keys = Object.keys(parsed); if (keys.length === 0) return value ?? ""; if ("en_US" in parsed) return parsed.en_US; return parsed[keys[0]]; }