(function () {
    'use strict';

    var sdkReady = false;

    function getConfig() {
        return typeof eyewvitrConfig !== 'undefined' ? eyewvitrConfig : {};
    }

    function showError(message) {
        if (!message) {
            message = 'Unable to launch AR try-on.';
        }

        console.error('Tryonixs:', message);
        window.alert(message);
    }

    function trackOpen() {
        var config = getConfig();

        if (!config.ajaxUrl || !config.nonce || typeof window.fetch !== 'function') {
            return;
        }

        var body = new window.URLSearchParams();
        body.append('action', 'eyewvitr_track_open');
        body.append('nonce', config.nonce);

        window.fetch(config.ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: body.toString()
        }).catch(function () {
            // Non-blocking analytics.
        });
    }

    function waitForSdk(callback, attempts) {
        var remaining = typeof attempts === 'number' ? attempts : 40;

        if (window.Tryonixs) {
            callback();
            return;
        }

        if (remaining <= 0) {
            showError('Tryonixs SDK failed to load. Check SDK Script URL in Tryonixs → Dashboard.');
            return;
        }

        window.setTimeout(function () {
            waitForSdk(callback, remaining - 1);
        }, 100);
    }

    function initSdk() {
        if (sdkReady && window.Tryonixs) {
            return true;
        }

        if (!window.Tryonixs) {
            return false;
        }

        var config = getConfig();

        if (!config.apiKey) {
            showError('API key is missing. Add it under Tryonixs → Dashboard.');
            return false;
        }

        var initOptions = {
            apiKey: config.apiKey,
            onError: function (error) {
                showError(error && error.message ? error.message : error);
            }
        };

        if (config.appUrl) {
            initOptions.appUrl = config.appUrl;
        }

        Tryonixs.init(initOptions);
        sdkReady = true;

        return true;
    }

    function getButtonImageUrl(button) {
        var imageUrl = button.getAttribute('data-image-url') || button.dataset.imageUrl || '';

        if (imageUrl) {
            return imageUrl;
        }

        var card = button.closest('.product');

        if (card) {
            var img = card.querySelector('a img, img.attachment-woocommerce_thumbnail, img');

            if (img) {
                return (
                    img.getAttribute('data-large_image') ||
                    img.getAttribute('data-src') ||
                    img.currentSrc ||
                    img.src ||
                    ''
                );
            }
        }

        return '';
    }

    function bindVariationImageSync() {
        if (typeof jQuery === 'undefined') {
            return;
        }

        var form = jQuery('form.variations_form');

        if (!form.length) {
            return;
        }

        form.on('found_variation', function (event, variation) {
            if (!variation) {
                return;
            }

            document.querySelectorAll('.eyewvitr-button').forEach(function (btn) {
                if (variation.variation_id) {
                    btn.dataset.productId = String(variation.variation_id);
                    btn.setAttribute('data-product-id', String(variation.variation_id));
                }

                if (!variation.image) {
                    return;
                }

                var url = variation.image.full_src || variation.image.src || variation.image.url;

                if (!url) {
                    return;
                }

                btn.dataset.imageUrl = url;
                btn.setAttribute('data-image-url', url);
            });
        });

        form.on('reset_data', function () {
            document.querySelectorAll('.eyewvitr-button').forEach(function (btn) {
                var defaultProductId = btn.getAttribute('data-product-id-default');

                if (defaultProductId) {
                    btn.dataset.productId = defaultProductId;
                    btn.setAttribute('data-product-id', defaultProductId);
                }

                var defaultUrl = btn.getAttribute('data-image-url-default');

                if (defaultUrl) {
                    btn.dataset.imageUrl = defaultUrl;
                    btn.setAttribute('data-image-url', defaultUrl);
                }
            });
        });
    }

    function setButtonLoading(button, isLoading) {
        if (!button) {
            return;
        }

        var label = button.querySelector('.eyewvitr-button__label');

        button.disabled = isLoading;
        button.classList.toggle('eyewvitr-button--loading', isLoading);

        if (isLoading) {
            button.setAttribute('aria-busy', 'true');
            button.dataset.eyewvitrOriginalText = label ? label.textContent : button.textContent;

            if (label) {
                label.textContent = (getConfig().i18n && getConfig().i18n.opening) || 'Opening Virtual Try-On…';
            } else {
                button.textContent = (getConfig().i18n && getConfig().i18n.opening) || 'Opening Virtual Try-On…';
            }
        } else {
            button.removeAttribute('aria-busy');

            if (button.dataset.eyewvitrOriginalText) {
                if (label) {
                    label.textContent = button.dataset.eyewvitrOriginalText;
                } else {
                    button.textContent = button.dataset.eyewvitrOriginalText;
                }

                delete button.dataset.eyewvitrOriginalText;
            }
        }
    }

    function openTryOn(button) {
        var config = getConfig();
        var productId = button.getAttribute('data-product-id') || button.dataset.productId || '';
        var productName = button.getAttribute('data-product-name') || button.dataset.productName || '';
        var imageUrl = getButtonImageUrl(button);
        var frameWidth = button.getAttribute('data-frame-width') || '';
        var lensHeight = button.getAttribute('data-lens-height') || '';
        var templeLength = button.getAttribute('data-temple-length') || '';
        var externalId = button.getAttribute('data-external-id') || '';

        if (!config.apiKey) {
            showError('API key is missing. Add it under Tryonixs → Dashboard.');
            return;
        }

        if (!imageUrl) {
            showError((config.i18n && config.i18n.missingImage) || 'Frame image is required for AR try-on.');
            return;
        }

        if (!productId) {
            showError((config.i18n && config.i18n.missingId) || 'Product ID is missing. Unable to open AR try-on.');
            return;
        }

        waitForSdk(function () {
            if (!initSdk()) {
                return;
            }

            setButtonLoading(button, true);
            trackOpen();

            if (typeof Tryonixs.isOpen === 'function' && Tryonixs.isOpen()) {
                Tryonixs.close();
            }

            var openOptions = {
                apiKey: config.apiKey,
                domain: window.location.hostname,
                productId: String(productId),
                productName: productName,
                imageUrl: imageUrl
            };

            if (config.appUrl) {
                openOptions.appUrl = config.appUrl;
            }

            if (externalId) {
                openOptions.externalProductId = String(externalId);
            }

            if (frameWidth) {
                openOptions.frameWidth = frameWidth;
            }

            if (lensHeight) {
                openOptions.lensHeight = lensHeight;
            }

            if (templeLength) {
                openOptions.templeLength = templeLength;
            }

            var result;

            try {
                result = Tryonixs.open(openOptions);
            } catch (error) {
                showError(error.message || error);
                setButtonLoading(button, false);
                return;
            }

            if (result === false) {
                setButtonLoading(button, false);
                return;
            }

            if (result && typeof result.then === 'function') {
                result
                    .then(function (opened) {
                        if (opened === false) {
                            showError('Unable to open AR try-on. Check product ID and domain in Tryonixs dashboard.');
                        }
                    })
                    .catch(function (error) {
                        showError(error && error.message ? error.message : error);
                    })
                    .finally(function () {
                        setButtonLoading(button, false);
                    });
            } else {
                setButtonLoading(button, false);
            }
        });
    }

    function bindButton(button) {
        if (!button || button.dataset.eyewvitrBound === '1') {
            return;
        }

        button.dataset.eyewvitrBound = '1';
        button.addEventListener('click', function (event) {
            event.preventDefault();
            event.stopPropagation();

            if (button.disabled) {
                return;
            }

            openTryOn(button);
        });
    }

    function bindButtons() {
        document.querySelectorAll('.eyewvitr-button').forEach(bindButton);

        if (typeof MutationObserver !== 'undefined') {
            var observer = new MutationObserver(function () {
                document.querySelectorAll('.eyewvitr-button').forEach(bindButton);
            });

            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        }
    }

    function boot() {
        bindButtons();
        bindVariationImageSync();

        waitForSdk(function () {
            initSdk();
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', boot);
    } else {
        boot();
    }
})();
