function startTrustPay() {
    var iframe = document.getElementById("TrustPayFrame");

    iframe.style.position = 'fixed';
    iframe.style.left = 0;
    iframe.style.right = 0;
    iframe.style.top = 0;
    iframe.style.bottom = 0;
    iframe.style.width = 0;
    iframe.style.height = 0;
    iframe.style.border = 'none';
    iframe.style.opacity = 0;
    iframe.style.transition = 'opacity .5s ease-in-out';
    iframe.style.zIndex = '99999';
    
    iframe.addEventListener('load', function () {
        try {
            openPopup();
        } catch (err) {
            console.error(err);
        }
    });

    if (window.addEventListener) {
        window.addEventListener("message", onMessage, false);
    }
    else if (window.attachEvent) {
        window.attachEvent("onmessage", onMessage, false);
    }
};

function onMessage(event) {
    var data = event.data;

    if (typeof (window[data.func]) === "function") {
        window[data.func].call(null, data.message);
    }
    else if (data === "popupLoaded") {
        if (typeof window.onTrustPayPopupLoaded === 'function') {
            onTrustPayPopupLoaded();
        }
    }
}

function openPopup() {
    var iframe = document.getElementById("TrustPayFrame");
    iframe.style.display = 'block'; // doplnene kvoli implementacii woo blocks
    iframe.style.opacity = 1;
    iframe.style.width = '100%';
    iframe.style.height = '100%';
    iframe.focus();
    iframe.contentWindow.postMessage('redirectMessage', '*');
    iframe.contentWindow.postMessage('authorizationMessage', '*');
}

function closePopup(message) {
    var iframe = document.getElementById('TrustPayFrame');
    iframe.style.opacity = 0;
    iframe.style.display = 'none';

    // Delay execution so that the iframe changes dimension only after opacity is 0
    setTimeout(function() {
        iframe.style.width = 0;
        iframe.style.height = 0;
    }, 1000);
}

function redirectPopup(url) {
    window.top.location.href = url;
}

// CashToCode handler
function cashToCode(country, amount) {
   
    const table = {
        'AT':[9.99, 10, 10.00, 12.99, 14.99, 17.99, 19.99, 22.99, 24.99, 25.00, 27.99, 29.99,
            34.99, 39.99, 44.99, 49.99, 50.00, 54.99, 59.99, 64.99, 69.99, 74.99, 79.99,
            84.99, 89.99, 94.99, 99.99, 100.00, 200.00, 300.00, 400.00, 500.00
        ],
        'DE':[9.99, 10, 10.00, 12.99, 14.99, 17.99, 19.99, 22.99, 24.99, 25.00, 27.99, 29.99,
            34.99, 39.99, 44.99, 49.99, 50.00, 54.99, 59.99, 64.99, 69.99, 74.99, 79.99,
            84.99, 89.99, 94.99, 99.99, 100.00, 200.00, 300.00, 400.00
        ],
        'IT':[9.99, 10, 10.00, 12.99, 14.99, 17.99, 19.99, 22.99, 24.99, 25.00, 27.99, 29.99,
            34.99, 39.99, 44.99, 49.99, 50.00, 54.99, 59.99, 64.99, 69.99, 74.99, 79.99,
            84.99, 89.99, 94.99, 99.99, 100.00, 150.00, 200.00, 300.00, 400.00, 500.00
        ],
        'IE':[9.99, 10, 10.00, 12.99, 14.99, 17.99, 19.99, 22.99, 24.99, 25.00, 27.99, 29.99,
            34.99, 39.99, 44.99, 49.99, 50.00, 54.99, 59.99, 64.99, 69.99, 74.99, 79.99,
            84.99, 89.99, 94.99, 99.99, 100.00, 150.00, 200.00, 300.00, 400.00, 500.00
        ]
    };

    var show = false;

    if(typeof(table[country]) == 'object' && table[country].includes(amount)) {
        show = true;
    } else if(country == 'DE' && amount >= 9.99 && amount <= 999.99) {
        show = true;
    } else if(country == 'IE' && amount <= 10.00 && amount <= 800.00) {
        show = true;
    }

    return show;
}







