jQuery(document).ready(function($) {
    // Use event delegation on a parent element that exists when the page loads
    $('#wpsummarize-meta-box').on('click', '#delete-meta', function(e) {
        e.preventDefault();
        var postId = $(this).data('postid');
        
        $.ajax({
            url: wpSummarizeAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'delete_wpsummarize_meta',
                post_id: postId,
                nonce: wpSummarizeAjax.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#wpsummarize-meta-box').html(response.data.html);
                    wpsummarize_initializeToggleEditor();
                    wpsummarize_initializeToggleLinksGeneral();
                } else {
                    console.log('Failed to delete meta.');
                }
            }
        });
    });
});



(function($) {
    $(document).ready(function() {
        // Make sure the wp object and its components are available
        if (typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor')) {
            var wpsummarize_previousIsSaving = false;

            wp.data.subscribe(function() {
                var isSaving = wp.data.select('core/editor').isSavingPost();
                var isAutosaving = wp.data.select('core/editor').isAutosavingPost();

                if (isSaving && !isAutosaving && !wpsummarize_previousIsSaving) {
                    // Post is being saved (not autosaved)
                    var postId = wp.data.select('core/editor').getCurrentPostId();
                    wpsummarize_checkSummaryStatus(postId);
                }

                wpsummarize_previousIsSaving = isSaving;
            });
        }
    });



function wpsummarize_checkSummaryStatus(postId, lastState = null) {
    var wpsummarize_attempts = 0;
    var wpsummarize_maxAttempts = 7;  // Maximum number of attempts before forcing an update

    var wpsummarize_statusInterval = setInterval(function() {
        wpsummarize_attempts++;
        
        jQuery.ajax({
            url: wpSummarizeAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'check_summary_status',
                post_id: postId,
                nonce: wpSummarizeAjax.nonce                
            },
            success: function(response) {
                // Check if response indicates an error
                if (!response.success) {
                    // Display error message
                    jQuery('#wpsummarize-meta-box').html('<div class="error-message">An error occurred while creating the summary.</div>');
                    clearInterval(wpsummarize_statusInterval);
                    lastState = 'completed';
                    return;
                }

                if (response.data.summary_running && lastState !== 'running') {
                    // State change to running
                    jQuery('#wpsummarize-meta-box').html(response.data.data.html_running);
                    lastState = 'running';
                } else if ((!response.data.summary_running && lastState === 'running') || (wpsummarize_attempts >= wpsummarize_maxAttempts && lastState === null)) {
                    // State change to completed
                    jQuery('#wpsummarize-meta-box').html(response.data.data.html_completed);
                    wpsummarize_initializeToggleEditor();
                    wpsummarize_initializeToggleLinksGeneral();
                    clearInterval(wpsummarize_statusInterval);
                    lastState = 'completed';
                    wpsummarize_attempts = 0;
                }
            },
            error: function(xhr, status, error) {
                // Handle AJAX request failures
                jQuery('#wpsummarize-meta-box').html('<div class="error-message">An error occurred while checking the summary status.</div>');
                clearInterval(wpsummarize_statusInterval);
            }
        });
    }, 1500);
}
})(jQuery);



function wpsummarize_initializeToggleLinksGeneral() {
    var toggleLink = document.getElementById('wpsummarize_edit_meta_box_link');
    var customizationDiv = document.getElementById('wpsummarize_edit_meta_box');

    if (toggleLink && customizationDiv) {
        toggleLink.addEventListener('click', function(e) {
            e.preventDefault();
            // Toggle the display style between 'block' and 'none'
            if (customizationDiv.style.display === 'block') {
                customizationDiv.style.display = 'none';
            } else {
                customizationDiv.style.display = 'block';
            }
        });
    }
};


function wpsummarize_initializeToggleEditor() {
    var toggleLink = document.getElementById('wpsummarize_edit_summary_meta_box_link');
    var customizationDiv = document.getElementById('wpsummarize_edit_summary_meta_box');

    if (toggleLink && customizationDiv) {
        toggleLink.addEventListener('click', function(e) {
            e.preventDefault();
            // Toggle the display style between 'block' and 'none'
            if (customizationDiv.style.display === 'block') {
                customizationDiv.style.display = 'none';
            } else {
                customizationDiv.style.display = 'block';
            }
        });
    }
};



// Function to uncheck the default checkbox
function wpsummarize_uncheckDefaultCheckbox(checkbox) {
  checkbox.checked = false;
}

