/* The platform's payment details, as the admin typed them (one per line). A line naming Airtel Money or TNM Mpamba
   gets that wallet's logo, its number large and a copy button; any other line stays plain text. */
import { useState } from 'react';
import { Check, Copy } from 'lucide-react';
import { cx } from './ui';

const WALLETS = [
    { match: /airtel/i, logo: '/images/pay/airtel-money.png', name: 'Airtel Money' },
    { match: /mpamba|tnm/i, logo: '/images/pay/mpamba.png', name: 'TNM Mpamba' },
];

function CopyNumber({ number }: { number: string }) {
    const [copied, setCopied] = useState(false);
    const copy = () => navigator.clipboard?.writeText(number.replace(/\s/g, '')).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); }, () => {});
    return (
        <button type="button" onClick={copy} className="grid size-9 shrink-0 place-items-center rounded-lg text-muted hover:bg-line-2" aria-label={copied ? 'Copied' : `Copy ${number}`}>
            {copied ? <Check className="size-4 text-emerald-600" aria-hidden /> : <Copy className="size-4" aria-hidden />}
        </button>
    );
}

export default function PaymentInstructions({ text, className }: { text: string; className?: string }) {
    const lines = text.split('\n').map((l) => l.trim()).filter(Boolean);

    return (
        <div className={cx('space-y-2', className)}>
            {lines.map((line, i) => {
                const wallet = WALLETS.find((w) => w.match.test(line));
                if (!wallet) return <p key={i} className="text-[15px] text-ink-2">{line}</p>;

                // "Airtel Money: 099 000 0000 (Name)": the label before the colon, then the number and the account name
                const detail = line.includes(':') ? line.slice(line.indexOf(':') + 1).trim() : line;
                const number = detail.match(/\+?\d[\d\s-]{6,}\d/)?.[0];
                const rest = number ? detail.replace(number, '').trim() : detail;
                return (
                    <div key={i} className="flex items-center gap-3 rounded-xl border border-line bg-white p-2.5">
                        <img src={wallet.logo} alt={wallet.name} className="size-11 shrink-0 rounded-lg object-contain" width={44} height={44} />
                        <div className="min-w-0 flex-1">
                            <p className="text-xs font-semibold text-muted">{wallet.name}</p>
                            {number ? <p className="text-lg leading-tight font-extrabold tracking-wide text-ink tabular-nums">{number}</p> : null}
                            {rest && <p className={cx('text-sm', number ? 'text-ink-2' : 'font-bold text-ink')}>{rest.replace(/^\((.*)\)$/, '$1')}</p>}
                        </div>
                        {number && <CopyNumber number={number} />}
                    </div>
                );
            })}
        </div>
    );
}
