document.addEventListener('onSolidshopOrderCreated', e => {
    const {detail} = e;
    const {id, currency, amount, payment} = detail.data;

    if (payment !== 'paypal') {
        return;
    }

    // Prevent redirect
    detail.redirect = false;
    const {clientId, orderUrl} = Joomla.getOptions('plg_solidshoppayment_paypal');
    const test = clientId.startsWith('test_');

    const baseSdk = test ? 'https://sandbox.paypal.com/sdk/js' : 'https://www.paypal.com/sdk/js';
    const sdk = `${baseSdk}?client-id=${clientId}&currency=${currency}&components=buttons`;
    const container = document.createElement('div');
    const ppSDKScript = document.createElement('script');
    document.body.appendChild(container);

    const loader = Solidshop.loader(container).show();
    ppSDKScript.src = sdk;
    ppSDKScript.onload = function () {
        const handleOrderUrl = orderUrl + (orderUrl.includes('?') ? '&' : '?') + 'order_id=' + id;
        window.paypal
            .Buttons({
                style: {
                    shape: 'rect',
                    layout: 'vertical',
                    color: 'gold',
                    label: 'pay',
                },
                message: {
                    amount,
                    align: 'center',
                    color: 'black',
                    position: 'top',
                },
                onError: (err) => Solidshop.notify('error', {body: err?.message || err?.toString() || err}),
                createOrder: async (data, actions) => {
                    let orderId = null;
                    await Solidshop.request.post(handleOrderUrl, {
                        data: { step: 'createOrder' },
                        onSuccess: json => orderId = json.data,
                    });

                    return orderId;
                },
                onApprove: (data, actions) => Solidshop.request.post(handleOrderUrl, {
                    data: {
                        payment_txn_id: data.orderID,
                        step: 'approveOrder',
                    },
                    onSuccess: () => window.location.href = detail.orderFinishUrl,
                }),
            })
            .render(container)
            .then(() => {
                Solidshop.modal.create({
                    autoShow: true,
                    header: false,
                    footer: false,
                    backdrop: false,
                    size: 'modal-lg',
                    body: container,
                    onShown: loader.hide,
                })
            });
    };

    document.body.appendChild(ppSDKScript);
});
