/**
 * WordPress Admin Menu Click Handler
 * Detects clicks on WordPress admin menu items and dispatches custom events
 * for React components to listen to.
 */

const MENU_EVENT_NAME = 'archivemaster:dashboard-click'
const DASHBOARD_MENU_HREF = 'admin.php?page=master-archives#/'

let observer = null

/**
 * Initialize menu click handler
 * Attaches click listeners to WordPress admin menu items
 */
export const initMenuClickHandler = () => {
  // Wait for DOM to be ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      attachMenuListeners()
      setupMutationObserver()
    })
  } else {
    attachMenuListeners()
    setupMutationObserver()
  }
}

/**
 * Attach click listeners to admin menu items
 */
const attachMenuListeners = () => {
  // Find all admin menu links
  const adminMenuLinks = document.querySelectorAll('#adminmenu a')

  adminMenuLinks.forEach(link => {
    // Check if this is the Dashboard menu link
    const href = link.getAttribute('href')
    if (href && href.includes(DASHBOARD_MENU_HREF)) {
      // Remove existing listener if any (to prevent duplicates)
      link.removeEventListener('click', handleDashboardMenuClick)
      // Add click listener
      link.addEventListener('click', handleDashboardMenuClick)
    }
  })
}

/**
 * Setup MutationObserver to watch for menu changes
 */
const setupMutationObserver = () => {
  const adminMenu = document.querySelector('#adminmenu')
  if (!adminMenu) {
    // Retry after a short delay if menu not found
    setTimeout(() => {
      const retryMenu = document.querySelector('#adminmenu')
      if (retryMenu) {
        attachMenuListeners()
        setupMutationObserver()
      }
    }, 500)
    return
  }

  // Clean up existing observer
  if (observer) {
    observer.disconnect()
  }

  // Watch for changes in the admin menu
  observer = new MutationObserver(() => {
    attachMenuListeners()
  })

  observer.observe(adminMenu, {
    childList: true,
    subtree: true
  })
}

/**
 * Handle Dashboard menu click
 * Dispatches custom event when Dashboard menu is clicked
 */
const handleDashboardMenuClick = (event) => {
  // Dispatch custom event that React components can listen to
  const customEvent = new CustomEvent(MENU_EVENT_NAME, {
    detail: {
      timestamp: Date.now(),
      href: event.target.closest('a')?.getAttribute('href')
    },
    bubbles: true
  })
  document.dispatchEvent(customEvent)
}

/**
 * Cleanup function to remove event listeners
 */
export const cleanupMenuClickHandler = () => {
  const adminMenuLinks = document.querySelectorAll('#adminmenu a')
  adminMenuLinks.forEach(link => {
    link.removeEventListener('click', handleDashboardMenuClick)
  })
  
  // Disconnect observer
  if (observer) {
    observer.disconnect()
    observer = null
  }
}

/**
 * Get the event name for external use
 */
export const getDashboardClickEventName = () => MENU_EVENT_NAME

