jQuery(document).ready(function($) {
    'use strict';
    const $adminPage = $('.sifency-admin-page');
    function openModal($modal) {
        $modal.css('display', 'flex');
        setTimeout(() => { $modal.addClass('is-visible'); }, 10);
    }
    function closeModal($modal) {
        $modal.removeClass('is-visible');
        setTimeout(() => { if (!$modal.hasClass('is-visible')) { $modal.css('display', 'none'); } }, 350);
    }

    $adminPage.on('change', '.sifency-status-toggle', function() {
        const $checkbox = $(this);
        const $label = $checkbox.closest('td').find('.status-label');
        const isActive = $checkbox.is(':checked');
        $label.text(isActive ? 'Active' : 'Inactive');
        $.post(sifency_tb_admin.ajax_url, {
            action: 'sifency_toggle_template_status',
            nonce: sifency_tb_admin.nonce,
            template_id: $checkbox.data('template-id'),
            is_active: isActive
        });
    });
    const $conditionsModal = $('#sifency-conditions-modal');
    const $conditionsModalBody = $conditionsModal.find('.sifency-modal-body');
    const $saveConditionsBtn = $('#sifency-save-conditions-btn');
    let currentTemplateId = 0;
    
    $adminPage.on('click', '.sifency-edit-conditions-btn', function(e) {
        e.preventDefault();
        currentTemplateId = $(this).data('template-id');
        $conditionsModalBody.html('<p>' + sifency_tb_admin.i18n.loading + '</p>');
        openModal($conditionsModal);
        $.post(sifency_tb_admin.ajax_url, {
            action: 'sifency_get_display_conditions',
            nonce: sifency_tb_admin.nonce,
            template_id: currentTemplateId
        }).done(response => {
            if (response.success) {
                $conditionsModalBody.html(response.data.html);
                initConditionRows($conditionsModalBody);
            } else {
                $conditionsModalBody.html('<p>' + sifency_tb_admin.i18n.error + '</p>');
            }
        });
    });

    $conditionsModal.on('click', function(e) {
        if ($(e.target).is('.sifency-modal-overlay, .sifency-modal-close')) {
            e.preventDefault();
            closeModal($conditionsModal);
        }
    });

    // Save Conditions
    $saveConditionsBtn.on('click', function(e) {
        e.preventDefault();
        if ($(this).hasClass('disabled')) return;
        $(this).addClass('disabled').find('.spinner').addClass('is-active');
        const conditions = { include: [], exclude: [] };

        $conditionsModal.find('#sifency-include-rules .sifency-condition-row').each(function() { conditions.include.push(serializeConditionRow($(this))); });
        $conditionsModal.find('#sifency-exclude-rules .sifency-condition-row').each(function() { conditions.exclude.push(serializeConditionRow($(this))); });
        $.post(sifency_tb_admin.ajax_url, {
            action: 'sifency_save_display_conditions',
            nonce: sifency_tb_admin.nonce,
            template_id: currentTemplateId,
            conditions: JSON.stringify(conditions)
        }).done(response => {
            if (response.success) {
                $(`.sifency-edit-conditions-btn[data-template-id="${currentTemplateId}"]`).closest('tr').find('.sifency-conditions-summary').text(response.data.summary);
                closeModal($conditionsModal);
            } else { alert(response.data.message || sifency_tb_admin.i18n.error); }
        }).always(() => { $saveConditionsBtn.removeClass('disabled').find('.spinner').removeClass('is-active'); });
    });
    
    $conditionsModal.on('click', '.sifency-add-condition', function(e) {
        e.preventDefault();
        const group = $(this).data('group');
        const $list = $conditionsModal.find('#sifency-' + group + '-rules');
        const $template = $conditionsModal.find('#sifency-condition-row-template').html();
        $list.find('.sifency-no-rules-message').remove();
        const $newRow = $($template);
        $list.append($newRow);
        initSingleConditionRow($newRow);
    });
    $conditionsModal.on('click', '.sifency-remove-condition', function(e) { e.preventDefault(); $(this).closest('.sifency-condition-row').remove(); });
    $conditionsModal.on('change', '.sifency-condition-type', function() { updateSubtypeDropdown($(this).closest('.sifency-condition-row')); });
    $conditionsModal.on('change', '.sifency-condition-subtype', function() { updateValueDropdown($(this).closest('.sifency-condition-row')); });

    const $newTemplateModal = $('#sifency-new-template-modal');
    const $createAndEditBtn = $('#sifency-create-and-edit');
    const $createAndSaveBtn = $('#sifency-create-and-save');

    // Open New Template Modal
    $adminPage.on('click', '#sifency-open-new-template-modal', function(e) { e.preventDefault(); openModal($newTemplateModal); });

    // Close New Template Modal
    $newTemplateModal.on('click', function(e) { if ($(e.target).is('.sifency-modal-overlay, .sifency-modal-close')) { e.preventDefault(); closeModal($newTemplateModal); } });

    // Handle the creation process (Save or Edit)
    $createAndEditBtn.add($createAndSaveBtn).on('click', function(e) {
        e.preventDefault();
        const $button = $(this);
        const shouldEdit = $button.is('#sifency-create-and-edit');
        const title = $('#sifency-template-title').val();
        const type = $('#sifency-template-type').val();
        if (!title.trim()) { alert('Please enter a template name.'); $('#sifency-template-title').focus(); return; }
        if ($button.hasClass('disabled')) return;
        const $buttons = $createAndEditBtn.add($createAndSaveBtn);
        $buttons.addClass('disabled');
        $button.find('.spinner').addClass('is-active');
        $.ajax({
            url: sifency_tb_admin.ajax_url, type: 'POST', dataType: 'json',
            data: { action: 'sifency_create_new_template', title: title, type: type, nonce: sifency_tb_admin.nonce },
            success: function(res) {
                if (res.success) {
                    if (shouldEdit && res.data.edit_url) { window.location.href = res.data.edit_url; } else { location.reload(); }
                } else { alert('Error: ' + (res.data.message || 'An unknown error occurred.')); }
            },
            error: function() { alert('An error occurred during the request. Please try again.'); },
            complete: function() { $buttons.removeClass('disabled'); $button.find('.spinner').removeClass('is-active'); }
        });
    });

const conditionOptions = {
    general: {
        'Entire Site': 'entire_site',
        'Front Page': 'front_page',
        'Search Results': 'search_results',
        '404 Page': 'error_404'
    },
    singular: {
        'All Singular': 'all',
        'All Posts': 'post_type-post',
        'All Pages': 'post_type-page',
        'All Products': 'post_type-product',
        'All Services': 'post_type-service',
        'All Portfolios': 'post_type-portfolio',
        'All Team Members': 'post_type-team',
        'All Events': 'post_type-event',
        'All Careers': 'post_type-career',
        'All Docs': 'post_type-doc',
        'All Digital Goods': 'post_type-digital',
        'All Downloads (EDD)': 'post_type-download',
        'Specific Post...': 'post',
        'Specific Page...': 'page',
        'Specific Product...': 'product',
        'Specific Service...': 'service',
        'Specific Portfolio...': 'portfolio',
        'Specific Team Member...': 'team',
        'Specific Event...': 'event',
        'Specific Career...': 'career',
        'Specific Doc...': 'doc',
        'Specific Digital Good...': 'digital',
        'Specific Download (EDD)...': 'download',
        'Posts in Category...': 'in_category',
        'Posts with Tag...': 'in_tag'
    },
    archive: {
        'All Archives': 'all',
        'Post Archive': 'post_type_archive-post',
        'Page Archive': 'post_type_archive-page',
        'Product Archive (Shop)': 'post_type_archive-product',
        'Service Archive': 'post_type_archive-service',
        'Portfolio Archive': 'post_type_archive-portfolio',
        'Team Archive': 'post_type_archive-team',
        'Event Archive': 'post_type_archive-event',
        'Career Archive': 'post_type_archive-career',
        'Doc Archive': 'post_type_archive-doc',
        'Digital Goods Archive': 'post_type_archive-digital',
        'Download Archive (EDD)': 'post_type_archive-download',
        'Category Archive...': 'category',
        'Tag Archive...': 'tag',
        'Author Archive...': 'author',
        'Date Archive': 'date'
    }
};

function initConditionRows($context) {
    $context.find('.sifency-condition-row').each(function() {
        initSingleConditionRow($(this));
    });
}

function initSingleConditionRow($row) {
    updateSubtypeDropdown($row, $row.data('subtype'));
}

function updateSubtypeDropdown($row, selectedSubtype = null) {
    const type = $row.find('.sifency-condition-type').val();
    const $subtypeSelect = $row.find('.sifency-condition-subtype');
    const options = conditionOptions[type] || {};
    $subtypeSelect.empty();
    $.each(options, (label, value) => {
        $subtypeSelect.append($('<option>', {
            value: value,
            text: label
        }));
    });
    if (selectedSubtype) {
        $subtypeSelect.val(selectedSubtype);
    }
    $subtypeSelect.trigger('change');
}

function updateValueDropdown($row) {
    const subtype = $row.find('.sifency-condition-subtype').val() || '';
    const $valueSelect = $row.find('.sifency-condition-value');

    const needsAjax = [
        'post', 'page', 'in_category', 'category', 'tag', 'author',
        'product', 'service', 'portfolio', 'team', 'event', 'career', 'doc', 'download', 'digital',
    ];
    
    let searchType = subtype;

    if (subtype.startsWith('post_type-') || subtype.startsWith('post_type_archive-')) {
        searchType = '';
    }

    if (needsAjax.includes(searchType)) {
        $valueSelect.show().select2({
            width: 'style',
            dropdownParent: $conditionsModal,
            ajax: {
                url: sifency_tb_admin.ajax_url,
                dataType: 'json',
                delay: 250,
                data: params => ({
                    action: 'sifency_search_posts_terms',
                    nonce: sifency_tb_admin.nonce,
                    search_type: searchType,
                    q: params.term
                }),
                processResults: data => ({
                    results: data.data
                }),
            }
        });
    } else {
        if ($valueSelect.data('select2')) {
            $valueSelect.select2('destroy');
        }
        $valueSelect.hide();
    }
}

function serializeConditionRow($row) {
    let subtype = $row.find('.sifency-condition-subtype').val() || '';
    let value = $row.find('.sifency-condition-value').val() || '';
    if (subtype.startsWith('post_type-')) {
        value = subtype.split('-')[1];
        subtype = 'post_type';
    } else if (subtype.startsWith('post_type_archive-')) {
        value = subtype.split('-')[1];
        subtype = 'post_type_archive';
    }
    return {
        type: $row.find('.sifency-condition-type').val(),
        subtype: subtype,
        value: value,
    };
}


});