(function () {
    'use strict';

    function openStep(step) {
        document.querySelectorAll('.ptgold-step').forEach(function (s) {
            s.classList.remove('is-active');
        });
        step.classList.add('is-active');
    }

    document.querySelectorAll('.ptgold-step-header').forEach(function (hdr) {
        hdr.addEventListener('click', function (e) {
            if (e.target.closest('.ptgold-edit-btn')) return;
            var step = hdr.closest('.ptgold-step');
            if (step.classList.contains('is-active')) {
                step.classList.remove('is-active');
            } else {
                openStep(step);
            }
        });
    });

    document.querySelectorAll('.ptgold-edit-btn').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.stopPropagation();
            openStep(btn.closest('.ptgold-step'));
        });
    });

    var extraList = document.getElementById('ptgold-social-extra-list');
    var addBtn = document.getElementById('ptgold-add-social');

    function makeExtraRow(name, url) {
        var row = document.createElement('div');
        row.className = 'ptgold-social-extra-row';

        var nameInput = document.createElement('input');
        nameInput.type = 'text';
        nameInput.name = 'social_extra_name[]';
        nameInput.value = name || '';
        nameInput.placeholder = ptgoldConfig.i18n.platformName;

        var urlInput = document.createElement('input');
        urlInput.type = 'url';
        urlInput.name = 'social_extra_url[]';
        urlInput.value = url || '';
        urlInput.placeholder = 'https://';

        var removeBtn = document.createElement('button');
        removeBtn.type = 'button';
        removeBtn.className = 'ptgold-remove-row';
        removeBtn.title = ptgoldConfig.i18n.remove;
        removeBtn.innerHTML = '<svg viewBox="0 0 20 20" fill="currentColor" width="16" height="16"><path d="M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z"/></svg>';
        removeBtn.addEventListener('click', function () {
            row.style.overflow = 'hidden';
            row.style.transition = 'max-height .25s ease, opacity .25s ease';
            row.style.maxHeight = row.offsetHeight + 'px';
            row.style.opacity = '1';
            requestAnimationFrame(function () {
                row.style.maxHeight = '0';
                row.style.opacity = '0';
            });
            setTimeout(function () { row.remove(); }, 260);
        });

        row.appendChild(nameInput);
        row.appendChild(urlInput);
        row.appendChild(removeBtn);
        return row;
    }

    if (extraList) {
        extraList.querySelectorAll('.ptgold-remove-row').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var row = btn.closest('.ptgold-social-extra-row');
                row.style.overflow = 'hidden';
                row.style.transition = 'max-height .25s ease, opacity .25s ease';
                row.style.maxHeight = row.offsetHeight + 'px';
                row.style.opacity = '1';
                requestAnimationFrame(function () {
                    row.style.maxHeight = '0';
                    row.style.opacity = '0';
                });
                setTimeout(function () { row.remove(); }, 260);
            });
        });
    }

    if (addBtn && extraList) {
        addBtn.addEventListener('click', function () {
            var row = makeExtraRow('', '');
            row.style.overflow = 'hidden';
            row.style.maxHeight = '0';
            row.style.opacity = '0';
            row.style.transition = 'max-height .25s ease, opacity .25s ease';
            extraList.appendChild(row);
            requestAnimationFrame(function () {
                row.style.maxHeight = '60px';
                row.style.opacity = '1';
            });
            setTimeout(function () {
                row.style.overflow = '';
                row.style.transition = '';
                row.style.maxHeight = '';
                row.style.opacity = '';
                row.querySelector('input[type="text"]').focus();
            }, 260);
        });
    }

    // Newsletter AJAX subscription
    var emailInput = document.getElementById('ptgold_newsletter_email');
    var messageDiv = document.getElementById('ptgold-newsletter-message');

    if (emailInput && messageDiv) {
        var newsletterForm = emailInput.closest('form');
        var newsletterBtn = emailInput.closest('.ptgold-field').querySelector('a.button');

        if (newsletterBtn && newsletterForm) {
            newsletterBtn.addEventListener('click', function (e) {
                e.preventDefault();

                var email = emailInput.value.trim();

                // Validate email
                if (!email) {
                    showMessage(ptgoldConfig.i18n.enterEmail, 'error');
                    return;
                }

                var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(email)) {
                    showMessage(ptgoldConfig.i18n.validEmail, 'error');
                    return;
                }

                // Get nonce
                var nonceInput = newsletterForm.querySelector('input[name="ptgold_newsletter_nonce"]');
                if (!nonceInput) {
                    showMessage(ptgoldConfig.i18n.securityError, 'error');
                    return;
                }

                var nonce = nonceInput.value;

                var allowTrackingValue = 'no';
                var allowTrackingInput = newsletterForm.querySelector('input[name="allow_tracking"]:checked');
                if (allowTrackingInput) {
                    allowTrackingValue = allowTrackingInput.value;
                }

                // Disable button and show loading state
                var originalText = newsletterBtn.textContent;
                newsletterBtn.style.opacity = '0.6';
                newsletterBtn.style.cursor = 'not-allowed';
                newsletterBtn.style.pointerEvents = 'none';
                newsletterBtn.textContent = ptgoldConfig.i18n.subscribing;

                // Send AJAX request
                var xhr = new XMLHttpRequest();
                xhr.open('POST', ptgoldConfig.ajaxUrl, true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

                xhr.onload = function () {
                    // Re-enable button
                    newsletterBtn.style.opacity = '1';
                    newsletterBtn.style.cursor = 'pointer';
                    newsletterBtn.style.pointerEvents = 'auto';
                    newsletterBtn.textContent = originalText;

                    if (xhr.status === 200) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            if (response.success) {
                                showMessage(response.data && response.data.message ? response.data.message : ptgoldConfig.i18n.thankYou, 'success');
                            } else {
                                showMessage(response.data && response.data.message ? response.data.message : ptgoldConfig.i18n.error, 'error');
                            }
                        } catch (e) {
                            showMessage(ptgoldConfig.i18n.error, 'error');
                        }
                    } else {
                        showMessage(ptgoldConfig.i18n.error, 'error');
                    }
                };

                xhr.onerror = function () {
                    // Re-enable button
                    newsletterBtn.style.opacity = '1';
                    newsletterBtn.style.cursor = 'pointer';
                    newsletterBtn.style.pointerEvents = 'auto';
                    newsletterBtn.textContent = originalText;
                    showMessage(ptgoldConfig.i18n.networkError, 'error');
                };

                var params = 'action=ptgold_newsletter_subscribe&email=' + encodeURIComponent(email) + '&allow_tracking=' + encodeURIComponent(allowTrackingValue) + '&nonce=' + encodeURIComponent(nonce);
                xhr.send(params);
            });

            function showMessage(message, type) {
                messageDiv.textContent = message;
                messageDiv.style.display = 'block';

                if (type === 'success') {
                    messageDiv.style.backgroundColor = '#d4edda';
                    messageDiv.style.color = '#155724';
                    messageDiv.style.border = '1px solid #c3e6cb';
                } else {
                    messageDiv.style.backgroundColor = '#f8d7da';
                    messageDiv.style.color = '#721c24';
                    messageDiv.style.border = '1px solid #f5c6cb';
                }
            }
        }
    }

})();
