import type { AccountField } from 'src/lib/api-types'

// Pure leaf — no component imports — so the jest-expo render-path (nitro/mmkv)
// is never pulled in and this stays unit-testable, mirroring
// `src/lib/text/fediverse-patterns.ts` and `src/lib/url-format.ts`.
//
// Mastodon exposes structured profile metadata as `Account.fields`: labelled
// name/value rows where `value` is HTML and `verified_at` (non-null) marks a
// rel="me"-verified link. Pixelfed always returns `fields: []`, so this
// normalizer returns an empty list there and the UI renders nothing — the
// feature is data-driven, not protocol-gated.
//
// Value HTML is carried through UNPARSED: parsing is deferred to render time
// where `StatusContent` (htmlToTextWithLineBreaks → AutolinkText) already turns
// a verified-link anchor into a tappable, favicon-decorated link with the full
// href preserved as the tap target. Re-parsing here would duplicate that.

export interface NormalizedField {
  name: string
  /** Raw HTML value, handed straight to StatusContent at render time. */
  valueHtml: string
  verified: boolean
}

export interface NormalizedAccountFields {
  fields: NormalizedField[]
  /** True iff any field is rel="me"-verified. Drives the (off-by-default)
   * account-level verified badge in ProfileHeader. */
  hasVerifiedField: boolean
}

const EMPTY: NormalizedAccountFields = { fields: [], hasVerifiedField: false }

export function normalizeAccountFields(
  account: { fields?: AccountField[] | null } | null | undefined
): NormalizedAccountFields {
  const raw = account?.fields
  if (!raw || raw.length === 0) return EMPTY

  const fields: NormalizedField[] = []
  let hasVerifiedField = false

  for (const field of raw) {
    if (!field) continue
    const name = (field.name ?? '').trim()
    const valueHtml = field.value ?? ''
    // Drop rows that carry neither a label nor a value; keep label-only or
    // value-only rows (both are legitimate on Mastodon).
    if (name.length === 0 && valueHtml.trim().length === 0) continue
    const verified = !!field.verified_at
    if (verified) hasVerifiedField = true
    fields.push({ name, valueHtml, verified })
  }

  if (fields.length === 0) return EMPTY
  return { fields, hasVerifiedField }
}
