/**
 * Sanity returns `[]` — not null — for a list an editor has emptied out, and
 * `??` only catches null/undefined. So `data?.stats ?? DEFAULT_STATS` keeps the
 * empty array and the section renders blank, rather than falling back to the
 * built-in content the way every page component assumes it will.
 *
 * Normalising empty arrays to `undefined` once, at the top of each content
 * component, makes all of those existing `?? fallback` expressions behave as
 * written. It runs over one already-fetched page document, so the recursion is
 * shallow and cheap.
 *
 * Deliberately does NOT touch empty strings: a field an editor cleared on
 * purpose (an optional badge, say) should stay cleared rather than snapping
 * back to a default they cannot see.
 */
export function normalizeEmptyArrays<T>(value: T): T {
  return normalize(value) as T;
}

function normalize(value: unknown): unknown {
  if (Array.isArray(value)) {
    if (value.length === 0) return undefined;
    return value.map(normalize);
  }

  // Plain objects only — never rebuild Dates, class instances or null.
  if (value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
    const out: Record<string, unknown> = {};
    for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
      out[key] = normalize(item);
    }
    return out;
  }

  return value;
}
