jQuery(document).ready(function($) {
    'use strict';
    
    // Form submission
    $('#pc-announcements-274-form').on('submit', function(e) {
        e.preventDefault();
        
        var $form = $(this);
        var $submitBtn = $form.find('button[type="submit"]');
        var originalText = $submitBtn.text();
        
        // Show loading state
        $submitBtn.prop('disabled', true).text('Saving...');
        
        $.ajax({
            url: pc_announcements_274_ajax.ajax_url,
            type: 'POST',
            data: $form.serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Show success message
                    $('<div class="notice notice-success is-dismissible"><p>' + response.data.message + '</p></div>')
                        .insertAfter('.wp-header-end')
                        .delay(3000)
                        .fadeOut(function() {
                            $(this).remove();
                        });
                    
                    // Redirect to list page
                    setTimeout(function() {
                        window.location.href = 'admin.php?page=pc-announcements-274&message=success';
                    }, 1000);
                } else {
                    // Show error message
                    $('<div class="notice notice-error is-dismissible"><p>' + response.data.message + '</p></div>')
                        .insertAfter('.wp-header-end');
                }
            },
            error: function() {
                $('<div class="notice notice-error is-dismissible"><p>' + pc_announcements_274_ajax.i18n.error_occurred + '</p></div>')
                    .insertAfter('.wp-header-end');
            },
            complete: function() {
                // Restore button state
                $submitBtn.prop('disabled', false).text(originalText);
            }
        });
    });
    
    // Delete confirmation
    $('.pc-announcements-274-delete-btn').on('click', function(e) {
        e.preventDefault();
        
        var announcementId = $(this).data('id');
        var $modal = $('#pc-announcements-274-delete-modal');
        
        // Show modal
        $modal.show();
        
        // Handle delete confirmation
        $modal.find('.pc-announcements-274-confirm-delete').off('click').on('click', function() {
            $.ajax({
                url: pc_announcements_274_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'pc_announcements_274_action',
                    sub_action: 'delete_announcement',
                    id: announcementId,
                    nonce: pc_announcements_274_ajax.nonce
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Remove the row from table
                        $('button[data-id="' + announcementId + '"]').closest('tr').fadeOut(function() {
                            $(this).remove();
                            
                            // Show empty state if no items left
                            if ($('.pc-announcements-274-wrap .wp-list-table tbody tr').length === 0) {
                                location.reload();
                            }
                        });
                        
                        // Show success message
                        $('<div class="notice notice-success is-dismissible"><p>' + response.data.message + '</p></div>')
                            .insertAfter('.wp-header-end')
                            .delay(3000)
                            .fadeOut(function() {
                                $(this).remove();
                            });
                    } else {
                        // Show error message
                        $('<div class="notice notice-error is-dismissible"><p>' + response.data.message + '</p></div>')
                            .insertAfter('.wp-header-end');
                    }
                },
                error: function() {
                    $('<div class="notice notice-error is-dismissible"><p>' + pc_announcements_274_ajax.i18n.error_occurred + '</p></div>')
                        .insertAfter('.wp-header-end');
                },
                complete: function() {
                    // Hide modal
                    $modal.hide();
                }
            });
        });
    });
    
    // Close modal handlers
    $('#pc-announcements-274-delete-modal').on('click', '.pc-announcements-274-cancel-delete, .pc-announcements-274-modal-backdrop', function() {
        $('#pc-announcements-274-delete-modal').hide();
    });
    
    // Close modal with Escape key
    $(document).on('keydown', function(e) {
        if (e.keyCode === 27) { // Escape key
            $('#pc-announcements-274-delete-modal').hide();
        }
    });
    
    // Media upload functionality
    var customUploader;
    
    $('.pc-announcements-274-upload-image-btn').on('click', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var $inputField = $button.siblings('input[type="url"]');
        
        // If the uploader object has already been created, reopen the dialog
        if (customUploader) {
            customUploader.open();
            return;
        }
        
        // Extend the wp.media object
        customUploader = wp.media.frames.file_frame = wp.media({
            title: pc_announcements_274_ajax.i18n.choose_image,
            button: {
                text: pc_announcements_274_ajax.i18n.choose_image
            },
            multiple: false
        });
        
        // When a file is selected, grab the URL and set it as the text field's value
        customUploader.on('select', function() {
            var attachment = customUploader.state().get('selection').first().toJSON();
            $inputField.val(attachment.url);
            
            // Update preview if exists
            var $preview = $inputField.siblings('.pc-announcements-274-image-preview');
            if ($preview.length === 0) {
                $preview = $('<div class="pc-announcements-274-image-preview"></div>').insertAfter($inputField.parent());
            }
            $preview.html('<img src="' + attachment.url + '" alt="' + pc_announcements_274_ajax.i18n.preview + '" style="max-width: 200px; height: auto;">');
        });
        
        // Open the uploader dialog
        customUploader.open();
    });
    
    // Auto-hide notices
    $('.notice.is-dismissible').on('click', '.notice-dismiss', function() {
        $(this).closest('.notice').fadeOut(function() {
            $(this).remove();
        });
    });
    
    // Image URL field change handler
    $('input[name="image_url"]').on('input', function() {
        var url = $(this).val();
        var $preview = $(this).siblings('.pc-announcements-274-image-preview');
        
        if (url) {
            if ($preview.length === 0) {
                $preview = $('<div class="pc-announcements-274-image-preview"></div>').insertAfter($(this).parent());
            }
            $preview.html('<img src="' + url + '" alt="' + pc_announcements_274_ajax.i18n.preview + '" style="max-width: 200px; height: auto;" onerror="this.style.display=\'none\'">');
        } else if ($preview.length > 0) {
            $preview.empty();
        }
    });
    
    // Date/time validation
    $('#start_date, #end_date').on('change', function() {
        var startDate = $('#start_date').val();
        var endDate = $('#end_date').val();
        
        if (startDate && endDate && new Date(startDate) >= new Date(endDate)) {
            $('<div class="notice notice-warning is-dismissible"><p>' + pc_announcements_274_ajax.i18n.end_date_warning + '</p></div>')
                .insertAfter('.wp-header-end')
                .delay(5000)
                .fadeOut(function() {
                    $(this).remove();
                });
        }
    });
});