/**
 * External Sources JavaScript functionality
 * 
 * @package Askany
 * @since 1.3.1
 */

(function ($) {
    'use strict';

    // External Sources Management
    const ExternalSources = {
        init: function () {
            this.bindEvents();
            this.loadSources();
        },

        bindEvents: function () {
            // Add source form submission
            $(document).on('submit', '#add-external-source-form', this.handleAddSource);

            // Toggle advanced options
            $(document).on('click', '#toggle-advanced', this.toggleAdvancedOptions);

        },

        handleAddSource: function (e) {
            e.preventDefault();

            const $form = $(this);
            const $submitBtn = $form.find('input[type="submit"]');
            const originalText = $submitBtn.val();

            // Disable submit button
            $submitBtn.prop('disabled', true).val('Adding...');

            const formData = {
                url: $('#external-url').val(),
                follow_links: $('#follow-links').is(':checked'),
                include_paths: $('#include-paths').val(),
                exclude_paths: $('#exclude-paths').val(),
                include_selectors: $('#include-selectors').val(),
                exclude_selectors: $('#exclude-selectors').val()
            };

            $.ajax({
                url: askanyAdmin.restUrl + 'askany/v1/external-sources',
                method: 'POST',
                data: formData,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', askanyAdmin.restNonce);
                },
                success: function (response) {
                    if (response.success) {
                        ExternalSources.showNotice(response.message, 'success');
                        $form[0].reset();
                        ExternalSources.loadSources();
                        ExternalSources.startStatusChecking();
                    } else {
                        ExternalSources.showNotice(response.message || 'Failed to add external source.', 'error');
                    }
                },
                error: function (xhr) {
                    const response = xhr.responseJSON;
                    ExternalSources.showNotice(response?.message || 'Failed to add external source.', 'error');
                },
                complete: function () {
                    $submitBtn.prop('disabled', false).val(originalText);
                }
            });
        },

        

        showNotice: function (message, type) {
            const noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
            const notice = $(`<div class="notice ${noticeClass} is-dismissible"><p>${message}</p></div>`);
            $('.wrap h1').after(notice);

            setTimeout(function () {
                notice.fadeOut();
            }, 5000);
        }
    };

    // Initialize when document is ready
    $(document).ready(function () {
        // Only initialize on external sources page
        if ($('#add-external-source-form').length) {
            // Add REST URL and nonce to admin object if not already present
            if (typeof askanyAdmin !== 'undefined') {
                askanyAdmin.restUrl = askanyAdmin.restUrl || '/wp-json/';
                askanyAdmin.restNonce = askanyAdmin.restNonce || $('#_wpnonce').val();
            }

            ExternalSources.init();
        }
    });

})(jQuery);