const KLARNA_PLACEMENT = 'klarna-placement';
const DATA_PURCHASE_AMOUNT_ATTRIBUTE = 'data-purchase-amount';
const DATA_CUSTOM_PAYMENT_METHOD_IDS_ATTRIBUTE = 'data-custom-payment-method-ids';

function refreshKlarnaPlacement() {
    window.Klarna?.OnsiteMessaging?.refresh();
}

function getKlarnaPlacements() {
    const klarnaPlacementsWithPurchaseAmountSelector = `${KLARNA_PLACEMENT}[${DATA_PURCHASE_AMOUNT_ATTRIBUTE}]`;
    return $.find(klarnaPlacementsWithPurchaseAmountSelector);
}

export function updateKlarnaPlacements(newAmount, paymentMethodIds = null) {
    const formattedAmount = newAmount.split(/[,.]/).join('');
    const klarnaPlacements = getKlarnaPlacements() || [];

    klarnaPlacements.forEach((placement) => {
        placement.setAttribute(DATA_PURCHASE_AMOUNT_ATTRIBUTE, formattedAmount);

        if (Array.isArray(paymentMethodIds) && paymentMethodIds.length > 0) {
            placement.setAttribute(
                DATA_CUSTOM_PAYMENT_METHOD_IDS_ATTRIBUTE,
                paymentMethodIds.join(',')
            );
        } else {
            placement.removeAttribute(DATA_CUSTOM_PAYMENT_METHOD_IDS_ATTRIBUTE);
        }
    });

    refreshKlarnaPlacement();
}