(() => {
    const settings = window.wc?.wcSettings?.['trustpay_gateway_data'] || {};
    console.log('Finby settings:', settings);
    
    const { createElement, useEffect } = window.wp.element;
    
    const showLogos = settings.showLogos;
    
    const label = createElement(
        'span',
        { style: { display: 'inline-flex', alignItems: 'center', gap: '8px' } },
        settings.title, // text vedľa obrázka
        (showLogos)? createElement('img', {
            src: settings.tpLogoUrl, // cesta k logu
            alt: 'finby logo',
            style: {
                height: '1.2em',       // prispôsobí sa výške textu
                width: 'auto',         // zachová pomer strán
                verticalAlign: 'middle'
            }
        }) : null
    );
    
    /*
    const paymentMethods = [
        {
            id: 'payment_method_trustpay_gateway_card',
            name: 'Platba kartou',
            logo: 'https://example.com/card.png',
            value: 'card'
        },
        {
            id: 'payment_method_trustpay_gateway_wire',
            name: 'Bankový prevod',
            logo: 'https://example.com/bank.png',
            value: 'wire'
        }
    ];*/
    const paymentMethods = settings.paymentMethods;
    

    const dynamicElements = paymentMethods.map((method, index) => {
        const labelChildren = [];
        

        labelChildren.push(method.name); // text sa vždy zobrazí

        if (showLogos) {
            labelChildren.push(
                createElement('img', {
                        src: method.logo,
                        alt: `${method.name} logo`,
                        style: {
                            height: '1.2em',
                            width: 'auto',
                            verticalAlign: 'middle'
                        }
                    })
            );
        }
        
        //if(method.value != 'cashtocode' || cashToCode(billingCountry, totalAmount))
            return createElement(
                'div',
                {
                    key: method.id || index,
                    id: 'trustpay_payment_method_'+method.value,
                    style: { display: (method.value != 'cashtocode')? 'flex':'none', alignItems: 'center', /*marginBottom: '8px',*/ gap: '8px' }
                },
                createElement('input', {
                    type: 'radio',
                    name: 'trustpay_gateway_method_option', // všetky musia mať rovnaký name pre skupinu rádii
                    id: method.id,
                    value: method.value,
                    defaultChecked: (index === 0)
                    /*
                    onChange: () => {
                        const hiddenInput = document.querySelector('#contact-namespace-trustpay_gateway_method');
                        if(hiddenInput) {
                            /*
                            hiddenInput.value = method.value;

                            // Vytvoríme a spustíme change event
                            const event = new Event('change', {
                                'bubbles': true,
                                'cancelable': true
                            });
                            hiddenInput.dispatchEvent(event);  // Vyvoláme change event
                            */
                            /*
                            // updatovanie hodnoty pola v reacte
                            var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
                            nativeInputValueSetter.call(hiddenInput, method.value);
                            var ev2 = new Event('input', { bubbles: true});
                            hiddenInput.dispatchEvent(ev2);
                        }
                    }*/
                }),
                createElement('label', {
                        htmlFor: method.id,
                        style: { display: 'flex', alignItems: 'center', gap: '6px', cursor: 'pointer', marginBottom: '0px', fontSize: '0.8em' }
                    },/*
                    method.name,
                    createElement('img', {
                        src: method.logo,
                        alt: `${method.name} logo`,
                        style: {
                            height: '1.2em',
                            width: 'auto',
                            verticalAlign: 'middle'
                        }
                    })*/
                    ...labelChildren
                )
            );
    });
    
    
    
    
    let currentCountry = document.querySelector('#billing-country')?.value;
    if(!currentCountry) {
        currentCountry = document.querySelector('#shipping-country')?.value;
    }

    const monitorCountryChange = setInterval(() => {
        
        let newCountry = document.querySelector('#billing-country')?.value;
        if(!newCountry) {
            newCountry = document.querySelector('#shipping-country')?.value;
        }
        
        let totalElement = document.querySelector('.wc-block-components-totals-item__value');
        let totalAmount = parseFloat(totalElement?.textContent.replace(/[^0-9,.\-]/g, '').replace(',', '.') );
        
        if (newCountry && newCountry !== currentCountry) {
            currentCountry = newCountry;
            //console.log('Billing country changed to:', currentCountry);
            //console.log('totalAmount:', totalAmount);
            
            const div = document.querySelector('#trustpay_payment_method_cashtocode');
            if(div) {
                if(cashToCode(currentCountry, totalAmount)){
                    div.style.display = 'flex';
                }
                else {
                    div.style.display = 'none';
                }
            }
        }
    }, 300);
    
    
    
    
    const IframeWithInit = () => {
        useEffect(() => {
            //console.log('Všetko je vykreslené – iframe aj ostatné prvky.');
            // Tu spusti tvoju JS funkciu (napr. komunikáciu s iframe)
            startTrustPay();
        }, []); // prázdne pole = spustí sa iba raz po prvom renderi

        return createElement('iframe', {
            id: 'TrustPayFrame',
            allow: 'payment',
            style: {
                height: '0',
                width: '0',
                border: 'none',
                display: 'none'
            }
        });
    };
    
    
    const Content = () => {
        
        //const description = window.wp.htmlEntities.decodeEntities(settings.description || '');

        return createElement(
            'div',
            null,
            /*
            createElement('p', null, description),
            createElement('img', {
                src: 'https://example.com/path/to/your/image.jpg',
                width: 40,
                height: 20,
                alt: 'Obrázok brány'
            }),*/
            ...dynamicElements,
            createElement(IframeWithInit)
        );
    };

    const Edit = () => {
        return window.wp.element.createElement('div', null, 'Edit finby gateway');
    };

    //document.addEventListener('DOMContentLoaded', function () { // nenastavovalo vybratu branu po nacitani checkout
        const { registerPaymentMethod } = window.wc?.wcBlocksRegistry || {};
        //const { createElement } = window.wp?.element || {};

        if (typeof registerPaymentMethod !== 'function' || typeof createElement !== 'function') {
            console.error('[Finby Gateway] registerPaymentMethod or createElement is not available.');
            return;
        }

        registerPaymentMethod({
            name: 'trustpay_gateway',
            label: label,
            ariaLabel: settings.title,
            content: createElement(Content, null), // Vytvorenie React elementu pre obsah platobnej brány
            edit: createElement(Edit, null), // Vytvorenie React elementu pre editačný režim
            canMakePayment: () => {
                //console.log('canMakePayment?');
                return true;
            },
            supports: {
                features: ['products']
            }
            
        });
    //});
    
    
    document.addEventListener('DOMContentLoaded', () => {
        const interval = setInterval(() => {
                const btn = document.querySelector('.wc-block-components-checkout-place-order-button');
                if (btn) {
                    clearInterval(interval);

                    btn.addEventListener('click', async (e) => {
                            
                            btn.disabled = true;
                            
                            // tuto upravu fetchu mozes zavolat aj mimo kliku.
                            // ak klik nebude spolahlivy, presun do behu anonymnej funkcie
                            const previousFetch = window.fetch;
                            window.fetch = async (input, init) => {
                                
                                try {
                                    // len ak je nasa brana aktivna a vybrata submetoda
                                    const selected = document.querySelector('input[name="trustpay_gateway_method_option"]:checked');
                                    
                                    // input je volana url string
                                    if (selected && typeof input === 'string' && input.includes('/wc/store/v1/checkout') && !input.includes('calc_totals')) {
                                        
                                        let separator = input.includes('?') ? '&' : '?';
                                        
                                        let newUrl = input;
                                        if (selected) {
                                            newUrl += `${separator}get_trustpay_type_url=${selected.value}`;
                                        }
                                        
                                        const originalData = JSON.parse(init.body);
                                        
                                        // Upraviť dáta
                                        const modifiedData = {
                                            ...originalData,
                                            additional_fields: {
                                                ...originalData.additional_fields,
                                                'namespace/trustpay_gateway_method': selected.value
                                            }
                                        };
                                        
                                        //const response = await previousFetch(newUrl, init);
                                        const response = await previousFetch(newUrl, {
                                            ...init,
                                            body: JSON.stringify(modifiedData)
                                        });
                                        
                                        const clonedResponse = response.clone();
                                        
                                        let data;
                                        
                                        try {
                                            data = await clonedResponse.json();
                                        } catch (err) {
                                            console.error('JSON parse error:', err);
                                            return response; // fallback, nech Woo neskolabuje
                                        }
                                        
                                        if (!response.ok) {
                                            return response;
                                        }
                                        
                                        const redirectMethods = [
                                            'bancontact',
                                            'cashtocode',
                                            'eps',
                                            'giropay',
                                            'paypal',
                                            'paysafecard',
                                            'sofort',
                                            'nasplatkytb',
                                            'skippay',
                                            'trustly'
                                        ]; 
                                        
                                        if (data?.payment_result?.redirect_url) {
                                            // Zablokuj redirect
                                            console.log('Intercepted TrustPay redirect:', data.payment_result.redirect_url);

                                            // Otvor popup namiesto redirectu
                                            if(settings.iframe && ! redirectMethods.includes(selected.value)) {
                                                const iframe = document.getElementById("TrustPayFrame");
                                                if(iframe) {
                                                    iframe.src = data.payment_result.redirect_url;
                                                }
                                            }
                                            else {
                                                redirectPopup(data.payment_result.redirect_url);
                                            }
                                            
                                            // Vráť neškodnú odpoveď, aby Woo necrashol
                                            return new Response(JSON.stringify({ status: 'success' }), {
                                                headers: { 'Content-Type': 'application/json' }
                                            });
                                        }
                                        
                                        return response;
                                    }
                                    
                                    return previousFetch(input, init);
                                    
                                } catch (err) {
                                    console.error('Custom window.fetch error in try block:', err);
                                }
                                finally {
                                     console.log('fetch finally');
                                    // Bez ohľadu na chyby, vždy obnov pôvodný fetch
                                    // toto nie je dobre. nikdy to nerob, lebo zrušíš iné hooky 
                                    //window.fetch = previousFetch;
                                }
                                
                                //console.log('fetch nevratil nic');
                                return previousFetch(input, init);
                            };
                            
                            btn.disabled = false;
                            
                    });

                }
        }, 100); // čaká, kým sa tlačidlo vyrenderuje
    });
    

})();