/* Small helpers shared by pages. Amounts travel as minor units (tambala, cents): 150000 = 1,500. */

/** 150000, "MWK" -> "MWK 1,500" (decimals only when there are some), like the server's App\Support\Money. */
export function money(minor: number, currency: string): string {
    const sign = minor < 0 ? '-' : '';
    const abs = Math.abs(Math.round(minor));
    const whole = abs % 100 === 0;
    return `${sign}${currency} ${(abs / 100).toLocaleString('en-US', { minimumFractionDigits: whole ? 0 : 2, maximumFractionDigits: whole ? 0 : 2 })}`;
}

/** "1,500" or "1500.5" typed in -> 150050 minor units, or null when it isn't a number. */
export function toMinor(input: string): number | null {
    const clean = input.replace(/[,\s]/g, '');
    if (!/^\d+(\.\d{1,2})?$/.test(clean)) return null;
    const [whole, fraction = ''] = clean.split('.');
    return Number(whole) * 100 + Number(fraction.padEnd(2, '0'));
}

/** 2 -> "2", 0.125 -> "0.125" (three decimals: a scale's grams) */
export const qty = (n: number) => String(Math.round(n * 1000) / 1000);

/** A fresh id for a sale, made on the phone, so a resend is recognised as the same sale. */
export function uuid(): string {
    if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
    // older Android browsers
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (Math.random() * 16) | 0;
        return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
    });
}
