/* ==================================================
   Nuclear Fancy Pants Edition™ — NUCLEAR+++
   File: /assets/js/amai-modules.js
   Description: Modules page JS — activation modal, help modal, API key wizard, model selector
   Last Edited: 2026-03-26
   ================================================== */

// amaiModules is passed via wp_localize_script:
// { provMeta: {...}, ajaxNonce: '...', ajaxUrl: '...' }

(function ($) {
    'use strict';

    var provMeta   = (typeof amaiModules !== 'undefined') ? amaiModules.provMeta   : {};
    var ajaxNonce  = (typeof amaiModules !== 'undefined') ? amaiModules.ajaxNonce  : '';
    var ajaxUrl    = (typeof amaiModules !== 'undefined') ? amaiModules.ajaxUrl    : window.ajaxurl;

    var curId = '', curName = '', curDefaultModel = '', curModelCosts = {}, curModelDescs = {}, isChangeMode = false;

    // hlpFromCard — true when help modal was opened from a card link (not from inside the act modal).
    // When true, "Got It" closes the help modal and opens the activation modal instead of just closing.
    var hlpFromCard = false;

    // --------------------------------------------------
    // Activation modal — open
    // --------------------------------------------------
    $(document).on('click', '.amai-activate-modal-btn', function (e) {
        e.preventDefault();
        curId           = $(this).data('provider-id');
        curName         = $(this).data('provider-name') || 'Provider';
        curDefaultModel = $(this).data('default-model') || (provMeta[curId] ? provMeta[curId].default_model : '');
        isChangeMode    = false;
        var isEmail     = $(this).data('email-provider') == '1';

        $('#act-modal-eyebrow').text(isEmail ? 'Email Providers' : 'AI Providers');
        $('#act-modal-title').text('Activate ' + curName);
        $('#act-key-wrapper').show();
        $('#act-save-btn').text('Save & Activate');
        if (isEmail) {
            $('#act-model-wrapper').hide();
            $('#act-help-trigger').show();
            $('#act-api-key').attr('placeholder', 'Paste your API key here...');
        } else {
            $('#act-model-wrapper').show();
            $('#act-help-trigger').show();
            $('#act-api-key').attr('placeholder', (provMeta[curId] ? provMeta[curId].prefix : '') + '…');
        }
        openActModal();
    });

    $(document).on('click', '.amai-change-model', function (e) {
        e.preventDefault();
        curId        = $(this).data('provider-id');
        curName      = $(this).data('provider-name') || 'Provider';
        isChangeMode = true;

        $('#act-modal-title').text('Change ' + curName + ' Model');
        $('#act-key-wrapper').hide();
        $('#act-help-trigger').hide();
        $('#act-save-btn').text('Save Model');
        openActModal();
    });

    function openActModal() {
        $('#act-api-key').val('');
        $('#act-model').html('<option value="">Enter API key first</option>').prop('disabled', true);
        $('#act-error').hide().text('');

        if (isChangeMode) {
            fetchModels(null);
        } else {
            $('#act-api-key').off('input.amai').on('input.amai', function () {
                var k = $(this).val().trim();
                if (k.length > 0) {
                    fetchModels(k);
                } else {
                    $('#act-model').html('<option value="">Enter API key first</option>').prop('disabled', true);
                }
            });
        }

        $('#amai-act-modal').addClass('show');
        setTimeout(function () { $('#act-api-key').focus(); }, 120);
    }

    function fetchModels(apiKey) {
        $.ajax({
            url:      ajaxUrl,
            type:     'POST',
            dataType: 'json',
            data: {
                action:      'amai_get_provider_data',
                provider_id: curId,
                api_key:     apiKey,
                _ajax_nonce: ajaxNonce,
            },
            success: function (r) {
                if (r && r.success && r.data.models && r.data.models.length) {
                    $('#act-model').html('<option value="">Select a model…</option>');
                    r.data.models.forEach(function (m) {
                        $('#act-model').append('<option value="' + m.value + '">' + m.label + '</option>');
                    });
                    if (curDefaultModel) { $('#act-model').val(curDefaultModel); }
                    if (!$('#act-model').val()) { $('#act-model').val(r.data.models[0].value); }
                    $('#act-model').prop('disabled', false);
                    curModelCosts = (r.data && r.data.model_costs) ? r.data.model_costs : {};
                    curModelDescs = (r.data && r.data.model_descriptions) ? r.data.model_descriptions : {};
                    if (r.data && r.data.recommended_model) {
                        $('#act-model').val(r.data.recommended_model);
                    }
                    updateCostChip($('#act-model').val());
                    updateDescChip($('#act-model').val());
                } else {
                    $('#act-model').html('<option value="">No models available</option>').prop('disabled', true);
                }
            },
            error: function () {
                $('#act-model').html('<option value="">Error loading models</option>').prop('disabled', true);
            },
        });
    }

    function closeActModal() { $('#amai-act-modal').removeClass('show'); }

    $('#act-cancel-btn, #act-close-btn').on('click', closeActModal);

    $('#act-save-btn').on('click', function () {
        if (isChangeMode) { saveModel(); } else { saveActivation(); }
    });

    function saveActivation() {
        var key   = $('#act-api-key').val().trim();
        var model = $('#act-model-wrapper').is(':visible') ? $('#act-model').val() : '';
        if (!key)                                             { showActErr('Please enter your API key.'); return; }
        if ($('#act-model-wrapper').is(':visible') && !model) { showActErr('Please select a model.');     return; }
        hideActErr();

        $.post(ajaxUrl, {
            action:      'amai_activate_provider',
            provider_id: curId,
            api_key:     key,
            model:       model,
            _ajax_nonce: ajaxNonce,
        }, function (r) {
            if (r.success) {
                closeActModal();
                location.reload();
            } else {
                showActErr((r.data && r.data.message) ? r.data.message : 'Activation failed - please try again.');
            }
        }).fail(function () { showActErr('Connection error - please try again.'); });
    }

    function saveModel() {
        var model      = $('#act-model').val();
        var modelLabel = $('#act-model option:selected').text();
        if (!model) { showActErr('Please select a model.'); return; }
        hideActErr();

        $.post(ajaxUrl, {
            action:      'amai_update_model',
            provider_id: curId,
            model:       model,
            model_label: modelLabel,
            _ajax_nonce: ajaxNonce,
        }, function (r) {
            if (r.success) {
                var $card      = $('[data-module-id="' + curId + '"]');
                var $name      = $card.find('.am-card-name');
                var baseName   = $name.data('base-name') || $name.text();
                var cleanLabel = modelLabel.split(' — ')[0].trim();
                if (cleanLabel && cleanLabel !== baseName) {
                    $name.text(cleanLabel);
                } else {
                    $name.text(baseName);
                }
                updateCostChip(model);
                updateDescChip(model);
                $card.find('.am-new-model-badge').remove();
                // Update locked message on sibling image provider cards.
                var displayName = cleanLabel && cleanLabel !== baseName ? cleanLabel : baseName;
                $card.find('.amai-change-model').attr('data-provider-name', displayName);
                curName = displayName;
                $('#act-modal-title').text('Change ' + curName + ' Model');
                $card.closest('.am-provider-grid').find('.am-card:not([data-module-id="' + curId + '"]) .am-locked').each(function () {
                    var txt = $(this).text();
                    if (txt.indexOf('is active right now') !== -1) {
                        $(this).text(displayName + ' is active right now. Deactivate it first to switch.');
                    }
                });
                closeActModal();
            } else {
                showActErr((r.data && r.data.message) ? r.data.message : 'Model update failed.');
            }
        }).fail(function () { showActErr('Connection error.'); });
    }

    $('#act-model').on('change', function () {
        var modelId = $(this).val();
        updateCostChip(modelId);
        updateDescChip(modelId);
    });

    function updateCostChip(modelId) {
        if (!curId || !modelId || !Object.keys(curModelCosts).length) { return; }
        var cost = curModelCosts[modelId];
        if (!cost) { return; }
        var $chip = $('[data-module-id="' + curId + '"] .am-card-cost');
        if ($chip.length) { $chip.text(cost); }
    }

    function updateDescChip(modelId) {
        if (!curId || !modelId || !Object.keys(curModelDescs).length) { return; }
        var desc = curModelDescs[modelId];
        if (!desc) { return; }
        var $desc = $('[data-module-id="' + curId + '"] .am-card-desc');
        if ($desc.length) { $desc.text(desc); }
    }

    function showActErr(msg) { $('#act-error').text(msg).show(); }
    function hideActErr()    { $('#act-error').hide().text(''); }

    $('#act-api-key, #act-model').on('input change', hideActErr);

    // --------------------------------------------------
    // Help / API key wizard modal
    // --------------------------------------------------
    var hlpSteps = [], hlpCur = 0, hlpPid = '';

    var consoles = {
        'ai-claude': { url: 'console.anthropic.com', color: '#D97757', icon: '✦', brand: 'Anthropic' },
        'ai-openai': { url: 'platform.openai.com',   color: '#10A37F', icon: '⬡', brand: 'OpenAI'    },
        'ai-gemini': { url: 'aistudio.google.com',   color: '#4285F4', icon: '◈', brand: 'Google AI' },
        'ai-grok':   { url: 'console.x.ai',          color: '#1C1917', icon: '✕', brand: 'xAI'       },
        'ai-mistral': { url: 'console.mistral.ai',  color: '#FA5400', icon: '▲', brand: 'Mistral'   },
        'img-dalle':  { url: 'platform.openai.com', color: '#10A37F', icon: '⬡', brand: 'OpenAI'    },
        'img-imagen': { url: 'aistudio.google.com', color: '#4285F4', icon: '◈', brand: 'Google AI' },
        'img-aurora':    { url: 'console.x.ai',              color: '#1C1917', icon: '✕', brand: 'xAI'          },
        'email-elastic': { url: 'app.elasticemail.com', color: '#6366F1', icon: '✉', brand: 'Elastic Email' },
    };

    function mockup(pid, stepType) {
        var c = consoles[pid] || consoles['ai-claude'];
        var chrome = '<div class="am-console"><div class="am-chrome"><div class="am-dots"><div class="am-dot" style="background:#FF5F57"></div><div class="am-dot" style="background:#FFBD2E"></div><div class="am-dot" style="background:#28C840"></div></div><div class="am-url"><span>' + c.url + '</span></div></div>';

        if (stepType === 'login') {
            return chrome + '<div class="am-screen" style="flex-direction:column;gap:5px;"><div style="width:30px;height:30px;background:' + c.color + ';border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:13px;margin-bottom:5px;">' + c.icon + '</div><div style="font-size:12.5px;font-weight:600;color:#F1F0EE;">Welcome to ' + c.brand + '</div><div style="font-size:10.5px;color:#6B7280;margin-bottom:9px;">Sign in to continue</div><div style="background:#1E2030;border:1px solid #3D4160;border-radius:7px;color:#D1D5DB;font-size:11px;padding:7px 14px;width:190px;text-align:center;margin-bottom:5px;">Continue with Google</div><div style="background:' + c.color + ';color:white;border-radius:7px;font-size:11px;font-weight:600;padding:7px 0;width:190px;text-align:center;" class="am-m-hl">Sign up with Email →</div></div></div><div class="am-ann"><div class="am-ann-line"></div><div class="am-ann-text">Either option works fine</div></div>';
        }
        if (stepType === 'nav') {
            var keyLabel = pid === 'ai-gemini' ? 'Get API key' : (pid === 'email-elastic' ? 'API Keys' : 'API Keys');
            return chrome + '<div class="am-screen" style="padding:0;align-items:stretch;"><div class="am-m-sidebar"><div class="am-m-logo"><div class="am-m-mark" style="background:' + c.color + ';">' + c.icon + '</div><span class="am-m-brand">' + c.brand + '</span></div><div class="am-m-nav">Overview</div><div class="am-m-nav active am-m-hl">' + keyLabel + '</div><div class="am-m-nav">Billing</div></div><div class="am-m-main"><div class="am-m-h">Dashboard</div><div style="background:#1A1D27;border:1px solid #2D3148;border-radius:6px;padding:11px;font-size:10.5px;color:#8B92A5;">Select a menu item.</div></div></div></div><div class="am-ann" style="padding-left:40px;"><div class="am-ann-line"></div><div class="am-ann-text">Click "' + keyLabel + '" in the sidebar</div></div>';
        }
        if (stepType === 'billing' || stepType === 'billing_first') {
            var billingNote = stepType === 'billing_first' ? 'Do this before creating a key' : 'Click Billing and add at least $5';
            return chrome + '<div class="am-screen" style="padding:0;align-items:stretch;"><div class="am-m-sidebar" style="width:125px;"><div class="am-m-logo"><div class="am-m-mark" style="background:' + c.color + ';">' + c.icon + '</div><span class="am-m-brand" style="font-size:9.5px;">' + c.brand + '</span></div><div class="am-m-nav">API Keys</div><div class="am-m-nav active am-m-hl">Billing</div></div><div class="am-m-main"><div class="am-m-h">Billing &amp; Credits</div><div class="am-m-cgrid"><div class="am-m-cbox"><div class="am-m-clbl">Balance</div><div class="am-m-cval" style="color:#F87171;">$0.00</div><div class="am-m-csub">No credits yet</div></div><div class="am-m-cbox"><div class="am-m-clbl">This Month</div><div class="am-m-cval">$0.00</div></div></div><div class="am-m-btn am-m-hl">+ Add Credits</div><div style="font-size:9.5px;color:#8B92A5;margin-top:6px;">Pay-as-you-go · $5 minimum</div></div></div></div><div class="am-ann" style="padding-left:55px;"><div class="am-ann-line"></div><div class="am-ann-text">' + billingNote + '</div></div>';
        }
        if (stepType === 'create') {
            var btnLabel = (pid === 'ai-openai' || pid === 'img-dalle') ? 'Create new secret key' : (pid === 'email-elastic' ? 'Create API Key' : 'Create API Key');
            return chrome + '<div class="am-screen" style="padding:0;align-items:stretch;"><div class="am-m-sidebar" style="width:125px;"><div class="am-m-logo"><div class="am-m-mark" style="background:' + c.color + ';">' + c.icon + '</div><span class="am-m-brand" style="font-size:9.5px;">' + c.brand + '</span></div><div class="am-m-nav active">API Keys</div><div class="am-m-nav">Billing</div></div><div class="am-m-main"><div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:9px;"><div class="am-m-h" style="margin:0;">API Keys</div><div class="am-m-btn am-m-hl">+ ' + btnLabel + '</div></div><div style="border:1px solid #2D3148;border-radius:5px;padding:13px;text-align:center;font-size:10.5px;color:#4B5563;">No keys yet</div></div></div></div><div class="am-ann"><div class="am-ann-line"></div><div class="am-ann-text">Click the button and give your key a name</div></div>';
        }
        if (stepType === 'copy') {
            var previews = { 'ai-claude': 'sk-ant-api03-AbCd…', 'ai-openai': 'sk-proj-AbCdEf…', 'ai-gemini': 'AIzaSyAbCdEf…', 'ai-grok': 'xai-AbCdEfGh…', 'ai-mistral': 'your-mistral-key…', 'img-dalle': 'sk-proj-AbCdEf…', 'img-imagen': 'AIzaSyAbCdEf…', 'img-aurora': 'xai-AbCdEfGh…', 'email-elastic': 'AbCdEfGhIjKl1234…' };
            return chrome + '<div class="am-screen" style="align-items:center;justify-content:center;"><div style="background:#1A1D27;border:1px solid #2D3148;border-radius:9px;padding:14px;width:260px;"><div style="font-size:11.5px;font-weight:600;color:#E2E8F0;margin-bottom:7px;">✅ &nbsp;Key Created</div><div class="am-m-warn">⚠️ This is the only time you\'ll see this key.</div><div class="am-m-keybox">' + (previews[pid] || 'your-api-key-here') + '</div><div class="am-m-copy am-m-hl">📋 &nbsp;Copy to Clipboard</div></div></div></div><div class="am-ann"><div class="am-ann-line"></div><div class="am-ann-text">Copy it, then click "Got It - Back to Setup"</div></div>';
        }
        return '';
    }

    var typeLabels = {
        'login':         'Create Account',
        'nav':           'Find Keys',
        'billing_first': 'Add Credits First',
        'create':        'Create Key',
        'copy':          'Copy & Save',
        'billing':       'Add Credits',
    };

    var stepTips = [
        'Takes about 5 minutes total',
        'The sidebar is always visible once you\'re logged in',
        'Give it a name you\'ll recognise later',
        'Copy it now - you won\'t get another chance',
        'Pay-as-you-go, no monthly fee',
    ];

    function calloutClass(stepType, isLast) {
        if (isLast)                        { return 'am-hlp-success'; }
        if (stepType === 'copy')           { return 'am-hlp-warn'; }
        if (stepType === 'billing_first')  { return 'am-hlp-warn'; }
        return 'am-hlp-note';
    }

    function renderHlp() {
        var total = hlpSteps.length;
        var pct   = total <= 1 ? 100 : Math.round((hlpCur / (total - 1)) * 88 + 12);
        var labHtml = '';

        hlpSteps.forEach(function (s, i) {
            var lbl = typeLabels[s[2]] || ('Step ' + (i + 1));
            var cls = i === hlpCur ? 'active' : (i < hlpCur ? 'done' : '');
            labHtml += '<span class="am-hlp-lbl ' + cls + '">' + lbl + '</span>';
        });

        $('#hlp-labels').html(labHtml);
        $('#hlp-fill').css('width', pct + '%');
        $('#hlp-counter').text('Step ' + (hlpCur + 1) + ' of ' + total);

        var step     = hlpSteps[hlpCur];
        var inst     = step[0] || '';
        var note     = step[1] || '';
        var stepType = step[2] || '';
        var isLast   = hlpCur === total - 1;
        var cCls     = calloutClass(stepType, isLast);
        var noteHtml = note ? '<div class="' + cCls + '">' + note + '</div>' : '';
        var mockHtml = mockup(hlpPid, stepType);

        $('#hlp-body').html(
            '<div class="am-hlp-step active">' +
            '<div class="am-hlp-headline">' + (typeLabels[stepType] || ('Step ' + (hlpCur + 1))) + '</div>' +
            '<div class="am-hlp-text">' + inst + '</div>' +
            mockHtml + noteHtml +
            '</div>'
        );

        $('#hlp-back').prop('disabled', hlpCur === 0);
        var last = hlpCur === total - 1;
        $('#hlp-next').toggle(!last);
        if (last) { $('#hlp-done').addClass('show'); } else { $('#hlp-done').removeClass('show'); }
        $('#hlp-tip').text(stepTips[Math.min(hlpCur, stepTips.length - 1)]);
    }

    // --------------------------------------------------
    // Help trigger — from inside the activation modal
    // --------------------------------------------------
    $(document).on('click', '#act-help-trigger', function (e) {
        e.preventDefault();
        if (!curId || !provMeta[curId] || !provMeta[curId].help_steps || !provMeta[curId].help_steps.length) { return; }
        hlpFromCard = false;
        hlpPid      = curId;
        hlpSteps    = provMeta[curId].help_steps;
        hlpCur      = 0;
        $('#hlp-eyebrow').text('Getting Started - ' + curName);
        $('#hlp-title').text('How to Get Your ' + curName + ' API Key');
        renderHlp();
        $('#amai-help-modal').addClass('show');
    });

    // --------------------------------------------------
    // Help trigger — from a provider card (pre-activation)
    // --------------------------------------------------
    $(document).on('click', '.amai-card-help-trigger', function (e) {
        e.preventDefault();
        var pid  = $(this).data('provider-id');
        var name = $(this).data('provider-name') || 'Provider';
        if (!pid || !provMeta[pid] || !provMeta[pid].help_steps || !provMeta[pid].help_steps.length) { return; }

        // Store provider context so "Got It" can open the correct activation modal
        curId           = pid;
        curName         = name;
        curDefaultModel = provMeta[pid].default_model || '';
        isChangeMode    = false;

        hlpFromCard = true;
        hlpPid      = pid;
        hlpSteps    = provMeta[pid].help_steps;
        hlpCur      = 0;
        $('#hlp-eyebrow').text('Getting Started - ' + name);
        $('#hlp-title').text('How to Get Your ' + name + ' API Key');
        renderHlp();
        $('#amai-help-modal').addClass('show');
    });

    $('#hlp-next').on('click', function () { if (hlpCur < hlpSteps.length - 1) { hlpCur++; renderHlp(); } });
    $('#hlp-back').on('click', function () { if (hlpCur > 0) { hlpCur--; renderHlp(); } });

    function closeHlp() {
        $('#amai-help-modal').removeClass('show');
        if (hlpFromCard) {
            hlpFromCard = false;
            // Open the activation modal for the provider they just read about
            $('#act-modal-title').text('Activate ' + curName);
            $('#act-key-wrapper').show();
            $('#act-help-trigger').show();
            $('#act-save-btn').text('Save & Activate');
            $('#act-api-key')
                .val('')
                .attr('placeholder', (provMeta[curId] ? provMeta[curId].prefix : '') + '…');
            $('#act-model').html('<option value="">Enter API key first</option>').prop('disabled', true);
            $('#act-error').hide().text('');
            $('#act-api-key').off('input.amai').on('input.amai', function () {
                var k = $(this).val().trim();
                if (k.length > 0) {
                    fetchModels(k);
                } else {
                    $('#act-model').html('<option value="">Enter API key first</option>').prop('disabled', true);
                }
            });
            $('#amai-act-modal').addClass('show');
            setTimeout(function () { $('#act-api-key').focus(); }, 120);
        }
    }

    $('#hlp-done, #hlp-close').on('click', closeHlp);

    $(document).on('keydown', function (e) {
        if ($('#amai-help-modal').hasClass('show')) {
            if (e.key === 'Escape')      { closeHlp(); }
            if (e.key === 'ArrowRight')  { $('#hlp-next').trigger('click'); }
            if (e.key === 'ArrowLeft')   { $('#hlp-back').trigger('click'); }
            return;
        }
        if ($('#amai-act-modal').hasClass('show') && e.key === 'Escape') { closeActModal(); }
    });

    $(document).on('click', '.close-notice, .am-notice-x', function () {
        $(this).closest('.am-notice,.notice').fadeOut(180, function () { $(this).remove(); });
    });


    // --------------------------------------------------
    // SMS provider modal
    // --------------------------------------------------
    var curSmsId = '', curSmsName = '';

    $(document).on('click', '.amai-sms-connect-btn', function (e) {
        e.preventDefault();
        curSmsId   = $(this).data('sms-provider-id');
        curSmsName = $(this).data('sms-provider-name') || 'Provider';
        openSmsModal();
    });

    function openSmsModal() {
        $('#sms-modal-eyebrow').text('SMS Providers');
        $('#sms-modal-title').text('Connect ' + curSmsName);
        $('.sms-provider-fields').hide();
        $('#sms-error').hide().text('');
        if (curSmsId === 'sms-twilio') {
            $('#sms-fields-twilio').show();
            $('#sms-twilio-sid').val('');
            $('#sms-twilio-token').val('');
            $('#sms-twilio-from').val('');
        } else if (curSmsId === 'sms-plivo') {
            $('#sms-fields-plivo').show();
            $('#sms-plivo-authid').val('');
            $('#sms-plivo-token').val('');
            $('#sms-plivo-from').val('');
        } else if (curSmsId === 'sms-vonage') {
            $('#sms-fields-vonage').show();
            $('#sms-vonage-key').val('');
            $('#sms-vonage-secret').val('');
            $('#sms-vonage-from').val('');
        } else if (curSmsId === 'sms-sinch') {
            $('#sms-fields-sinch').show();
            $('#sms-sinch-plan').val('');
            $('#sms-sinch-token').val('');
            $('#sms-sinch-from').val('');
        }
        $('#amai-sms-modal').addClass('show');
    }

    function closeSmsModal() { $('#amai-sms-modal').removeClass('show'); }

    $('#sms-cancel-btn, #sms-close-btn').on('click', closeSmsModal);

    $('#sms-save-btn').on('click', function () {
        var data = { action: 'amai_save_sms_provider', provider_id: curSmsId, _ajax_nonce: ajaxNonce };
        if (curSmsId === 'sms-twilio') {
            data.account_sid = $('#sms-twilio-sid').val().trim();
            data.auth_token  = $('#sms-twilio-token').val().trim();
            data.from_number = $('#sms-twilio-from').val().trim();
            if (!data.account_sid || !data.auth_token || !data.from_number) {
                $('#sms-error').text('All three fields are required.').show(); return;
            }
        } else if (curSmsId === 'sms-plivo') {
            data.auth_id     = $('#sms-plivo-authid').val().trim();
            data.auth_token  = $('#sms-plivo-token').val().trim();
            data.from_number = $('#sms-plivo-from').val().trim();
            if (!data.auth_id || !data.auth_token || !data.from_number) {
                $('#sms-error').text('All three fields are required.').show(); return;
            }
        } else if (curSmsId === 'sms-vonage') {
            data.api_key     = $('#sms-vonage-key').val().trim();
            data.api_secret  = $('#sms-vonage-secret').val().trim();
            data.from_number = $('#sms-vonage-from').val().trim();
        } else if (curSmsId === 'sms-sinch') {
            data.service_plan_id = $('#sms-sinch-plan').val().trim();
            data.api_token       = $('#sms-sinch-token').val().trim();
            data.from_number     = $('#sms-sinch-from').val().trim();
            if (!data.api_key || !data.api_secret || !data.from_number) {
                $('#sms-error').text('All three fields are required.').show(); return;
            }
        }
        $('#sms-save-btn').prop('disabled', true).text('Saving...');
        $.post(ajaxUrl, data, function (r) {
            if (r.success) {
                closeSmsModal();
                location.reload();
            } else {
                $('#sms-error').text((r.data && r.data.message) ? r.data.message : 'Save failed - please try again.').show();
                $('#sms-save-btn').prop('disabled', false).text('Save & Activate');
            }
        }).fail(function () {
            $('#sms-error').text('Connection error - please try again.').show();
            $('#sms-save-btn').prop('disabled', false).text('Save & Activate');
        });
    });

    $(document).on('keydown', function (e) {
        if ($('#amai-sms-modal').hasClass('show') && e.key === 'Escape') { closeSmsModal(); }
    });


    // ----------------------------------------------------------------
    // Store provider modal (WooCommerce)
    // ----------------------------------------------------------------
    $(document).on('click', '.amai-store-connect-btn', function (e) {
        e.preventDefault();
        $('#store-error').hide().text('');
        $('#amai-store-modal').addClass('show');
    });

    function closeStoreModal() { $('#amai-store-modal').removeClass('show'); }

    $('#store-cancel-btn, #store-close-btn').on('click', closeStoreModal);

    $('#store-save-btn').on('click', function () {
        $('#store-save-btn').prop('disabled', true).text('Connecting...');
        $.post(ajaxUrl, {
            action:      'amai_save_store_provider',
            provider_id: 'store-woocommerce',
            _ajax_nonce: ajaxNonce
        }, function (r) {
            if (r.success) {
                closeStoreModal();
                location.reload();
            } else {
                var msg = (r.data && r.data.message) ? r.data.message : 'Connection failed - please try again.';
                $('#store-error').text(msg).show();
                $('#store-save-btn').prop('disabled', false).text('Connect WooCommerce');
            }
        }).fail(function () {
            $('#store-error').text('Connection error - please try again.').show();
            $('#store-save-btn').prop('disabled', false).text('Connect WooCommerce');
        });
    });

    $(document).on('keydown', function (e) {
        if ($('#amai-store-modal').hasClass('show') && e.key === 'Escape') { closeStoreModal(); }
    });

}(jQuery));