/**
 * HVAC Event Edit Form Fix
 * 
 * Workaround for TEC Community Events plugin bug where title and description
 * fields remain empty when editing existing events. This script manually
 * populates those fields after the form loads.
 */
(function($) {
    'use strict';

    // Only run on event management pages
    if (typeof hvac_event_edit === 'undefined') {
        return;
    }

    // Prevent multiple runs
    var fixAttempted = false;

    /**
     * Populate empty title and description fields for event editing
     */
    function populateEventFields() {
        // Prevent multiple attempts
        if (fixAttempted) {
            return;
        }
        
        // Get event ID from URL parameter
        const urlParams = new URLSearchParams(window.location.search);
        const eventId = urlParams.get('event_id');
        
        if (!eventId) {
            console.log('HVAC Event Fix: No event_id found, assuming new event creation');
            return;
        }

        fixAttempted = true;
        console.log('HVAC Event Fix: Attempting to fix empty fields for event ID:', eventId);

        // Wait for TEC form to be fully rendered
        setTimeout(function() {
            fixEmptyFields(eventId);
        }, 1000);

        // Also try again after a longer delay in case the form loads slowly
        setTimeout(function() {
            fixEmptyFields(eventId);
        }, 3000);
    }

    /**
     * Fix empty title and description fields
     */
    function fixEmptyFields(eventId) {
        // Check if title field is empty
        const $titleField = $('#post_title, input[name="post_title"], .tribe-community-events-form-title input');
        const $descriptionField = $('#post_content, textarea[name="post_content"], .tribe-community-events-form-content textarea, .wp-editor-area');

        let fieldsFixed = 0;

        // Fix title field if empty
        if ($titleField.length > 0 && !$titleField.val().trim()) {
            if (hvac_event_edit.event_title) {
                $titleField.val(hvac_event_edit.event_title);
                $titleField.trigger('change');
                $titleField.addClass('hvac-fixed-field');
                fieldsFixed++;
                console.log('HVAC Event Fix: Populated title field with:', hvac_event_edit.event_title);
            }
        }

        // Fix description field if empty (handle both regular textarea and TinyMCE)
        if ($descriptionField.length > 0 && !$descriptionField.val().trim()) {
            if (hvac_event_edit.event_content) {
                // Handle TinyMCE editor if present
                if (typeof tinymce !== 'undefined' && tinymce.get('post_content')) {
                    tinymce.get('post_content').setContent(hvac_event_edit.event_content);
                    $descriptionField.addClass('hvac-fixed-field');
                    console.log('HVAC Event Fix: Populated TinyMCE editor with content');
                } else {
                    // Fallback to regular textarea
                    $descriptionField.val(hvac_event_edit.event_content);
                    $descriptionField.trigger('change');
                    $descriptionField.addClass('hvac-fixed-field');
                    console.log('HVAC Event Fix: Populated description textarea with content');
                }
                fieldsFixed++;
            }
        }

        if (fieldsFixed > 0) {
            console.log(`HVAC Event Fix: Successfully fixed ${fieldsFixed} empty field(s)`);
            
            // Show a subtle notification to the user
            showFixNotification(fieldsFixed);
        } else {
            console.log('HVAC Event Fix: No empty fields found or no data to populate');
        }
    }

    /**
     * Show a subtle notification that fields were fixed
     */
    function showFixNotification(fieldsFixed) {
        const message = fieldsFixed === 1 ? 
            'Event field populated successfully' : 
            `${fieldsFixed} event fields populated successfully`;

        // Create and show notification
        const $notification = $('<div class="hvac-fix-notification">')
            .html(`<span class="hvac-fix-icon">✓</span> ${message}`)
            .css({
                'position': 'fixed',
                'top': '20px',
                'right': '20px',
                'background': '#4CAF50',
                'color': 'white',
                'padding': '10px 15px',
                'border-radius': '4px',
                'font-size': '14px',
                'z-index': '9999',
                'box-shadow': '0 2px 5px rgba(0,0,0,0.2)',
                'opacity': '0',
                'transition': 'opacity 0.3s ease'
            });

        $('body').append($notification);
        
        // Fade in
        setTimeout(() => $notification.css('opacity', '1'), 100);
        
        // Fade out and remove after 4 seconds
        setTimeout(() => {
            $notification.css('opacity', '0');
            setTimeout(() => $notification.remove(), 300);
        }, 4000);
    }

    /**
     * Initialize the fix when document is ready
     */
    $(document).ready(function() {
        populateEventFields();
    });

    /**
     * Also try to fix fields when the page is fully loaded
     * (in case some content loads via AJAX)
     */
    $(window).on('load', function() {
        setTimeout(populateEventFields, 500);
    });

})(jQuery);