/**
 * Code Snippets Manager - Admin JavaScript
 *
 * @package Switchboard
 * @since 1.0.0
 */

jQuery(document).ready(function($) {
    'use strict';

    /**
     * Show admin notice (available globally)
     */
    function showNotice(message, type) {
        const $notice = $('<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>');
        $('.sb-module-wrap').prepend($notice);

        // Auto dismiss after 3 seconds
        setTimeout(function() {
            $notice.fadeOut(function() {
                $(this).remove();
            });
        }, 3000);
    }

    // ===================================
    // Dashboard Filtering & Search
    // ===================================

    if ($('.csm-dashboard-layout').length > 0) {
        let currentFilters = {
            status: 'all',
            type: 'all',
            location: 'all',
            search: ''
        };

        // Filter option click handler
        $('.csm-filter-option').on('click', function() {
            const filterType = $(this).data('filter');
            const filterValue = $(this).data('value');

            // Update active state within the same filter group
            $('[data-filter="' + filterType + '"]').removeClass('active');
            $(this).addClass('active');

            // Update filter
            currentFilters[filterType] = filterValue;

            // Apply filters
            applyFilters();
        });

        // Search input handler
        $('#csm-search').on('input', function() {
            currentFilters.search = $(this).val().toLowerCase();
            applyFilters();
        });

        // Row click handler - navigate to edit page
        $('.csm-snippet-row').on('click', function(e) {
            // Don't trigger if clicking on a link, button, label, or input within the row
            if ($(e.target).closest('a, button, label, input').length === 0) {
                const editUrl = $(this).find('.csm-snippet-row-edit').attr('href');
                if (editUrl) {
                    window.location.href = editUrl;
                }
            }
        });

        // Apply all filters
        function applyFilters() {
            let visibleCount = 0;

            $('.csm-snippet-row').each(function() {
                const $row = $(this);
                const rowType = $row.data('type');
                const rowLocation = $row.data('location');
                const rowStatus = $row.data('status');
                const rowTitle = $row.find('.csm-snippet-row-title').text().toLowerCase();
                const rowDesc = $row.find('.csm-snippet-row-desc').text().toLowerCase();

                // Check all filters
                let matches = true;

                // Status filter
                if (currentFilters.status !== 'all' && rowStatus !== currentFilters.status) {
                    matches = false;
                }

                // Type filter
                if (currentFilters.type !== 'all' && rowType !== currentFilters.type) {
                    matches = false;
                }

                // Location filter
                if (currentFilters.location !== 'all' && rowLocation !== currentFilters.location) {
                    matches = false;
                }

                // Search filter
                if (currentFilters.search !== '' &&
                    !rowTitle.includes(currentFilters.search) &&
                    !rowDesc.includes(currentFilters.search)) {
                    matches = false;
                }

                // Show/hide row
                if (matches) {
                    $row.show();
                    visibleCount++;
                } else {
                    $row.hide();
                }
            });

            // Show/hide no results message
            if (visibleCount === 0) {
                $('.csm-no-results').show();
            } else {
                $('.csm-no-results').hide();
            }
        }

        // Toggle snippet active status
        $('.csm-toggle-input').on('change', function(e) {
            e.stopPropagation();

            const $toggle = $(this);
            const $label = $toggle.closest('.csm-snippet-toggle');
            const snippetId = $label.data('snippet-id');
            const isActive = $toggle.is(':checked');

            // Disable toggle during request
            $toggle.prop('disabled', true);

            // Update snippet status via AJAX
            $.post(ajaxurl, {
                action: 'switchboard_toggle_snippet',
                nonce: switchboard_csm_admin.nonce,
                snippet_id: snippetId,
                active: isActive
            }, function(response) {
                if (response.success) {
                    // Update row data attribute for filtering
                    $toggle.closest('.csm-snippet-row').data('status', isActive ? 'active' : 'inactive');

                    // Show brief success feedback
                    const $row = $toggle.closest('.csm-snippet-row');
                    $row.css('background', '#dcfce7');
                    setTimeout(function() {
                        $row.css('background', '');
                    }, 300);
                } else {
                    // Revert toggle on error
                    $toggle.prop('checked', !isActive);
                    showNotice(response.data.message || 'Failed to update snippet status.', 'error');
                }
                $toggle.prop('disabled', false);
            }).fail(function() {
                // Revert toggle on error
                $toggle.prop('checked', !isActive);
                showNotice('Failed to update snippet status. Please try again.', 'error');
                $toggle.prop('disabled', false);
            });
        });
    }

    // ===================================
    // Snippet Editor
    // ===================================

    // Check if we're on the snippet edit page
    if ($('#csm-form').length === 0) {
        return;
    }

    let currentSnippetId = $('#csm-snippet-id').val();
    let isEdit = $('#csm-is-edit').val() === '1';

    /**
     * Update location options based on code type
     */
    function updateLocationOptions() {
        // Update editor notices
        updateEditorNotice();
    }

    /**
     * Update editor notice based on code type
     */
    function updateEditorNotice() {
        const type = $('#csm-type').val();
        $('#csm-editor-notice-js, #csm-editor-notice-css, #csm-editor-notice-html').hide();
        $('#csm-editor-notice-' + type).show();
    }

    // Code type change handler
    $('#csm-type').on('change', updateLocationOptions);

    // Initialize on page load
    updateLocationOptions();

    /**
     * Save snippet
     */
    $('#csm-save-snippet').on('click', function() {
        const $btn = $(this);
        const title = $('#csm-title').val().trim();
        const code = $('#csm-code').val().trim();

        // Validation
        if (!title) {
            alert('Please enter a snippet title.');
            $('#csm-title').focus();
            return;
        }

        if (!code) {
            alert('Please enter some code for this snippet.');
            $('#csm-code').focus();
            return;
        }

        // Collect data
        const snippetData = {
            id: currentSnippetId || 'snippet_' + Date.now(),
            title: title,
            description: $('#csm-description').val().trim(),
            code: code,
            type: $('#csm-type').val(),
            location: $('#csm-location').val(),
            priority: parseInt($('#csm-priority').val()) || 10,
            active: $('#csm-active').is(':checked'),
            modified: new Date().toISOString()
        };

        // Preserve or set created timestamp
        if (isEdit && window.csmSnippetData && window.csmSnippetData.created) {
            snippetData.created = window.csmSnippetData.created;
        } else {
            snippetData.created = new Date().toISOString();
        }

        // Show loading state
        $btn.prop('disabled', true).html('<span class="dashicons dashicons-update dashicons-spin"></span> Saving...');

        // Save via AJAX
        $.post(ajaxurl, {
            action: 'switchboard_save_snippet',
            nonce: switchboard_csm_admin.nonce,
            snippet_data: snippetData,
            is_edit: isEdit
        }, function(response) {
            var btnText = isEdit ? 'Update Snippet' : 'Create Snippet';
            if (response.success) {
                // Show success message
                showNotice('Snippet saved successfully!', 'success');

                // If this was a new snippet, redirect to edit page
                if (!isEdit) {
                    setTimeout(function() {
                        window.location.href = response.data.redirect_url;
                    }, 1000);
                } else {
                    // Re-enable button
                    $btn.prop('disabled', false).text(btnText);
                }
            } else {
                showNotice(response.data.message || 'Failed to save snippet.', 'error');
                $btn.prop('disabled', false).text(btnText);
            }
        }).fail(function() {
            var btnText = isEdit ? 'Update Snippet' : 'Create Snippet';
            showNotice('Failed to save snippet. Please try again.', 'error');
            $btn.prop('disabled', false).text(btnText);
        });
    });

    /**
     * Cancel button
     */
    $('#csm-cancel-snippet').on('click', function() {
        window.location.href = switchboard_csm_admin.dashboardUrl;
    });

    /**
     * Delete snippet
     */
    $('#csm-delete-snippet').on('click', function() {
        if (!confirm('Are you sure you want to delete this snippet? This action cannot be undone.')) {
            return;
        }

        const $btn = $(this);
        $btn.prop('disabled', true).html('<span class="dashicons dashicons-update dashicons-spin"></span> Deleting...');

        $.post(ajaxurl, {
            action: 'switchboard_delete_snippet',
            nonce: switchboard_csm_admin.nonce,
            snippet_id: currentSnippetId
        }, function(response) {
            if (response.success) {
                showNotice('Snippet deleted successfully!', 'success');
                setTimeout(function() {
                    window.location.href = response.data.redirect_url;
                }, 1000);
            } else {
                showNotice(response.data.message || 'Failed to delete snippet.', 'error');
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-trash"></span> Delete Snippet');
            }
        }).fail(function() {
            showNotice('Failed to delete snippet. Please try again.', 'error');
            $btn.prop('disabled', false).html('<span class="dashicons dashicons-trash"></span> Delete Snippet');
        });
    });

    /**
     * Tab key handling in code editor for proper indentation
     */
    $('#csm-code').on('keydown', function(e) {
        if (e.keyCode === 9) { // Tab key
            e.preventDefault();
            const start = this.selectionStart;
            const end = this.selectionEnd;
            const value = this.value;

            // Insert 4 spaces
            this.value = value.substring(0, start) + '    ' + value.substring(end);

            // Move cursor
            this.selectionStart = this.selectionEnd = start + 4;
        }
    });
});
