(function () {
    const ORDER = ['30', '30_60', '30_90', '30_60_90'];

    const COPY = {
        30: {
            heading: 'Buy now, pay within 30 days',
            repayment:
                'From the point of collection / delivery of goods you’ll have 30 days to pay',
        },
        '30_60': {
            heading: 'Buy now and choose to pay within 30 or 60 days',
            repayment:
                "From the point of collection / delivery of goods, you'll have until the end of your chosen repayment term to pay",
        },
        '30_90': {
            heading: 'Buy now and choose to pay within 30 or 90 days',
            repayment:
                "From the point of collection / delivery of goods, you'll have until the end of your chosen repayment term to pay",
        },
        '30_60_90': {
            heading: 'Buy now and choose to pay within 30, 60 or 90 days',
            repayment:
                "From the point of collection / delivery of goods, you'll have until the end of your chosen repayment term to pay",
        },
    };

    let index = -1;

    function nextTerms() {
        index = (index + 1) % ORDER.length;
        return ORDER[index];
    }

    function resetBillieModalScroll($modal) {
        const $body = $modal.find('.modal-body');
        const $content = $modal.find('.modal-content');

        $body.scrollTop(0);
        $content.attr('data-scroll-state', 'top');
    }

    function applyBillieTerms(terms) {
        const copy = COPY[terms] || COPY['30'];
        const $modal = $('#billieLearnMoreModal');

        $modal.find('.js-billie-terms-heading').text(copy.heading);
        $modal.find('.js-billie-repayment-line').text(copy.repayment);
        $modal.attr('data-billie-terms', terms);
    }

    $(document).on('shown.bs.modal', '#billieLearnMoreModal', function () {
        const $modal = $(this);
        requestAnimationFrame(() => resetBillieModalScroll($modal));
    });

    $(document).on('hidden.bs.modal', '#billieLearnMoreModal', function () {
        resetBillieModalScroll($(this));
    });

    $(document).on('click', '.billie__link', function (e) {
        e.preventDefault();

        const terms = nextTerms();
        applyBillieTerms(terms);
    });
})();
