/* ChainPay Admin JS — chainpay.store */
(function($){
'use strict';

/* ── Helpers ───────────────────────────────────────────── */
function cpMsg(el, type, msg){
    el.removeClass('ok err info warn').addClass(type).html(msg).show();
}
function cpCopy(text, btn){
    var orig = $(btn).text();
    if(navigator.clipboard){
        navigator.clipboard.writeText(text).then(function(){ $(btn).text('Copied!'); setTimeout(function(){ $(btn).text(orig); }, 1800); });
    } else {
        var ta = document.createElement('textarea');
        ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta);
        $(btn).text('Copied!'); setTimeout(function(){ $(btn).text(orig); }, 1800);
    }
}

/* ── Save settings ─────────────────────────────────────── */
$(document).on('click', '.cp-save-btn', function(e){
    e.preventDefault();
    var $btn = $(this);
    var $msg = $('#cp-save-msg');
    var tab  = $btn.data('tab') || 'general';
    var data = { action: 'chainpay_admin_save', nonce: cpAdmin.nonce, tab: tab };

    // Collect all inputs in the active tab section
    $('.cp-field input, .cp-field select, .cp-field textarea').each(function(){
        var name = $(this).attr('name');
        if(!name) return;
        if($(this).attr('type') === 'checkbox'){
            data[name] = $(this).is(':checked') ? 'yes' : 'no';
        } else {
            data[name] = $(this).val();
        }
    });

    // Enabled coins checkboxes
    var coins = [];
    $('input[name="chainpay_enabled_coins[]"]:checked').each(function(){ coins.push($(this).val()); });
    if(coins.length) data['chainpay_enabled_coins'] = coins;

    // xPub fields
    $('input[data-xpub-coin]').each(function(){
        var coin = $(this).data('xpub-coin');
        var val  = $(this).val().trim();
        if(val){ data['xpub[' + coin + ']'] = val; }
    });

    $btn.prop('disabled', true).html('<span class="cp-spin"></span>Saving…');
    $.post(cpAdmin.ajax, data, function(r){
        $btn.prop('disabled', false).text('Save Changes');
        if(r.success){
            cpMsg($msg, 'ok', '✓ ' + (r.data.message || 'Settings saved.'));
        } else {
            cpMsg($msg, 'err', '✗ ' + (r.data || 'Save failed.'));
        }
        setTimeout(function(){ $msg.fadeOut(); }, 4000);
    }).fail(function(){
        $btn.prop('disabled', false).text('Save Changes');
        cpMsg($msg, 'err', '✗ Network error.');
    });
});

/* ── License verify ─────────────────────────────────────── */
$(document).on('click', '#cp-license-verify', function(e){
    e.preventDefault();
    var $btn = $(this);
    var key  = $('#cp-license-key-input').val().trim();
    var $msg = $('#cp-license-msg');
    if(!key){ cpMsg($msg, 'err', '✗ Please enter a license key.'); return; }
    $btn.prop('disabled', true).html('<span class="cp-spin"></span>Verifying…');
    $.post(cpAdmin.ajax, { action: 'chainpay_admin_verify_license', nonce: cpAdmin.nonce, license_key: key }, function(r){
        $btn.prop('disabled', false).text('Activate License');
        if(r.success){
            cpMsg($msg, 'ok', '✓ ' + r.data.message);
            setTimeout(function(){ location.reload(); }, 1500);
        } else {
            cpMsg($msg, 'err', '✗ ' + (r.data || 'Invalid key.'));
        }
    });
});

/* ── License revoke ─────────────────────────────────────── */
$(document).on('click', '#cp-license-revoke', function(e){
    e.preventDefault();
    if(!confirm('Revoke your license? Pro features will be disabled.')) return;
    var $btn = $(this);
    var $msg = $('#cp-license-msg');
    $btn.prop('disabled', true).html('<span class="cp-spin"></span>Revoking…');
    $.post(cpAdmin.ajax, { action: 'chainpay_admin_revoke_license', nonce: cpAdmin.nonce }, function(r){
        $btn.prop('disabled', false).text('Revoke License');
        if(r.success){
            cpMsg($msg, 'warn', '⚠ ' + r.data.message);
            setTimeout(function(){ location.reload(); }, 1500);
        }
    });
});

/* ── Test xPub derivation ───────────────────────────────── */
$(document).on('click', '.cp-test-xpub', function(e){
    e.preventDefault();
    var $btn  = $(this);
    var coin  = $btn.data('coin');
    var xpub  = $('input[data-xpub-coin="' + coin + '"]').val().trim();
    var $res  = $('#cp-xpub-result-' + coin);
    if(!xpub){ $res.show().removeClass('ok err').addClass('warn').html('⚠ Enter an xPub key first.'); return; }
    $btn.prop('disabled', true).html('<span class="cp-spin"></span>Testing…');
    $.post(cpAdmin.ajax, { action: 'chainpay_admin_test_xpub', nonce: cpAdmin.nonce, coin: coin, xpub: xpub }, function(r){
        $btn.prop('disabled', false).text('Test Derivation');
        if(r.success && r.data.addresses){
            var addrs = r.data.addresses.map(function(a, i){ return '<code style="display:block;font-size:10px;padding:2px 0;">' + i + ': ' + a + '</code>'; }).join('');
            cpMsg($res, 'ok', '✓ Valid! Sample addresses:<br>' + addrs + (r.data.note ? '<br><small>' + r.data.note + '</small>' : ''));
        } else {
            cpMsg($res, 'err', '✗ ' + (r.data || 'Derivation failed.'));
        }
        $res.show();
    });
});

/* ── Refresh prices ─────────────────────────────────────── */
$(document).on('click', '#cp-refresh-prices', function(e){
    e.preventDefault();
    var $btn = $(this);
    var $msg = $('#cp-prices-msg');
    $btn.prop('disabled', true).html('<span class="cp-spin"></span>Refreshing…');
    $.post(cpAdmin.ajax, { action: 'chainpay_admin_refresh_prices', nonce: cpAdmin.nonce }, function(r){
        $btn.prop('disabled', false).text('↻ Refresh Prices');
        if(r.success){
            cpMsg($msg, 'ok', '✓ ' + r.data.message + ' (' + r.data.count + ' coins)');
        } else {
            cpMsg($msg, 'err', '✗ ' + (r.data || 'Refresh failed.'));
        }
        setTimeout(function(){ $msg.fadeOut(); }, 4000);
    });
});

/* ── Copy buttons ───────────────────────────────────────── */
$(document).on('click', '.cp-copy-btn', function(){
    var $val = $(this).closest('.cp-copy-row').find('.cp-copy-val');
    cpCopy($val.text().trim(), this);
});

/* ── Tab navigation ─────────────────────────────────────── */
$(document).on('click', '.cp-tab-link', function(e){
    // Allow normal navigation (href-based)
    return true;
});

/* ── Toggle switches sync ───────────────────────────────── */
$(document).on('change', '.cp-switch input', function(){
    var name = $(this).attr('name');
    var val  = $(this).is(':checked') ? 'yes' : 'no';
    // Hidden input sync for form submission
    $('input[name="' + name + '_hidden"]').val(val);
});

})(jQuery);
