console.log('Advanced Reporting JS loaded');

jQuery(function ($) {

    if (typeof SS_ADV === 'undefined') {
        console.error('SS_ADV not defined');
        return;
    }

    let type = 'scans';

    /* ======================
       REPORT TYPE
    ====================== */
    $('.ss-card').on('click', function () {
        $('.ss-card').removeClass('active');
        $(this).addClass('active');
        type = $(this).data('type');
    });

    /* ======================
       PREVIEW
    ====================== */
    $('#ss_preview').on('click', function (e) {
        e.preventDefault();

        $('#ss_output').html('Loading preview...');

        $.post(SS_ADV.ajaxurl, {
            action: 'ss_adv_preview',
            _nonce: SS_ADV.nonce,
            type: type,
            from: $('#ss_from').val(),
            to: $('#ss_to').val()
        })
        .done(function (res) {
            if (res.success) {
                $('#ss_output').html(res.data.html);
            } else {
                $('#ss_output').html('No data');
            }
        })
        .fail(function (xhr) {
            console.error(xhr);
            $('#ss_output').html('Preview failed (' + xhr.status + ')');
        });
    });

    /* ======================
       SAVE BRAND
    ====================== */
    $('#ss-save-brand').on('click', function () {

    $.post(SS_ADV.ajaxurl, {
        action: 'ss_adv_save_brand',
        _nonce: SS_ADV.nonce,
        company: $('#ss_company').val(),
        logo: $('#ss_logo').val()
    })
    .done(() => alert('Brand saved'))
    .fail(xhr => alert('Failed (' + xhr.status + ')'));
});


    /* ======================
       SAVE COMPETITORS
    ====================== */
    $('#ss-save').on('click', function () {
        $.post(SS_ADV.ajaxurl, {
            action: 'ss_save_competitors',
            _nonce: SS_ADV.nonce,
            competitors: $('#ss-competitors').val()
        })
        .done(() => alert('Competitors saved'))
        .fail(xhr => alert('Failed (' + xhr.status + ')'));
    });

    /* ======================
       RUN BENCHMARK
    ====================== */
    $('#ss-run').on('click', function () {

        $('#ss-results').html('Running analysis...');

        $.post(SS_ADV.ajaxurl, {
            action: 'ss_competitive_benchmark',
            _nonce: SS_ADV.nonce
        })
        .done(res => {
            if (res.success) {
                $('#ss-results').html(res.data.html);
            } else {
                $('#ss-results').html('No data');
            }
        })
        .fail(xhr => {
            console.error(xhr);
            $('#ss-results').html('Failed (' + xhr.status + ')');
        });
    });

});
