/**
 * AI Content Generator - Admin Scripts
 */

(function ($) {
    'use strict';

    // Toast Notification System
    function showToast(message, type) {
        type = type || 'info';
        var container = $('#roidaico-toast-container');
        if (container.length === 0) {
            $('body').append('<div id="roidaico-toast-container"></div>');
            container = $('#roidaico-toast-container');
        }
        var icon = 'info';
        if (type === 'success') icon = 'yes';
        else if (type === 'error') icon = 'dismiss';
        else if (type === 'warning') icon = 'warning';
        
        var toast = $('<div class="roidaico-toast roidaico-toast-' + type + '">' +
            '<span class="roidaico-toast-icon dashicons dashicons-' + icon + '"></span>' +
            '<div class="roidaico-toast-message">' + escapeHtml(message) + '</div>' +
            '<button class="roidaico-toast-close">&times;</button>' +
            '</div>');
            
        container.append(toast);
        
        // Trigger reflow
        toast[0].offsetHeight;
        toast.addClass('show');
        
        // Auto dismiss
        var dismissTimeout = setTimeout(function() {
            toast.removeClass('show');
            setTimeout(function() {
                toast.remove();
            }, 300);
        }, 5000);
        
        toast.find('.roidaico-toast-close').on('click', function() {
            clearTimeout(dismissTimeout);
            toast.removeClass('show');
            setTimeout(function() {
                toast.remove();
            }, 300);
        });
    }

    // Initialize Select2
    function initSelect2($el) {
        if (typeof $.fn.select2 !== 'undefined') {
            $el = $el || $('.roidaico-select2');
            if ($el.length > 0) {
                // Force destruction of existing instance to avoid double initialization
                if ($el.hasClass('select2-hidden-accessible')) {
                    $el.select2('destroy');
                }
                $el.select2({
                    width: '350px',
                    minimumResultsForSearch: 0
                });
            }
        }
    }

    // Filter categories by language
    function filterCategoriesByLanguage(langSelectSelector, categorySelectSelector) {
        var langSelect = $(langSelectSelector);
        var categorySelect = $(categorySelectSelector);
        
        if (!langSelect.length || !categorySelect.length) {
            return;
        }

        // Cache original options if not already cached
        var originalOptions = categorySelect.data('original-options');
        if (!originalOptions) {
            originalOptions = categorySelect.find('option').clone();
            categorySelect.data('original-options', originalOptions);
        }

        function updateOptions() {
            var selectedLang = langSelect.val();
            var currentValue = categorySelect.val();
            
            categorySelect.empty();
            
            originalOptions.each(function() {
                var option = $(this).clone();
                var optionLang = option.data('lang');
                
                // Always show the default placeholder or "All Categories" option if value is empty
                if (option.val() === '') {
                    categorySelect.append(option);
                    return;
                }
                
                // If no language is selected (e.g. "All Languages"), show all categories
                // Otherwise, show only categories matching the selected language
                if (!selectedLang || !optionLang || optionLang === selectedLang) {
                    categorySelect.append(option);
                }
            });

            // Restore previous value if it's still available in the filtered list
            if (categorySelect.find('option[value="' + currentValue + '"]').length > 0) {
                categorySelect.val(currentValue);
            } else {
                // Otherwise select the first option
                categorySelect.find('option').first().prop('selected', true);
            }
            
            // Trigger change event to notify Select2 if initialized
            if (categorySelect.hasClass('select2-hidden-accessible')) {
                categorySelect.trigger('change.select2');
            }
        }

        langSelect.on('change', updateOptions);
        updateOptions(); // run initially
    }

    $(document).ready(function () {
        initSelect2();

        // Filter categories by language dynamically
        filterCategoriesByLanguage('#add-language', '#add-category');
        filterCategoriesByLanguage('#gen-language', '#gen-category');
        filterCategoriesByLanguage('select[name="language"]', 'select[name="category"]');

        // Toggle provider sections in settings page
        $(document).on('change', '#roidaico_ai_provider', function () {
            var val = $(this).val();
            if (val === 'wp_ai_client') {
                $('.roidaico-provider-section-openrouter').slideUp(200);
                $('.roidaico-provider-section-wp-ai-client').slideDown(200);
                $('.roidaico-guide-section-openrouter').slideUp(200);
                $('.roidaico-guide-note-openrouter').slideUp(200);
            } else {
                $('.roidaico-provider-section-openrouter').slideDown(200);
                $('.roidaico-provider-section-wp-ai-client').slideUp(200);
                $('.roidaico-guide-section-openrouter').slideDown(200);
                $('.roidaico-guide-note-openrouter').slideDown(200);
            }
        });

        // Toggle AI image model row in content settings
        $(document).on('change', '#roidaico_image_source', function () {
            var val = $(this).val();
            if (val === 'ai') {
                $('.roidaico-ai-image-model-row').slideDown(200);
            } else {
                $('.roidaico-ai-image-model-row').slideUp(200);
            }
        });
    });

    // Modal handling
    function openModal(modalId) {
        $(modalId).fadeIn(200);
    }

    function closeModal(modalId) {
        $(modalId).fadeOut(200);
    }

    // Close modal when clicking X or outside
    $(document).on('click', '.roidaico-modal-close', function () {
        $(this).closest('.roidaico-modal').fadeOut(200);
    });

    $(document).on('click', '.roidaico-modal', function (e) {
        if ($(e.target).hasClass('roidaico-modal')) {
            $(this).fadeOut(200);
        }
    });

    // Toggle password visibility
    $(document).on('click', '.roidaico-toggle-password', function () {
        var input = $(this).siblings('input');
        var icon = $(this).find('.dashicons');

        if (input.attr('type') === 'password') {
            input.attr('type', 'text');
            icon.removeClass('dashicons-visibility').addClass('dashicons-hidden');
        } else {
            input.attr('type', 'password');
            icon.removeClass('dashicons-hidden').addClass('dashicons-visibility');
        }
    });

    // Test API connection
    $(document).on('click', '.roidaico-test-api', function () {
        var btn = $(this);
        var apiType = btn.data('api');
        var apiKey = btn.siblings('input').val();
        var statusEl = $('#' + apiType + '-status');

        btn.prop('disabled', true).text(aicgAdmin.strings.generating);
        statusEl.removeClass('success error').text('');

        $.ajax({
            url: aicgAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'roidaico_test_api',
                nonce: aicgAdmin.nonce,
                api_type: apiType,
                api_key: apiKey
            },
            success: function (response) {
                if (response.success) {
                    statusEl.addClass('success').text(response.data);

                    // If OpenRouter, load models immediately
                    if (apiType === 'openrouter') {
                        loadModels(apiKey);
                    }
                } else {
                    statusEl.addClass('error').text(response.data);
                }
            },
            error: function () {
                statusEl.addClass('error').text(aicgAdmin.strings.error);
            },
            complete: function () {
                btn.prop('disabled', false).text('Test Connection');
            }
        });
    });

    // Keywords Page
    // Add keyword modal
    $('#roidaico-add-keyword-btn').on('click', function () {
        openModal('#roidaico-add-keyword-modal');
    });

    // Add keyword form (supports multiple keywords)
    $('#roidaico-add-keyword-form').on('submit', function (e) {
        e.preventDefault();

        var form = $(this);
        var btn = form.find('button[type="submit"]');
        var rawInput = $('#add-keywords').val();
        var categoryId = $('#add-category').val();
        var language = $('#add-language').val();
        var translationOf = $('#add-translation-of').val();

        // Parse keywords: split by newline or comma, trim whitespace, remove empty
        var keywords = rawInput
            .split(/[\n,]+/)
            .map(function (k) { return k.trim(); })
            .filter(function (k) { return k.length > 0; });

        if (keywords.length === 0) {
            showToast('Please enter at least one keyword.', 'warning');
            return;
        }

        btn.prop('disabled', true).text(aicgAdmin.strings.saving);

        // Add keywords one by one
        var added = 0;
        var errors = [];

        function addNextKeyword(index) {
            if (index >= keywords.length) {
                if (added > 0) {
                    location.reload();
                } else {
                    showToast('Failed to add keywords: ' + errors.join(', '), 'error');
                    btn.prop('disabled', false).text('Add to Queue');
                }
                return;
            }

            $.ajax({
                url: aicgAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'roidaico_add_keyword',
                    nonce: aicgAdmin.nonce,
                    keyword: keywords[index],
                    category_id: categoryId,
                    language: language,
                    translation_of: translationOf
                },
                success: function (response) {
                    if (response.success) {
                        added++;
                    } else {
                        errors.push(keywords[index]);
                    }
                    addNextKeyword(index + 1);
                },
                error: function () {
                    errors.push(keywords[index]);
                    addNextKeyword(index + 1);
                }
            });
        }

        addNextKeyword(0);
    });

    // Generate keywords modal
    $('#roidaico-generate-keywords-btn').on('click', function () {
        openModal('#roidaico-generate-keywords-modal');
    });

    // Generate keywords form
    $('#roidaico-generate-keywords-form').on('submit', function (e) {
        e.preventDefault();

        var btn = $('#roidaico-generate-btn');
        var modal = $('#roidaico-generate-keywords-modal .roidaico-modal-content');
        var language = $('#gen-language').val();

        // Show loading overlay
        if (!modal.find('.roidaico-loading-overlay').length) {
            modal.append(
                '<div class="roidaico-loading-overlay">' +
                '<div class="roidaico-loading-spinner"></div>' +
                '<div class="roidaico-loading-text">Generating keywords with AI...</div>' +
                '<div class="roidaico-loading-subtext">This may take 10-30 seconds. Please wait.</div>' +
                '</div>'
            );
        }
        modal.find('.roidaico-loading-overlay').fadeIn(200);

        btn.prop('disabled', true).text(aicgAdmin.strings.generating);

        $.ajax({
            url: aicgAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'roidaico_generate_keywords',
                nonce: aicgAdmin.nonce,
                topic: $('#gen-topic').val(),
                count: $('#gen-count').val(),
                category_id: $('#gen-category').val(),
                language: language
            },
            success: function (response) {
                modal.find('.roidaico-loading-overlay').fadeOut(200);
                if (response.success) {
                    var keywordsList = $('#roidaico-keywords-list');
                    keywordsList.empty();

                    response.data.keywords.forEach(function (keyword, index) {
                        keywordsList.append(
                            '<label><input type="checkbox" name="selected_keywords[]" value="' +
                            escapeHtml(keyword) + '" checked> ' + escapeHtml(keyword) + '</label>'
                        );
                    });

                    $('#roidaico-generated-keywords').show();
                    $('#roidaico-add-selected-btn').show();
                } else {
                    showToast(response.data, 'error');
                }
            },
            error: function () {
                modal.find('.roidaico-loading-overlay').fadeOut(200);
                showToast(aicgAdmin.strings.error, 'error');
            },
            complete: function () {
                btn.prop('disabled', false).text('Generate Keywords');
            }
        });
    });

    // Add selected keywords to queue
    $('#roidaico-add-selected-btn').on('click', function () {
        var btn = $(this);
        var selectedKeywords = [];
        var categoryId = $('#gen-category').val();
        var language = $('#gen-language').val();

        $('input[name="selected_keywords[]"]:checked').each(function () {
            selectedKeywords.push($(this).val());
        });

        if (selectedKeywords.length === 0) {
            showToast('Please select at least one keyword.', 'warning');
            return;
        }

        btn.prop('disabled', true).text(aicgAdmin.strings.saving);

        // Add keywords one by one (simple approach)
        var added = 0;
        var errors = [];

        function addNextKeyword(index) {
            if (index >= selectedKeywords.length) {
                if (added > 0) {
                    location.reload();
                } else {
                    showToast('Failed to add keywords: ' + errors.join(', '), 'error');
                    btn.prop('disabled', false).text('Add Selected to Queue');
                }
                return;
            }

            $.ajax({
                url: aicgAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'roidaico_add_keyword',
                    nonce: aicgAdmin.nonce,
                    keyword: selectedKeywords[index],
                    category_id: categoryId,
                    language: language
                },
                success: function (response) {
                    if (response.success) {
                        added++;
                    } else {
                        errors.push(selectedKeywords[index]);
                    }
                    addNextKeyword(index + 1);
                },
                error: function () {
                    errors.push(selectedKeywords[index]);
                    addNextKeyword(index + 1);
                }
            });
        }

        addNextKeyword(0);
    });

    // Generate content from keyword
    $(document).on('click', '.roidaico-generate-content-btn', function () {
        var btn = $(this);
        var keywordId = btn.data('id');

        if (!confirm('Generate content for this keyword? This will use API credits.')) {
            return;
        }

        btn.prop('disabled', true).text(aicgAdmin.strings.generating);

        $.ajax({
            url: aicgAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'roidaico_generate_content',
                nonce: aicgAdmin.nonce,
                keyword_id: keywordId
            },
            success: function (response) {
                if (response.success) {
                    showToast(response.data.message, 'success');
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    showToast(response.data, 'error');
                    btn.prop('disabled', false).text('Generate');
                }
            },
            error: function () {
                showToast(aicgAdmin.strings.error, 'error');
                btn.prop('disabled', false).text('Generate');
            }
        });
    });

    // Delete keyword
    $(document).on('click', '.roidaico-delete-keyword-btn', function () {
        var btn = $(this);
        var keywordId = btn.data('id');

        if (!confirm(aicgAdmin.strings.confirmDelete)) {
            return;
        }

        $.ajax({
            url: aicgAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'roidaico_delete_keyword',
                nonce: aicgAdmin.nonce,
                keyword_id: keywordId
            },
            success: function (response) {
                if (response.success) {
                    btn.closest('tr').fadeOut(300, function () {
                        $(this).remove();
                    });
                } else {
                    showToast(response.data, 'error');
                }
            },
            error: function () {
                showToast(aicgAdmin.strings.error, 'error');
            }
        });
    });

    // Translate keyword button clicked
    $(document).on('click', '.roidaico-translate-keyword-btn', function () {
        var btn = $(this);
        var keywordId = btn.data('id');
        var keywordText = btn.data('keyword');
        var sourceLang = btn.data('lang');

        $('#trans-source-id').val(keywordId);
        $('#trans-original-text').text(keywordText);
        $('#trans-manual-text').val('');
        $('#trans-method').val('ai');
        $('#trans-manual-row').hide();

        // Hide source language option in target language select
        $('#trans-target-lang option').show();
        if (sourceLang) {
            $('#trans-target-lang option[value="' + sourceLang + '"]').hide();
            // If the hidden language was selected, select the first visible option
            if ($('#trans-target-lang').val() === sourceLang) {
                $('#trans-target-lang option').filter(function() {
                    return $(this).css('display') !== 'none';
                }).first().prop('selected', true);
            }
        }

        openModal('#roidaico-translate-keyword-modal');
    });

    // Click on missing translation badge (+)
    $(document).on('click', '.roidaico-add-translation-badge', function (e) {
        e.preventDefault();
        var btn = $(this);
        var keywordId = btn.data('id');
        var keywordText = btn.data('keyword');
        var targetLang = btn.data('lang');

        // Find parent row to get the source language
        var parentRow = btn.closest('tr');
        var sourceLang = parentRow.length ? (parentRow.data('id') ? parentRow.find('.roidaico-lang-badge.original').text().trim().toLowerCase() : '') : '';

        $('#trans-source-id').val(keywordId);
        $('#trans-original-text').text(keywordText);
        $('#trans-manual-text').val('');
        $('#trans-method').val('ai');
        $('#trans-manual-row').hide();

        // Hide source language option in target language select
        $('#trans-target-lang option').show();
        if (sourceLang) {
            $('#trans-target-lang option[value="' + sourceLang + '"]').hide();
        }

        $('#trans-target-lang').val(targetLang);

        openModal('#roidaico-translate-keyword-modal');
    });

    // Toggle manual translation field
    $('#trans-method').on('change', function () {
        if ($(this).val() === 'manual') {
            $('#trans-manual-row').slideDown(200);
            $('#trans-manual-text').prop('required', true);
        } else {
            $('#trans-manual-row').slideUp(200);
            $('#trans-manual-text').prop('required', false);
        }
    });

    // Handle translation submission
    $('#roidaico-translate-keyword-form').on('submit', function (e) {
        e.preventDefault();

        var form = $(this);
        var btn = $('#roidaico-submit-translate-btn');
        var sourceId = $('#trans-source-id').val();
        var targetLang = $('#trans-target-lang').val();
        var method = $('#trans-method').val();
        var manualText = $('#trans-manual-text').val();

        var parentRow = $('tr[data-id="' + sourceId + '"]');
        var categoryId = parentRow.length ? (parentRow.data('category-id') || 0) : 0;

        btn.prop('disabled', true).text('Saving...');

        if (method === 'ai') {
            // Translate with AI
            // Show loading state
            var modal = $('#roidaico-translate-keyword-modal .roidaico-modal-content');
            if (!modal.find('.roidaico-loading-overlay').length) {
                modal.append(
                    '<div class="roidaico-loading-overlay">' +
                    '<div class="roidaico-loading-spinner"></div>' +
                    '<div class="roidaico-loading-text">Translating keyword with AI...</div>' +
                    '<div class="roidaico-loading-subtext">Please wait.</div>' +
                    '</div>'
                );
            }
            modal.find('.roidaico-loading-overlay').fadeIn(200);

            $.ajax({
                url: aicgAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'roidaico_translate_keyword_ai',
                    nonce: aicgAdmin.nonce,
                    keyword_id: sourceId,
                    target_lang: targetLang
                },
                success: function (response) {
                    modal.find('.roidaico-loading-overlay').fadeOut(200);
                    if (response.success) {
                        showToast(response.data.message, 'success');
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                    } else {
                        showToast(response.data, 'error');
                        btn.prop('disabled', false).text('Create Translation');
                    }
                },
                error: function () {
                    modal.find('.roidaico-loading-overlay').fadeOut(200);
                    showToast(aicgAdmin.strings.error || 'An error occurred', 'error');
                    btn.prop('disabled', false).text('Create Translation');
                }
            });
        } else {
            // Manual translation
            if (!manualText.trim()) {
                showToast('Please enter the translated keyword.', 'warning');
                btn.prop('disabled', false).text('Create Translation');
                return;
            }

            $.ajax({
                url: aicgAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'roidaico_add_keyword',
                    nonce: aicgAdmin.nonce,
                    keyword: manualText,
                    category_id: categoryId,
                    language: targetLang,
                    translation_of: sourceId
                },
                success: function (response) {
                    if (response.success) {
                        showToast('Translation added to queue.', 'success');
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                    } else {
                        showToast(response.data, 'error');
                        btn.prop('disabled', false).text('Create Translation');
                    }
                },
                error: function () {
                    showToast(aicgAdmin.strings.error || 'An error occurred', 'error');
                    btn.prop('disabled', false).text('Create Translation');
                }
            });
        }
    });

    // Select all keywords
    $('#select-all-keywords').on('change', function () {
        $('input[name="keyword_ids[]"]').prop('checked', $(this).is(':checked'));
    });

    // Bulk actions
    $(document).on('click', '.do-bulk-action', function (e) {
        e.preventDefault();
        var btn = $(this);
        var nav = btn.closest('.tablenav');
        var action = nav.find('.bulk-action-selector').val();
        var selectedIds = [];
        var selectedLangs = [];

        $('input[name="keyword_ids[]"]:checked').each(function () {
            selectedIds.push($(this).val());
            var lang = $(this).data('lang');
            if (lang && selectedLangs.indexOf(lang) === -1) {
                selectedLangs.push(lang);
            }
        });

        if (!action || selectedIds.length === 0) {
            showToast('Please select an action and at least one keyword.', 'warning');
            return;
        }

        if (action === 'delete') {
            if (!confirm('Delete ' + selectedIds.length + ' keywords?')) {
                return;
            }
            // Delete keywords
            var deleted = 0;
            function deleteNext(index) {
                if (index >= selectedIds.length) {
                    location.reload();
                    return;
                }
                $.ajax({
                    url: aicgAdmin.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'roidaico_delete_keyword',
                        nonce: aicgAdmin.nonce,
                        keyword_id: selectedIds[index]
                    },
                    success: function() {
                        deleted++;
                        deleteNext(index + 1);
                    },
                    error: function() {
                        deleteNext(index + 1);
                    }
                });
            }
            deleteNext(0);
        }

        if (action === 'generate') {
            if (!confirm('Generate content for ' + selectedIds.length + ' keywords? This will use API credits.')) {
                return;
            }
            
            // Show loading indicator
            showToast('Generating content for ' + selectedIds.length + ' keywords...', 'info');
            btn.prop('disabled', true).text('Generating...');
            
            var generated = 0;
            function generateNext(index) {
                if (index >= selectedIds.length) {
                    showToast('Bulk generation complete: ' + generated + ' succeeded.', 'success');
                    setTimeout(function() {
                        location.reload();
                    }, 2000);
                    return;
                }
                $.ajax({
                    url: aicgAdmin.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'roidaico_generate_content',
                        nonce: aicgAdmin.nonce,
                        keyword_id: selectedIds[index]
                    },
                    success: function(response) {
                        if (response.success) {
                            generated++;
                        }
                        generateNext(index + 1);
                    },
                    error: function() {
                        generateNext(index + 1);
                    }
                });
            }
            generateNext(0);
        }

        if (action === 'translate') {
            $('#bulk-trans-count').text(selectedIds.length);
            
            // Hide the shared language from the target dropdown if all selected keywords have the same language
            $('#bulk-trans-target-lang option').show();
            if (selectedLangs.length === 1) {
                var sharedLang = selectedLangs[0];
                $('#bulk-trans-target-lang option[value="' + sharedLang + '"]').hide();
                // If the hidden option was selected, switch to 'all' or another visible option
                if ($('#bulk-trans-target-lang').val() === sharedLang) {
                    $('#bulk-trans-target-lang').val('all');
                }
            } else {
                // If keywords have different languages, default to 'all'
                $('#bulk-trans-target-lang').val('all');
            }
            
            openModal('#roidaico-bulk-translate-modal');
        }
    });

    // Handle bulk translation submission
    $('#roidaico-bulk-translate-form').on('submit', function (e) {
        e.preventDefault();

        var btn = $('#roidaico-submit-bulk-translate-btn');
        var targetLang = $('#bulk-trans-target-lang').val();
        var selectedIds = [];

        $('input[name="keyword_ids[]"]:checked').each(function () {
            selectedIds.push($(this).val());
        });

        if (selectedIds.length === 0) {
            showToast('No keywords selected.', 'warning');
            return;
        }

        btn.prop('disabled', true).text('Translating...');

        // Show loading state
        var modal = $('#roidaico-bulk-translate-modal .roidaico-modal-content');
        if (!modal.find('.roidaico-loading-overlay').length) {
            modal.append(
                '<div class="roidaico-loading-overlay">' +
                '<div class="roidaico-loading-spinner"></div>' +
                '<div class="roidaico-loading-text">Translating keywords with AI...</div>' +
                '<div class="roidaico-loading-subtext">This might take a moment. Please wait.</div>' +
                '</div>'
            );
        }
        modal.find('.roidaico-loading-overlay').fadeIn(200);

        $.ajax({
            url: aicgAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'roidaico_bulk_translate_keywords',
                nonce: aicgAdmin.nonce,
                keyword_ids: selectedIds,
                target_lang: targetLang
            },
            success: function (response) {
                modal.find('.roidaico-loading-overlay').fadeOut(200);
                if (response.success) {
                    showToast(response.data.message, 'success');
                    setTimeout(function() {
                        location.reload();
                    }, 2000);
                } else {
                    showToast(response.data, 'error');
                    btn.prop('disabled', false).text('Start Bulk Translation');
                }
            },
            error: function () {
                modal.find('.roidaico-loading-overlay').fadeOut(200);
                showToast(aicgAdmin.strings.error || 'An error occurred', 'error');
                btn.prop('disabled', false).text('Start Bulk Translation');
            }
        });
    });

    // Schedule Page
    // Add schedule modal
    $('#roidaico-add-schedule-btn, #roidaico-add-first-schedule').on('click', function () {
        $('#schedule-id').val('');
        $('#roidaico-schedule-form')[0].reset();

        // Reset time slots to default (one slot at 12:00)
        var container = $('#roidaico-times-container');
        container.empty();
        container.append('<div class="roidaico-time-slot">' +
            '<input type="time" name="times[]" value="12:00" required>' +
            '<button type="button" class="button roidaico-remove-time" style="display:none;">' +
            '<span class="dashicons dashicons-no"></span></button></div>');

        $('#roidaico-schedule-modal-title').text('Add Schedule');
        openModal('#roidaico-schedule-modal');
        setTimeout(checkWeeklySlotsLimit, 100);
    });

    // Add time slot
    $('#roidaico-add-time').on('click', function () {
        // Check if adding would exceed limit for free users
        if (!aicgAdmin.isPro) {
            var days = $('input[name="days[]"]:checked').length || 1; // Assume at least 1 day if none checked yet
            var times = $('input[name="times[]"]').length + 1;

            // If they haven't selected days yet, we check limit based on potential 1 day minimum
            if (days * times > 4) {
                showToast('Free version limit: Maximum 4 slots per week.', 'warning');
                return;
            }
        }

        var container = $('#roidaico-times-container');
        var newSlot = $('<div class="roidaico-time-slot">' +
            '<input type="time" name="times[]" value="12:00" required>' +
            '<button type="button" class="button roidaico-remove-time">' +
            '<span class="dashicons dashicons-no"></span></button></div>');
        container.append(newSlot);
        updateRemoveButtons();
        checkWeeklySlotsLimit();
    });

    // Remove time slot
    $(document).on('click', '.roidaico-remove-time', function () {
        $(this).closest('.roidaico-time-slot').remove();
        updateRemoveButtons();
        checkWeeklySlotsLimit();
    });

    function updateRemoveButtons() {
        var slots = $('.roidaico-time-slot');
        if (slots.length > 1) {
            slots.find('.roidaico-remove-time').show();
        } else {
            slots.find('.roidaico-remove-time').hide();
        }
    }

    // Check and enforce weekly slots limit for free users
    function checkWeeklySlotsLimit() {
        // Strict check for Pro status
        var isPro = (aicgAdmin.isPro == 1 || aicgAdmin.isPro === '1' || aicgAdmin.isPro === true);

        if (isPro) {
            return; // No limits for Pro
        }

        var MAX_SLOTS = 4;
        var daysChecked = $('input[name="days[]"]:checked').length;
        var timesCount = $('input[name="times[]"]').length;
        var currentSlots = daysChecked * timesCount;

        // Determine limits
        var canAddMoreDays = true;
        var canAddMoreTimes = true;

        // If we add another day, would we exceed limit?
        if ((daysChecked + 1) * timesCount > MAX_SLOTS) {
            canAddMoreDays = false;
        }

        // If we add another time, would we exceed limit?
        if (daysChecked * (timesCount + 1) > MAX_SLOTS) {
            canAddMoreTimes = false;
        }

        // Disable unchecked days if adding one would exceed limit
        $('input[name="days[]"]').each(function () {
            if (!$(this).is(':checked')) {
                if (!canAddMoreDays) {
                    $(this).prop('disabled', true);
                    $(this).closest('label').addClass('roidaico-disabled');
                } else {
                    $(this).prop('disabled', false);
                    $(this).closest('label').removeClass('roidaico-disabled');
                }
            } else {
                $(this).prop('disabled', false);
                $(this).closest('label').removeClass('roidaico-disabled');
            }
        });

        // Disable Add Time button if adding one would exceed limit
        if (!canAddMoreTimes) {
            $('#roidaico-add-time').prop('disabled', true).addClass('roidaico-disabled');
        } else {
            $('#roidaico-add-time').prop('disabled', false).removeClass('roidaico-disabled');
        }

        // Show limit indicator
        var $indicator = $('#roidaico-slots-indicator');
        if ($indicator.length === 0) {
            $('#roidaico-add-time').after('<span id="roidaico-slots-indicator" class="roidaico-limit-indicator"></span>');
            $indicator = $('#roidaico-slots-indicator');
        }
        $indicator.text(currentSlots + '/4 ' + (aicgAdmin.strings.slotsPerWeek || 'slots per week'));

        if (currentSlots >= MAX_SLOTS) {
            $indicator.addClass('roidaico-limit-warning');
        } else {
            $indicator.removeClass('roidaico-limit-warning');
        }
    }

    // Listen for day checkbox changes
    $(document).on('change', 'input[name="days[]"]', function () {
        var isPro = (aicgAdmin.isPro == 1 || aicgAdmin.isPro === '1' || aicgAdmin.isPro === true);

        if (!isPro) {
            var days = $('input[name="days[]"]:checked').length;
            var times = $('input[name="times[]"]').length;
            var totalSlots = days * times;

            if (totalSlots > 4) {
                $(this).prop('checked', false);
                showToast('Free version limit: Maximum 4 slots per week.', 'warning');
                // Re-run check to ensure UI state is correct
                checkWeeklySlotsLimit();
                return;
            }
        }
        checkWeeklySlotsLimit();
    });

    // Initialize limit check when opening schedule modal
    $(document).on('click', '#roidaico-add-schedule-btn, #roidaico-add-first-schedule, .roidaico-edit-schedule', function () {
        setTimeout(checkWeeklySlotsLimit, 100);
    });

    // Edit schedule
    $(document).on('click', '.roidaico-edit-schedule', function () {
        var schedule = $(this).data('schedule');

        $('#schedule-id').val(schedule.id);
        $('#schedule-name').val(schedule.name);
        $('#schedule-category').val(schedule.category_id);
        $('#schedule-post-type').val(schedule.post_type);
        $('#schedule-author').val(schedule.author_id);
        $('input[name="enabled"]').prop('checked', schedule.enabled == 1);

        // Set days
        $('input[name="days[]"]').prop('checked', false);
        var days = schedule.days.split(',');
        days.forEach(function (day) {
            $('input[name="days[]"][value="' + day + '"]').prop('checked', true);
        });

        // Set times
        var times = JSON.parse(schedule.times || '["09:00"]');
        var timesContainer = $('#roidaico-times-container');
        timesContainer.empty();
        times.forEach(function (time, index) {
            timesContainer.append(
                '<div class="roidaico-time-slot">' +
                '<input type="time" name="times[]" value="' + time + '" required>' +
                '<button type="button" class="button roidaico-remove-time">' +
                '<span class="dashicons dashicons-no"></span></button></div>'
            );
        });
        updateRemoveButtons();

        // Set options
        var options = JSON.parse(schedule.options || '{}');
        if (options.tone) $('select[name="options[tone]"]').val(options.tone);
        if (options.length) $('select[name="options[length]"]').val(options.length);

        $('#roidaico-schedule-modal-title').text('Edit Schedule');
        openModal('#roidaico-schedule-modal');
    });

    // Save schedule form
    $('#roidaico-schedule-form').on('submit', function (e) {
        e.preventDefault();

        var form = $(this);
        var btn = form.find('button[type="submit"]');

        // Collect days
        var days = [];
        $('input[name="days[]"]:checked').each(function () {
            days.push($(this).val());
        });

        if (days.length === 0) {
            showToast('Please select at least one day.', 'warning');
            return;
        }

        // Collect times
        var times = [];
        $('input[name="times[]"]').each(function () {
            times.push($(this).val());
        });

        // Check weekly slots limit for free users
        var totalWeeklySlots = days.length * times.length;
        var isPro = (aicgAdmin.isPro == 1 || aicgAdmin.isPro === '1' || aicgAdmin.isPro === true);

        if (!isPro && totalWeeklySlots > 4) {
            showToast('Free version limit: Maximum 4 publish slots per week.\n\nPlease reduce days or times to max 4 total slots.', 'warning');
            btn.prop('disabled', false).text('Save Schedule');
            return false;
        }

        // Collect options
        var options = {
            tone: $('select[name="options[tone]"]').val(),
            length: $('select[name="options[length]"]').val()
        };

        btn.prop('disabled', true).text(aicgAdmin.strings.saving);

        $.ajax({
            url: aicgAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'roidaico_save_schedule',
                nonce: aicgAdmin.nonce,
                id: $('#schedule-id').val(),
                name: $('#schedule-name').val(),
                category_id: $('#schedule-category').val(),
                days: days.join(','),
                times: JSON.stringify(times),
                post_type: $('#schedule-post-type').val(),
                author_id: $('#schedule-author').val(),
                options: JSON.stringify(options),
                enabled: $('input[name="enabled"]').is(':checked') ? 1 : 0
            },
            success: function (response) {
                if (response.success) {
                    location.reload();
                } else {
                    showToast(response.data, 'error');
                    btn.prop('disabled', false).text('Save Schedule');
                }
            },
            error: function () {
                showToast(aicgAdmin.strings.error, 'error');
                btn.prop('disabled', false).text('Save Schedule');
            }
        });
    });

    // Toggle schedule
    $(document).on('change', '.roidaico-toggle-schedule', function () {
        var scheduleId = $(this).data('id');
        var enabled = $(this).is(':checked') ? 1 : 0;
        var card = $(this).closest('.roidaico-schedule-card');

        $.ajax({
            url: aicgAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'roidaico_toggle_schedule',
                nonce: aicgAdmin.nonce,
                schedule_id: scheduleId,
                enabled: enabled
            },
            success: function (response) {
                if (response.success) {
                    if (enabled) {
                        card.removeClass('roidaico-schedule-disabled');
                    } else {
                        card.addClass('roidaico-schedule-disabled');
                    }
                } else {
                    showToast(response.data, 'error');
                }
            },
            error: function () {
                showToast(aicgAdmin.strings.error, 'error');
            }
        });
    });

    // Delete schedule
    $(document).on('click', '.roidaico-delete-schedule', function () {
        var btn = $(this);
        var scheduleId = btn.data('id');

        if (!confirm(aicgAdmin.strings.confirmDelete)) {
            return;
        }

        $.ajax({
            url: aicgAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'roidaico_delete_schedule',
                nonce: aicgAdmin.nonce,
                schedule_id: scheduleId
            },
            success: function (response) {
                if (response.success) {
                    btn.closest('.roidaico-schedule-card').fadeOut(300, function () {
                        $(this).remove();
                        if ($('.roidaico-schedule-card').length === 0) {
                            location.reload();
                        }
                    });
                } else {
                    showToast(response.data, 'error');
                }
            },
            error: function () {
                showToast(aicgAdmin.strings.error, 'error');
            }
        });
    });

    // Run schedule now (manual trigger)
    $(document).on('click', '.roidaico-run-schedule-now', function () {
        var btn = $(this);
        var scheduleId = btn.data('id');
        var originalText = btn.text();

        btn.prop('disabled', true).text(aicgAdmin.strings.generating || 'Generating...');

        $.ajax({
            url: aicgAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'roidaico_run_schedule_now',
                nonce: aicgAdmin.nonce,
                schedule_id: scheduleId
            },
            success: function (response) {
                btn.prop('disabled', false).text(originalText);
                if (response.success) {
                    showToast(response.data.message, 'success');
                    if (response.data.edit_url) {
                        if (confirm('Open the article for editing?')) {
                            window.open(response.data.edit_url, '_blank');
                        }
                    }
                    setTimeout(function() {
                        location.reload();
                    }, 2000);
                } else {
                    showToast('Error: ' + response.data, 'error');
                }
            },
            error: function () {
                btn.prop('disabled', false).text(originalText);
                showToast(aicgAdmin.strings.error || 'An error occurred', 'error');
            }
        });
    });

    // Helper function
    function escapeHtml(text) {
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(text));
        return div.innerHTML;
    }

    // Settings Page - Load AI Models
    var allModels = [];

    function renderModels(models) {
        var $select = $('#roidaico_openrouter_model');
        var currentModel = $select.data('current') || 'openai/gpt-4o-mini';
        $select.empty();

        if (models.length === 0) {
            $select.append('<option value="">No models found</option>');
        } else {
            models.forEach(function (model) {
                var selected = model.id === currentModel ? 'selected' : '';
                $select.append('<option value="' + model.id + '" ' + selected + '>' + model.name + '</option>');
            });
        }

        // Initialize Select2 after population
        initSelect2($select);
    }

    function loadModels(apiKey) {
        var $select = $('#roidaico_openrouter_model');

        if (!$select.length) {
            return;
        }

        var data = {
            action: 'roidaico_get_models',
            nonce: aicgAdmin.nonce
        };

        if (apiKey) {
            data.api_key = apiKey;
        }

        // Show loading state
        if ($select.find('option').length <= 1) {
            $select.html('<option>Loading models...</option>');
        }

        $.ajax({
            url: aicgAdmin.ajaxUrl,
            type: 'POST',
            data: data,
            success: function (response) {
                if (response.success) {
                    allModels = response.data;
                    renderModels(allModels);
                } else {
                    $select.html('<option value="">Error loading models</option>');
                    console.error('Error loading models:', response.data);
                }
            },
            error: function () {
                $select.html('<option value="">Error loading models</option>');
            }
        });
    }

    // Load models on page load if key exists and provider is OpenRouter
    if ($('#roidaico_openrouter_model').length > 0 && $('#roidaico_ai_provider').val() !== 'wp_ai_client') {
        loadModels();
    }

})(jQuery);
