import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';

/**
 * TrizTech Search UX Helper (Native Algolia Edition)
 * This script ensures the search text is cleared when dismissing the modal,
 * strictly using Algolia's native buttons to prevent React state crashes.
 */
if (ExecutionEnvironment.canUseDOM) {
  // Use mousedown with capture phase to intercept before Algolia closes the modal
  window.addEventListener('mousedown', (e) => {
    // 1. Identify what the user is clicking
    const isCancelButton = !!e.target.closest('.aa-DetachedCancelButton');
    const isOverlay = e.target.classList.contains('aa-DetachedOverlay');

    // 2. Apply Desired Behaviors:
    // - If clicking "x" (.aa-ClearButton), we do NOTHING. Algolia natively handles this 
    //   by clearing the text and keeping the modal open. (If it was quitting before, 
    //   it was because our previous artificial events crashed the component).
    
    // - If clicking "Cancel" or "Background Overlay", we want to clear the text AND quit.
    if (isCancelButton || isOverlay) {
      // Find Algolia's native Clear Button (the "x" inside the search input)
      const clearButton = document.querySelector('.aa-ClearButton');
      
      // If the clear button exists, it means there is text in the input
      if (clearButton) {
        // Programmatically click the native clear button to safely reset Algolia's internal React state
        clearButton.click();
      }
      
      // We don't stop propagation. The event will continue down to the Cancel button 
      // or Overlay, allowing Algolia to natively close the modal.
    }
  }, { capture: true });
}
