(function($){'use strict';

/* Tab switching */
$(document).on('click','.epwf-tab-btn',function(){
    var t=$(this).data('tab');
    $('.epwf-tab-btn').removeClass('is-active');
    $('.epwf-tab-panel').removeClass('is-active');
    $(this).addClass('is-active');
    $('#epwf-tab-'+t).addClass('is-active');
});

/* Model row highlight */
$(document).on('change','.epwf-model-radio',function(){
    $('.epwf-model-row').removeClass('is-active').find('.epwf-active-tick').remove();
    var $r=$(this).closest('.epwf-model-row').addClass('is-active');
    $r.append('<span class="epwf-active-tick">✓</span>');
});

/* Style card highlight */
$(document).on('change','.epwf-style-radio',function(){
    $('.epwf-style-card').removeClass('is-active').find('.epwf-style-active').remove();
    var $c=$(this).closest('.epwf-style-card').addClass('is-active');
    $c.append('<div class="epwf-style-active">Active</div>');
});

/* Hook radio → mockup + code preview */
function hookUI(v){
    $('.epwf-hook-item').removeClass('is-active').find('.epwf-active-badge').remove();
    var $it=$('input.epwf-hook-radio[value="'+v+'"]').closest('.epwf-hook-item').addClass('is-active');
    $it.append('<span class="epwf-active-badge">Active</span>');
    $('.epwf-mz').removeClass('is-active');
    $('.epwf-mz[data-hook="'+v+'"]').addClass('is-active');
    var p=$('#epwf-priority').val()||10;
    $('#epwf-hook-code').text("add_action( '"+v+"', 'render_faq', "+p+" );");
}
var $checkedHook=$('input.epwf-hook-radio:checked');
if($checkedHook.length)hookUI($checkedHook.val());
$(document).on('change','.epwf-hook-radio',function(){hookUI($(this).val());});
$('#epwf-priority').on('input',function(){hookUI($('input.epwf-hook-radio:checked').val()||'');});

/* Font ranges */
$('#epwf-qfont-range').on('input',function(){$('#epwf-qfont-val').text($(this).val()+'px');$(this).attr('aria-valuenow',$(this).val());});
$('#epwf-afont-range').on('input',function(){$('#epwf-afont-val').text($(this).val()+'px');$(this).attr('aria-valuenow',$(this).val());});
/* Spacing ranges */
$('.epwf-spacing-range').on('input',function(){var out=$(this).data('out');$('#'+out).text($(this).val()+'px');$(this).attr('aria-valuenow',$(this).val());});

/* ── Provider ↔ Model dropdown sync ───────────────────────────────── */
function epwfSyncModels(provider){
    var $sel=$('#epwf-model-select');
    var saved=$sel.val();
    $sel.empty();
    $('#epwf-model-options-store [data-provider="'+provider+'"] option').each(function(){
        $sel.append($(this).clone());
    });
    // restore saved value if it belongs to this provider
    if($sel.find('option[value="'+saved+'"]').length){$sel.val(saved);}
}
function epwfSyncKeys(provider){
    $('.epwf-key-field').hide().filter('[data-provider="'+provider+'"]').show();
}
(function(){
    var init=$('#epwf-provider-select').val();
    if(init){epwfSyncModels(init);epwfSyncKeys(init);}
    $('#epwf-provider-select').on('change',function(){
        var p=$(this).val();
        epwfSyncModels(p);
        epwfSyncKeys(p);
    });
})();


/* Color picker + swatch sync */
if($.fn.wpColorPicker){
    $('.epwf-color-picker').wpColorPicker({
        change:function(e,ui){
            var hex=ui.color.toString();
            var key=$(this).data('key');
            $('#swatch-'+key).css('background',hex);
        },
        clear:function(){
            var key=$(this).closest('.epwf-color-item').find('.epwf-color-picker').data('key');
            $('#swatch-'+key).css('background','transparent');
        }
    });
    /* hide legacy swatch divs — wp-color-result button is the swatch now */
    $('.epwf-color-list .epwf-color-swatch').hide();
}

/* Show/hide API key */
$(document).on('click','.epwf-show-key',function(){
    var $i=$(this).prev('.epwf-key-input');
    $i.attr('type',$i.attr('type')==='password'?'text':'password');
});

/* AJAX regenerate */
$(document).on('click','#epwf-regen',function(){
    var $b=$(this),pid=$b.data('pid'),$msg=$('.epwf-gen-msg'),$spin=$('.epwf-spin');
    $b.prop('disabled',true);$spin.addClass('is-active');
    $msg.css('color','#374151').text(epwfAdmin.generating);
    $.post(epwfAdmin.ajax,{action:'epwf_regenerate',nonce:epwfAdmin.nonce,pid:pid},function(res){
        $b.prop('disabled',false);$spin.removeClass('is-active');
        if(res.success){
            $msg.css('color','#16a34a').removeClass('epwf-notice-box').text(res.data.msg);
            $('#epwf-rows').html(res.data.html);
            $('.epwf-mb-count').text(res.data.count+' FAQs');
        }else{
            var errMsg=res.data&&res.data.msg?res.data.msg:epwfAdmin.err;
            var noticeType=res.data&&res.data.notice_type?res.data.notice_type:'error';
            var icons={'invalid_key':'🔑','quota_exceeded':'📊','timeout':'⏱','malformed':'⚠️','rate_limit':'🚦','error':'❌'};
            var labels={'invalid_key':'Invalid API Key','quota_exceeded':'Quota Exceeded','timeout':'Request Timed Out','malformed':'Malformed Response','rate_limit':'Rate Limited','error':'Error'};
            var icon=icons[noticeType]||'❌';
            var label=labels[noticeType]||'Error';
            $msg.addClass('epwf-notice-box epwf-notice-'+noticeType)
                .html('<strong>'+icon+' '+label+':</strong> '+errMsg);
        }
    }).fail(function(){$b.prop('disabled',false);$spin.removeClass('is-active');
        $msg.addClass('epwf-notice-box epwf-notice-timeout').html('<strong>⏱ Connection Error:</strong> '+epwfAdmin.err);
    });
});

/* Add FAQ row */
var ri=$('#epwf-rows .epwf-faq-row').length;
$(document).on('click','#epwf-add-row',function(){
    var tpl=$('#epwf-row-tpl').html();if(!tpl)return;
    tpl=tpl.replace(/__IDX__/g,ri++);
    $('#epwf-rows .epwf-empty-msg').remove();
    $('#epwf-rows').append(tpl);
});

/* Remove FAQ row */
$(document).on('click','.epwf-del-row',function(){
    if(confirm(epwfAdmin.confirm_del))$(this).closest('.epwf-faq-row').remove();
});

}(jQuery));

/* Source: assets/js/admin.js — unminified for readability.
   For production, minify with: npx terser admin.js -o admin.min.js */
