(function($){
      // Add new attribute
    $('#camanager-addRow').on('click', function (e) {
        e.preventDefault();

        // only look inside the add form
        const selector = $('#camanager-attribute-form #camanager-selector').val();
        const attr = $('#camanager-attribute-form #camanager-attr').val();
        const value = $('#camanager-attribute-form #camanager-value').val();

        if (!selector || !attr || !value) {
            alert('All fields are required.');
            return;
        }

        $.post(camVars.ajaxurl, {
            action: 'camanager_save_attribute',
            selector: selector,
            attr: attr,
            value: value,
            _ajax_nonce: camVars.nonce
        }, function (resp) {
            if (resp.success) {
                const url = new URL(window.location.href);
                url.searchParams.set('camanager_notice', 'added');
                window.location.href = url.toString();
            } else {
                 if (resp.data && resp.data.upgrade_url) {
                    alert(resp.data.message);
                    window.open(resp.data.upgrade_url, '_blank');
                } else {
                    alert(resp.data || 'Error saving attribute.');
                }
            }
        });
    });


    // Delete attribute
    $(document).on('click', '.camanager-remove-attribute', function () {
        if (!confirm('Delete this attribute?')) return;
        const row = $(this).closest('tr');
        const id = row.data('id');

        $.post(camVars.ajaxurl, {
            action: 'camanager_remove_attribute',
            id: id,
            _ajax_nonce: camVars.nonce
        }, function (resp) {
            if (resp.success) {
                const url = new URL(window.location.href);
                url.searchParams.set('camanager_notice', 'deleted');
                window.location.href = url.toString();
            } else {
                alert(resp.data || 'Error deleting attribute.');
            }
        });
    });

    // Edit attribute (inline editing with dropdown for attr)
    $(document).on('click', '.camanager-edit-attribute', function () {
        const row = $(this).closest('tr');

        // Make existing dropdown editable
        row.find('.camanager-edit-attr').prop('disabled', false);

        // Replace selector and value with inputs
        const selector = row.find('.selector').text().trim();
        const value = row.find('.value').text().trim();

        row.find('.selector').html('<input type="text" class="edit-selector" value="'+selector+'" />');
        row.find('.value').html('<input type="text" class="edit-value" value="'+value+'" />');

        // Switch button to Save mode
        $(this)
            .text('Update')
            .removeClass('camanager-edit-attribute')
            .addClass('camanager-save-edit');
    });


    // Save edited attribute
    $(document).on('click', '.camanager-save-edit', function () {
        const row = $(this).closest('tr');
        const id = row.data('id');
        const selector = row.find('.edit-selector').val();
        const attr = row.find('.camanager-edit-attr').val();
        const value = row.find('.edit-value').val();

        if (!selector || !attr || !value) {
            alert('All fields are required.');
            return;
        }

        $.post(camVars.ajaxurl, {
            action: 'camanager_update_attribute',
            id: id,
            selector: selector,
            attr: attr,
            value: value,
            _ajax_nonce: camVars.nonce
        }, function (resp) {
            if (resp.success) {
                const url = new URL(window.location.href);
                url.searchParams.set('camanager_notice', 'updated');
                window.location.href = url.toString();
            } else {
                alert(resp.data || 'Error updating attribute.');
            }
        });
    });

    setTimeout(function(){
        $('.notice.camanager-alert-box').fadeOut('slow');
    }, 10000);

    const url = new URL(window.location.href);
    if (url.searchParams.has('camanager_notice') ||
        url.searchParams.has('imported_count')) {
        url.searchParams.delete('camanager_notice');
        url.searchParams.delete('imported_count');
        window.history.replaceState({}, document.title, url.pathname + url.search);
    }

     $('#toplevel_page_camanager-attributes')
        .find('a[href="https://customattributesmanager.com/support"]')
        .attr('target', '_blank');

    // ===============================================================
    // CSV Import (Pro only)
    // ===============================================================

    let offset = 0;
    let file = null;
    let isRunning = false;

    $('#camanager-import-btn').on('click', function (e) {
        e.preventDefault();
        $('#camanager-import-file').trigger('click');
    });

    $('#camanager-import-file').on('change', function (e) {
       
        file = this.files[0];

        if (!file) {
            alert('Please select a CSV file');
            return;
        }

        if (!file.name.toLowerCase().endsWith('.csv')) {
            alert('Please upload a valid CSV file.');
            $(this).val('');
            return;
        }

        offset = 0;
        isRunning = true;

        importChunk();
    });

    function importChunk() {
        if (!isRunning) return;

        const formData = new FormData();
        formData.append('action', 'camanager_import_csv');
        formData.append('_ajax_nonce', camVars.nonce);
        formData.append('csv', file);
        formData.append('offset', offset);

        $.ajax({
            url: camVars.ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success(response) {
                if (!response.success) {
                    alert(response.data?.message || 'CSV Import failed');
                    isRunning = false;
                    window.open(resp.data?.upgrade_url, '_blank');
                    return;
                }

                offset = response.data.next_offset;
                if (response.data.done) {
                    isRunning = false;
                    const url = new URL(window.location.href);
                    url.searchParams.set('camanager_notice', 'imported');
                    url.searchParams.set('imported_count', response.data.imported);
                    window.location.href = url.toString();
                }
                // Continue next chunk
                importChunk();
            },
            error() {
                alert('Server error during import');
                isRunning = false;
            }
        });
    }

    // ===============================================================
    // Toggle import/export dropdown
    // ===============================================================
    $('.camanager-dropdown-toggle').on('click', function() {
        $(this).next('.camanager-dropdown-menu').toggle();
    });
    // Hide dropdown when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.camanager-dropdown').length) {
            $('.camanager-dropdown-menu').hide();
        }
    });

    // ===============================================================
    // Toggle Table Selection and Bulk Delete
    // ===============================================================
    // Select all rows
    $('#camanager-select-all').on('change', function () {
        const checked = $(this).is(':checked');
        $('.camanager-row-checkbox').prop('checked', checked);
        toggleBulkDeleteButton();
    });

    // Individual checkbox toggle
    $(document).on('change', '.camanager-row-checkbox', function () {
        toggleBulkDeleteButton();
    });

    // Enable / disable bulk delete button
    function toggleBulkDeleteButton() {
        const anyChecked = $('.camanager-row-checkbox:checked').length > 0;
        $('#camanager-delete-selected').prop('disabled', !anyChecked);
    }
    
    // ===============================================================
    //  BULK DELETE CLICK
    // ===============================================================
    $('#camanager-delete-selected').on('click', function () {

        const ids = $('.camanager-row-checkbox:checked')
            .map(function () {
                return $(this).val();
            }).get();

        if (!ids.length) {
            return;
        }

        if (!confirm('Delete selected attributes? This cannot be undone.')) {
            return;
        }

        $.post(camVars.ajaxurl, {
            action: 'camanager_bulk_delete',
            ids: ids,
            _ajax_nonce: camVars.nonce
        }, function (resp) {

            if (resp.success) {
                const url = new URL(window.location.href);
                url.searchParams.set('camanager_notice', 'deleted');
                window.location.href = url.toString();
            } else {
                alert(resp.data || 'Bulk delete failed.');
            }
        });
    });


})(jQuery);