// Function to find the closest parent with a specific class
function wpsummarize_findClosestParent(element, className) {
  while (element && !element.classList.contains(className)) {
    element = element.parentElement;
  }
  return element;
}


// Function to handle input interactions
function wpsummarize_handleInputInteraction(event) {
  const container = wpsummarize_findClosestParent(event.target, 'wpsummarize-customization-control');
  if (container) {
    const defaultCheckbox = container.querySelector('.wpsummarize-default-checkbox');
    if (defaultCheckbox) {
      wpsummarize_uncheckDefaultCheckbox(defaultCheckbox);
    }
  }
}

// Function to set up event listeners for a container
function wpsummarize_setupContainerListeners(container) {
  const customizationOptions = container.querySelector('.customization-options');
  if (customizationOptions) {
    customizationOptions.addEventListener('focus', wpsummarize_handleInputInteraction, true);
    customizationOptions.addEventListener('change', wpsummarize_handleInputInteraction, true);
  }
}

// Set up MutationObserver to watch for dynamically added content
const wpsummarize_customization_observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.type === 'childList') {
      mutation.addedNodes.forEach((node) => {
        if (node.nodeType === Node.ELEMENT_NODE) {
          if (node.classList.contains('wpsummarize-customization-control')) {
            wpsummarize_setupContainerListeners(node);
          } else {
            const containers = node.querySelectorAll('.wpsummarize-customization-control');
            containers.forEach(wpsummarize_setupContainerListeners);
          }
        }
      });
    }
  });
});

// Initial setup
document.addEventListener('DOMContentLoaded', function() {
  const containers = document.querySelectorAll('.wpsummarize-customization-control');
  containers.forEach(wpsummarize_setupContainerListeners);

  // Start observing the document body for changes
  wpsummarize_customization_observer.observe(document.body, { childList: true, subtree: true });
});





// Function to check the update checkbox
function wpsummarize_rem_check_updateCheckbox() {
  const checkbox = document.querySelector('input[type="checkbox"][name="wpsummarize_update_on_edit"]');
  if (checkbox) {
    checkbox.checked = true;
  }
}

// Function to handle input interactions
function wpsummarize_rem_check_handleInputInteraction(event) {
  if (event.target.tagName === 'INPUT' || event.target.tagName === 'SELECT' || event.target.tagName === 'TEXTAREA') {
    wpsummarize_rem_check_updateCheckbox();
  }
}

// Function to set up event listeners for a container
function wpsummarize_rem_check_setupContainerListeners(container) {
  container.addEventListener('focus', wpsummarize_rem_check_handleInputInteraction, true);
  container.addEventListener('change', wpsummarize_rem_check_handleInputInteraction, true);
}

// Function to set up event listeners
function wpsummarize_rem_check_setupFormListeners() {
  const containers = document.querySelectorAll('.wpsummarize-watched-input');
  containers.forEach(wpsummarize_rem_check_setupContainerListeners);
}

// Set up MutationObserver to watch for dynamically added content
const wpsummarize_rem_check_observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.type === 'childList') {
      mutation.addedNodes.forEach((node) => {
        if (node.nodeType === Node.ELEMENT_NODE) {
          if (node.classList.contains('wpsummarize-watched-input')) {
            wpsummarize_rem_check_setupContainerListeners(node);
          } else {
            const containers = node.querySelectorAll('.wpsummarize-watched-input');
            containers.forEach(wpsummarize_rem_check_setupContainerListeners);
          }
        }
      });
    }
  });
});

// Initialize the functionality when the DOM is fully loaded
document.addEventListener('DOMContentLoaded', () => {
  wpsummarize_rem_check_setupFormListeners();
  
  // Start observing the document body for changes
  wpsummarize_rem_check_observer.observe(document.body, { childList: true, subtree: true });
});

jQuery(document).ready(function($) {

    $(document).on('click', '#wpsummarize-api-key-notice .notice-dismiss', function() {
        $.ajax({
            url: wpSummarizeAjax.ajaxurl,
            type: 'POST',
            data: {
                action: wpSummarizeAjax.dismiss_notice_action,
                nonce: wpSummarizeAjax.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#wpsummarize-api-key-notice').fadeOut();
                }
            }
        });
    });
});

jQuery(document).ready(function($) {
    $('.wpsummarize-position-select').on('change', function() {
        var $hint = $(this).siblings('.wpsummarize-shortcode-hint');
        if ($(this).val() === 'manual_shortcode') {
            $hint.slideDown();
        } else {
            $hint.slideUp();
        }
    });
});

