const KLARNA_PLACEMENT = 'klarna-placement';
const DATA_PURCHASE_AMOUNT_ATTRIBUTE = 'data-purchase-amount';

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

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

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

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

    refreshKlarnaPlacement();
}
