/**
 * Idempotent normalizer for signature-slot markup. Guarantees that every
 * occurrence of `[Signature Conciergerie]` / `[Signature Partenaire]` in
 * the document body is wrapped in the canonical span:
 *
 *     <span data-signature-slot="sender">[Signature Conciergerie]</span>
 *     <span data-signature-slot="recipient">[Signature Partenaire]</span>
 *
 * Works whether the input has none of them wrapped, all of them wrapped,
 * or any mix (Tiptap-saved + user-typed). The renderer's slot scanner
 * relies on this uniform shape.
 */
export function normalizeSignatureSlots(html: string | null | undefined): string {
    if (!html) return '';

    let result = html;

    // Step 1 — strip any existing wrappers so we start from a clean state.
    result = result.replace(
        /<span[^>]*data-signature-slot\s*=\s*["']sender["'][^>]*>[\s\S]*?<\/span>/gi,
        '[Signature Conciergerie]',
    );
    result = result.replace(
        /<span[^>]*data-signature-slot\s*=\s*["']recipient["'][^>]*>[\s\S]*?<\/span>/gi,
        '[Signature Partenaire]',
    );

    // Step 2 — wrap every bracket marker with an EMPTY span. We deliberately
    // omit the bracket text from the wrapper so that if the renderer's JS
    // effect doesn't run (cached chunk, JS error, etc.) the recipient still
    // sees a clean empty slot instead of literal "[Signature Partenaire]".
    result = result.replace(
        /\[Signature\s+Conciergerie\]/gi,
        '<span data-signature-slot="sender"></span>',
    );
    result = result.replace(
        /\[Signature\s+Partenaire\]/gi,
        '<span data-signature-slot="recipient"></span>',
    );

    return result;
}

/**
 * Same as {@link normalizeSignatureSlots} but additionally fills the slot
 * wrappers with a static, fully-rendered signature block (title + stamp /
 * signature image). Used for the read-only / locked render path so the
 * rich block is present in the HTML directly — no client-side JS pass is
 * needed and a stale or failing useEffect can never leave the slot empty.
 */
export function renderStaticSignatureSlots(
    html: string | null | undefined,
    opts: {
        senderSignatureUrl?: string | null;
        senderStampUrl?: string | null;
        recipientSignatureUrl?: string | null;
        recipientSignedAt?: string | null;
    } = {},
): string {
    const base = normalizeSignatureSlots(html);
    if (!base) return '';

    const senderImg = opts.senderStampUrl || opts.senderSignatureUrl || '/admin-sign/sign-admin.png';
    const senderBlock = `<span data-signature-slot="sender" style="display:inline-block;text-align:center;vertical-align:top;width:100%;max-width:320px"><span style="display:block;font-size:14px;font-weight:600;color:#000;margin-bottom:8px">Signature et cachet du mandataire</span><img src="${senderImg}" alt="Signature Conciergerie" style="display:block;margin:0 auto;height:12rem;width:16rem;object-fit:contain"/></span>`;

    const recipientImg = opts.recipientSignatureUrl;
    const recipientInner = recipientImg
        ? `<img src="${recipientImg}" alt="Signature Partenaire" style="height:100%;width:100%;object-fit:contain"/>`
        : `<span style="display:flex;align-items:center;justify-content:center;height:100%;color:#94a3b8;font-style:italic;font-size:13px">En attente de signature</span>`;
    const caption = recipientImg && opts.recipientSignedAt
        ? `<span style="display:block;font-size:11px;color:#64748b;margin-top:6px">Signé le ${formatDateFrSafe(opts.recipientSignedAt)}</span>`
        : '';
    const recipientBlock = `<span data-signature-slot="recipient" style="display:inline-block;text-align:center;vertical-align:top;width:100%;max-width:320px"><span style="display:block;font-size:14px;font-weight:600;color:#000;margin-bottom:8px">Signature du Partenaire</span><span style="display:block;margin:0 auto;height:12rem;width:100%;max-width:20rem;border-radius:0.375rem;border:1px solid #9ca3af;background:#fff;overflow:hidden">${recipientInner}</span>${caption}</span>`;

    return base
        .replace(/<span data-signature-slot="sender"><\/span>/g, senderBlock)
        .replace(/<span data-signature-slot="recipient"><\/span>/g, recipientBlock);
}

function formatDateFrSafe(value: string): string {
    const d = new Date(value);
    if (Number.isNaN(d.getTime())) return value;
    const dd = String(d.getDate()).padStart(2, '0');
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const yyyy = d.getFullYear();
    const hh = String(d.getHours()).padStart(2, '0');
    const mi = String(d.getMinutes()).padStart(2, '0');
    return `${dd}/${mm}/${yyyy} ${hh}:${mi}`;
}
