/**
 * Saudi Riyal (SAR) display formatting — SAMA symbol usage rules.
 *
 * Contract enforced by formatCurrency (rules 1–4) and by the self-hosted
 * SaudiRiyal webfont for the official glyph at U+20C1 (rules 5–10):
 *
 * 1. Position — Symbol is always to the LEFT of the numeric value (all languages).
 * 2. Spacing — Exactly one ASCII space between symbol and amount.
 * 3. Verbal values — When amounts use words (e.g. "million"), keep the symbol to
 *    the left of the whole expression. This helper formats numbers only.
 * 4. Negatives — Symbol is left of both the minus sign and the digits:
 *    correct: "\u20C1 -123.45" — incorrect: "-\u20C1 123.45"
 * 5–6. Proportions / geometry — Use the official SAMA-derived glyph; do not
 *    stretch or distort the character (web font + normal text metrics).
 * 7. Alignment — Symbol height follows surrounding text (font-size inherit).
 * 8. Direction — Do not mirror the glyph; LTR isolation preserves symbol-left order in RTL UI.
 * 9–10. Clear space / contrast — Layout and theming; symbol inherits text color.
 *
 * Glyph rendering: U+20C1 needs the app `SaudiRiyal` @font-face until OS fonts
 * cover Unicode 17. Never format SAR amounts ad-hoc; always use this helper.
 *
 * Excel exports should use `{ withSymbol: false }` — spreadsheets lack reliable
 * U+20C1 glyphs; amounts are numbers only there.
 */

/** Unicode U+20C1 SAUDI RIYAL SIGN */
export const SAUDI_RIYAL_SIGN = '\u20C1'

/** LTR isolate so RTL (ar) layout keeps symbol → sign → digits order. */
const LRI = '\u2066'
const PDI = '\u2069'

/**
 * Force LTR embedding for mixed copy that starts with the riyal symbol
 * (e.g. meter chips). Prevents RTL reordering from placing U+20C1 on the right.
 */
export function isolateLtr(text: string): string {
    return `${LRI}${text}${PDI}`
}

export type FormatCurrencyOptions = {
    /** When false, omit the riyal sign and bidi marks (e.g. Excel). Default true. */
    withSymbol?: boolean
}

/**
 * CSS for export/print documents that do not load the app stylesheet.
 * Pass an absolute URL so the font resolves in standalone HTML windows.
 */
export function saudiRiyalFontFaceCss(fontUrl: string): string {
    return `
@font-face {
    font-family: "SaudiRiyal";
    src: url("${fontUrl}") format("woff2");
    unicode-range: U+20C1;
    font-display: swap;
}`.trim()
}

export function formatCurrency(
    amount: number | string,
    customLocale?: string,
    options: FormatCurrencyOptions = {},
): string {
    const withSymbol = options.withSymbol !== false
    const amountNumber = Number(amount)

    // Always use Western/Arabic digits (0–9). ar-SA defaults to Eastern Arabic–Indic
    // (٠–٩), which mixes with Latin digits elsewhere in the UI.
    const absFormatted = new Intl.NumberFormat(customLocale ?? 'en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
        numberingSystem: 'latn',
    }).format(Math.abs(amountNumber))

    const isNegative = amountNumber < 0 || Object.is(amountNumber, -0)
    const body = isNegative ? `-${absFormatted}` : absFormatted

    if (!withSymbol) {
        return body
    }

    return `${LRI}${SAUDI_RIYAL_SIGN} ${body}${PDI}`
}
