/**
 * Admin Settings Page JS — NoonElite Audit Engine
 *
 * Handles: logo picker, copy-to-clipboard, dismiss guide, connection testing.
 * Localized data available via noonAuditSettings object.
 */
(function($) {
    'use strict';

    // ── Toast Utility ────────────────────────────────────────────────────────
    function noonToast(msg) {
        var t = document.getElementById('noon-toast');
        if (!t) return;
        t.innerHTML = '<span class="dashicons dashicons-yes" style="color:#10b981;"></span>' + msg;
        t.classList.add('show');
        clearTimeout(t._tid);
        t._tid = setTimeout(function() { t.classList.remove('show'); }, 2000);
    }

    // ── Copy Utility ─────────────────────────────────────────────────────────
    function noonCopy(text) {
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(text);
        } else {
            var ta = document.createElement('textarea');
            ta.value = text;
            ta.style.position = 'fixed';
            ta.style.opacity = '0';
            document.body.appendChild(ta);
            ta.select();
            document.execCommand('copy');
            document.body.removeChild(ta);
        }
        noonToast(noonAuditSettings.i18n.shortcodeCopied);
    }

    $(function() {
        // ── Logo Media Picker ────────────────────────────────────────────────
        $('#noon-audit-logo-btn').on('click', function(e) {
            e.preventDefault();
            var frame = wp.media({
                title: noonAuditSettings.i18n.selectLogo,
                multiple: false,
                library: { type: 'image' }
            });
            frame.on('select', function() {
                var url = frame.state().get('selection').first().toJSON().url;
                $('#noon-audit-logo-url').val(url);
            });
            frame.open();
        });

        // ── Copy Shortcode ───────────────────────────────────────────────────
        $('#noon-audit-copy-btn, #noon-audit-shortcode').on('click', function() {
            noonCopy('[noon_audit type="your-slug"]');
        });

        // ── Dismiss Getting Started Guide ────────────────────────────────────
        $(document).on('click', '.noon-audit-dismiss-guide', function() {
            $('#noon-audit-guide').slideUp(200);
            $.post(noonAuditSettings.ajaxUrl, {
                action: 'noon_audit_dismiss_guide',
                _wpnonce: noonAuditSettings.dismissNonce
            });
        });
    });

    // ── Connection Testing ───────────────────────────────────────────────────
    document.addEventListener('DOMContentLoaded', function() {
        // Salesforce Test
        var btnSf = document.getElementById('noon-audit-test-sf');
        if (btnSf) {
            btnSf.addEventListener('click', function(e) {
                e.preventDefault();
                btnSf.disabled = true;
                btnSf.innerText = 'Testing...';

                var resultEl = document.getElementById('noon-audit-sf-result');
                resultEl.innerHTML = '';
                resultEl.className = '';

                var formData = new FormData();
                formData.append('action', 'noon_audit_test_sf');
                formData.append('_wpnonce', noonAuditSettings.testConnNonce);

                fetch(noonAuditSettings.ajaxUrl, { method: 'POST', body: formData })
                    .then(function(response) { return response.json(); })
                    .then(function(res) {
                        btnSf.disabled = false;
                        btnSf.innerText = noonAuditSettings.i18n.testConnection;
                        if (res.success) {
                            resultEl.className = 'noon-success-text';
                            resultEl.innerHTML = '<span class="dashicons dashicons-yes-alt"></span> ' + res.data;
                        } else {
                            resultEl.className = 'noon-error-text';
                            resultEl.innerHTML = '<span class="dashicons dashicons-warning"></span> ' + res.data;
                        }
                    })
                    .catch(function() {
                        resultEl.className = 'noon-error-text';
                        resultEl.innerHTML = '<span class="dashicons dashicons-warning"></span> ' + noonAuditSettings.i18n.requestFailed;
                    });
            });
        }

        // HubSpot Test
        var btnHs = document.getElementById('noon-audit-test-hs');
        if (btnHs) {
            btnHs.addEventListener('click', function(e) {
                e.preventDefault();
                btnHs.disabled = true;
                btnHs.innerText = 'Testing...';

                var resultEl = document.getElementById('noon-audit-hs-result');
                resultEl.innerHTML = '';
                resultEl.className = '';

                var formData = new FormData();
                formData.append('action', 'noon_audit_test_hs');
                formData.append('_wpnonce', noonAuditSettings.testConnNonce);

                fetch(noonAuditSettings.ajaxUrl, { method: 'POST', body: formData })
                    .then(function(response) { return response.json(); })
                    .then(function(res) {
                        btnHs.disabled = false;
                        btnHs.innerText = noonAuditSettings.i18n.testConnection;
                        if (res.success) {
                            resultEl.className = 'noon-success-text';
                            resultEl.innerHTML = '<span class="dashicons dashicons-yes-alt"></span> ' + res.data;
                        } else {
                            resultEl.className = 'noon-error-text';
                            resultEl.innerHTML = '<span class="dashicons dashicons-warning"></span> ' + res.data;
                        }
                    })
                    .catch(function() {
                        btnHs.disabled = false;
                        btnHs.innerText = noonAuditSettings.i18n.testConnection;
                        resultEl.className = 'noon-error-text';
                        resultEl.innerHTML = '<span class="dashicons dashicons-warning"></span> ' + noonAuditSettings.i18n.requestFailed;
                    });
            });
        }
    });
})(jQuery);