jQuery(document).ready(function($) {
    // Handle quota error notice dismissal
    $('.wpsummarize-dismiss-quota-notice').on('click', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var $notice = $button.closest('.wpsummarize-quota-error');
        var noticeType = $button.data('notice');
        
        // Verify we have what we need
        if (!wpSummarizeAjax || !wpSummarizeAjax.ajaxurl) {
            alert('Configuration error: AJAX URL not found');
            return;
        }
        
        if (!wpSummarizeAjax.nonce) {
            alert('Configuration error: Nonce not found');
            return;
        }
        
        // Prepare the data
        var ajaxData = {
            action: 'wpsummarize_dismiss_quota_notice',
            notice_type: noticeType,
            nonce: wpSummarizeAjax.nonce
        };
        
        // Disable button during request
        $button.prop('disabled', true).text('Dismissing...');
        
        $.ajax({
            url: wpSummarizeAjax.ajaxurl,
            type: 'POST',
            data: ajaxData,
            dataType: 'json',
            success: function(response) {
                if (response && response.success) {
                    $notice.fadeOut(300, function() {
                        $(this).remove();
                    });
                } else {
                    alert('Error: ' + (response && response.data && response.data.message ? response.data.message : 'Unknown error'));
                    $button.prop('disabled', false).text('Dismiss');
                }
            },
            error: function(xhr, status, error) {
                var errorMessage = 'Failed to dismiss notice. ';
                if (xhr.status === 0) {
                    errorMessage += 'Network error - check your internet connection.';
                } else if (xhr.status === 403) {
                    errorMessage += 'Forbidden. Please refresh the page and try again.';
                } else if (xhr.status === 404) {
                    errorMessage += 'AJAX endpoint not found.';
                } else if (xhr.status === 500) {
                    errorMessage += 'Server error. Please try again later.';
                } else {
                    errorMessage += 'Please try again.';
                }
                
                alert(errorMessage);
                $button.prop('disabled', false).text('Dismiss');
            }
        });
    });
});


jQuery(document).ready(function($) {
    
    // ========================================================================
    // QUOTA ERROR NOTICE DISMISSAL
    // ========================================================================
    
    $('.wpsummarize-dismiss-quota-notice').on('click', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var $notice = $button.closest('.wpsummarize-quota-error');
        var noticeType = $button.data('notice');
        
        // Verify we have what we need
        if (!wpSummarizeAjax || !wpSummarizeAjax.ajaxurl || !wpSummarizeAjax.nonce) {
            alert('Configuration error. Please refresh the page and try again.');
            return;
        }
        
        // Disable button during request
        $button.prop('disabled', true).text('Dismissing...');
        
        $.ajax({
            url: wpSummarizeAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'wpsummarize_dismiss_quota_notice',
                notice_type: noticeType,
                nonce: wpSummarizeAjax.nonce
            },
            dataType: 'json',
            success: function(response) {
                if (response && response.success) {
                    $notice.fadeOut(300, function() {
                        $(this).remove();
                    });
                } else {
                    alert('Error: ' + (response && response.data && response.data.message ? response.data.message : 'Unknown error'));
                    $button.prop('disabled', false).text('Dismiss');
                }
            },
            error: function(xhr) {
                var errorMessage = 'Failed to dismiss notice. ';
                if (xhr.status === 0) {
                    errorMessage += 'Network error - check your internet connection.';
                } else if (xhr.status === 403) {
                    errorMessage += 'Forbidden. Please refresh the page and try again.';
                } else {
                    errorMessage += 'Please try again.';
                }
                alert(errorMessage);
                $button.prop('disabled', false).text('Dismiss');
            }
        });
    });
    
    // ========================================================================
    // TOKEN LIMIT NOTICE DISMISSAL
    // ========================================================================
    
    $('.wpsummarize-dismiss-token-limit-notice').on('click', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var $notice = $button.closest('.wpsummarize-token-limit-notice');
        var noticeType = $button.data('notice');
        
        // Verify we have what we need
        if (!wpSummarizeAjax || !wpSummarizeAjax.ajaxurl || !wpSummarizeAjax.nonce) {
            alert('Configuration error. Please refresh the page and try again.');
            return;
        }
        
        // Disable button during request
        $button.prop('disabled', true).text('Dismissing...');
        
        $.ajax({
            url: wpSummarizeAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'wpsummarize_dismiss_token_limit_notice',
                notice_type: noticeType,
                nonce: wpSummarizeAjax.nonce
            },
            dataType: 'json',
            success: function(response) {
                if (response && response.success) {
                    $notice.fadeOut(300, function() {
                        $(this).remove();
                    });
                } else {
                    alert('Error: ' + (response && response.data && response.data.message ? response.data.message : 'Unknown error'));
                    $button.prop('disabled', false).text('Dismiss');
                }
            },
            error: function(xhr) {
                var errorMessage = 'Failed to dismiss notice. ';
                if (xhr.status === 0) {
                    errorMessage += 'Network error - check your internet connection.';
                } else if (xhr.status === 403) {
                    errorMessage += 'Forbidden. Please refresh the page and try again.';
                } else {
                    errorMessage += 'Please try again.';
                }
                alert(errorMessage);
                $button.prop('disabled', false).text('Dismiss');
            }
        });
    });
    
});

