import axios from 'axios';
import { ready, slideDown } from '@site/js/utils/dom.js';

/**
 * Worldpay integration for the checkout basket overview page.
 *
 * Initialises the Worldpay template form when `#worldpayContainer` exists,
 * wires the "Pay" button, and forwards the resulting token to the back-end
 * 3DS handler. Originally by Rihards Siliņš (2016) — converted to vanilla
 * during the front-end jquery removal.
 */
ready(() => {
    const worldpayContainer = document.getElementById('worldpayContainer');
    if (!worldpayContainer) {
        return;
    }

    const payButton = document.querySelector('.worldPayPay');
    const defaultButtonLabel = payButton ? payButton.innerHTML : '';

    const resetButton = () => {
        if (!payButton) {
            return;
        }
        payButton.classList.remove('block');
        payButton.innerHTML = defaultButtonLabel;
    };

    Worldpay.useTemplateForm({
        clientKey: worldpay_variables.client_key,
        form: 'worldpayPaymentForm',
        paymentSection: 'worldpayPaymentSection',
        display: 'inline',
        saveButton: false,
        reusable: true,
        type: 'post',
        templateOptions: {
            dimensions: {
                width: 500,
                height: 265,
            },
        },
        validationError() {
            resetButton();
        },
        async callback(obj) {
            if (!obj || !obj.token) {
                return;
            }

            const form = document.getElementById('worldpayPaymentForm');
            if (!form) {
                return;
            }

            const tokenInput = form.querySelector('input[name=token]');
            const nameInput = form.querySelector('input[name=name]');
            if (tokenInput) tokenInput.value = obj.token;
            if (nameInput) nameInput.value = obj.paymentMethod.name;

            const data = {};
            new FormData(form).forEach((value, key) => {
                data[key] = value;
            });

            try {
                const result = await axios.post('/shop/checkout/worldpay/ajax/payment.php', data, {
                    headers: {
                        Accept: worldpay_variables.server_http_accept,
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                });
                const response = result.data;

                if (response.paymentStatus === 'PRE_AUTHORIZED'
                    && response.redirectURL
                    && response.redirectURL !== '') {
                    const paReqInput = form.querySelector('input[name=PaReq]');
                    if (paReqInput) {
                        paReqInput.value = response.oneTime3DsToken;
                    }
                    form.setAttribute('action', response.redirectURL);
                    form.submit();
                    return;
                }

                resetButton();
                const declinedReason = document.querySelector('.cardDeclined .reason');
                const declinedBox = document.querySelector('.cardDeclined');
                if (declinedReason) declinedReason.textContent = response.paymentStatusReason ?? '';
                if (declinedBox) declinedBox.style.display = '';
            } catch (err) {
                resetButton();
                const reasonEl = document.querySelector('.paymentError .reason');
                const errorBox = document.querySelector('.paymentError');
                const responseText = err.response?.data ?? err.message;
                if (reasonEl) {
                    reasonEl.textContent = typeof responseText === 'string'
                        ? responseText
                        : JSON.stringify(responseText);
                }
                if (errorBox) errorBox.style.display = '';
            }
        },
    });

    // Pay button — first click reveals the payment section; second click submits.
    payButton?.addEventListener('click', (event) => {
        if (payButton.classList.contains('block')) {
            event.preventDefault();
            return;
        }

        document.querySelectorAll('.worldpayErrorMsg').forEach((el) => {
            el.style.display = 'none';
        });

        const section = document.getElementById('worldpayPaymentSection');
        const sectionVisible = section && getComputedStyle(section).display !== 'none';

        if (sectionVisible) {
            event.preventDefault();
            payButton.innerHTML = 'Please wait ...';
            payButton.classList.add('block');
            Worldpay.submitTemplateForm();
        } else if (section) {
            slideDown(section);
        }
    });
});