jQuery(document).ready(function($) {
    $('#wpsummarize-check-api-key').on('click', function() {
        var $button = $(this);
        var $result = $('#wpsummarize-api-key-result');
        var apiKey = $('#wpsummarize_openai_api_key').val();
        var provider = $('#wpsummarize_ai_api_provider').length ? $('#wpsummarize_ai_api_provider').val() : 'openai mini';
        
        if (!apiKey || apiKey.trim() === '') {
            $result.html('<span style="color:red">' + wpSummarizeAjax.invalid_key_text + ' No API key entered.</span>');
            return;
        }
        
        $button.prop('disabled', true).text(wpSummarizeAjax.checking_text);
        $result.html('');
        
        $.ajax({
            url: wpSummarizeAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'wpsummarize_check_api_key',
                nonce: wpSummarizeAjax.check_api_key_nonce,
                api_key: apiKey,
                provider: provider
            },
            success: function(response) {
                if (response.success) {
                    var html = '<span style="color:green">' + response.data.message + '</span>';
                    if (response.data.warning) {
                        html += '<br><span style="color:#dba617; font-size:13px;">Notice: ' + response.data.warning + '</span>';
                    }
                    $result.html(html);
                } else {
                    var errorMsg = (response.data && (response.data.error || response.data.message))
                        ? (response.data.error || response.data.message)
                        : wpSummarizeAjax.ajax_error_text;
                    $result.empty().append(
                        $('<span>').css('color', 'red').text(errorMsg)
                    );
                }
            },
            error: function(jqXHR, textStatus) {
                var detail = jqXHR && jqXHR.status ? ' (HTTP ' + jqXHR.status + ')' : (textStatus ? ' (' + textStatus + ')' : '');
                $result.empty().append(
                    $('<span>').css('color', 'red').text(wpSummarizeAjax.ajax_error_text + detail)
                );
            },
            complete: function() {
                $button.prop('disabled', false).text(wpSummarizeAjax.check_key_text);
            }
        });
    });
});


// Dismiss generic API error notice
jQuery(document).on('click', '.wpsummarize-dismiss-api-error-notice', function(e) {
    e.preventDefault();
    
    var $notice = jQuery(this).closest('.wpsummarize-api-error-notice');
    
    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'wpsummarize_dismiss_api_error_notice',
            nonce: wpSummarizeAjax.nonce,
            notice_type: 'wpsummarize_api_error'
        },
        success: function(response) {
            $notice.fadeOut(300, function() {
                jQuery(this).remove();
            });
        },
        error: function() {
            $notice.fadeOut(300, function() {
                jQuery(this).remove();
            });
        }
    });
});

// Also dismiss via the WordPress native X button
jQuery(document).on('click', '.wpsummarize-api-error-notice .notice-dismiss', function() {
    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'wpsummarize_dismiss_api_error_notice',
            nonce: wpSummarizeAjax.nonce,
            notice_type: 'wpsummarize_api_error'
        }
    });
});

jQuery(document).ready(function($) {
    $('#wpsummarize-meta-box').on('click', '#wpsummarize-delete-summary', function(e) {
        e.preventDefault();
        
        if (!confirm('Are you sure you want to delete this summary?')) {
            return;
        }
        
        var $link = $(this);
        var postId = $link.data('postid');
        
        $link.text('Deleting...');
        
        $.ajax({
            url: wpSummarizeAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'wpsummarize_delete_summary',
                post_id: postId,
                nonce: wpSummarizeAjax.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#wpsummarize-meta-box').html(response.data.html);
                    wpsummarize_initializeToggleEditor();
                    wpsummarize_initializeToggleLinksGeneral();
                } else {
                    alert('Failed to delete summary.');
                    $link.text('Delete this summary');
                }
            },
            error: function() {
                alert('Request failed. Please try again.');
                $link.text('Delete this summary');
            }
        });
    });
});