#!/usr/bin/env python3
"""
DEFINITIVE mega menu fix for header.php.
Uses the EXACT class names found in the DOM to locate dropdown panels.
"""

HEADER_PATH = '/Applications/XAMPP/xamppfiles/htdocs/aaa/header.php'

# Exact class string from the DOM inspection
# class=" absolute  z-50 flex-col hidden border border-neutral-200  bg-white ..."
# The key distinguishing feature: contains 'group-hover:block' and 'z-50' and 'hidden'

MEGA_MENU_BLOCK = '''<!-- SureCertificate Mega Menu Fix v4 -->
<style>
/* Remove Tailwind's display:none from group-hover:block since we handle it via JS */
</style>
<script>
(function() {
  document.addEventListener('DOMContentLoaded', function() {

    // ============================================================
    // UTILITY: Find dropdown panels by their exact class signature
    // Class contains: 'z-50', 'hidden', 'group-hover:block', 'min-w-262'
    // ============================================================
    var allDropdowns = [];
    document.querySelectorAll('div').forEach(function(div) {
      var cls = div.className || '';
      if (cls.indexOf('z-50') > -1 && cls.indexOf('min-w-262') > -1 && cls.indexOf('hidden') > -1) {
        allDropdowns.push(div);
      }
    });

    console.log('[SC Menu] Found ' + allDropdowns.length + ' dropdown panels');

    // For each dropdown, find its .group ancestor and wire up hover
    allDropdowns.forEach(function(dropdown) {
      // Remove 'hidden' class but keep hidden via display:none so we control it
      dropdown.classList.remove('hidden');
      dropdown.style.display = 'none';

      // Walk up to find the .group ancestor
      var groupEl = dropdown.parentElement;
      while (groupEl) {
        if (groupEl.classList && groupEl.classList.contains('group')) break;
        groupEl = groupEl.parentElement;
      }

      if (!groupEl) {
        console.log('[SC Menu] No .group ancestor found for dropdown');
        return;
      }

      // Hover events on the group
      groupEl.addEventListener('mouseenter', function() {
        dropdown.style.display = 'flex';
        dropdown.style.flexDirection = 'column';
      });
      groupEl.addEventListener('mouseleave', function() {
        dropdown.style.display = 'none';
      });
      // Stay visible when hovering inside dropdown itself
      dropdown.addEventListener('mouseenter', function() {
        dropdown.style.display = 'flex';
        dropdown.style.flexDirection = 'column';
      });
      dropdown.addEventListener('mouseleave', function() {
        dropdown.style.display = 'none';
      });
    });

    // ============================================================
    // "All Courses" Panel Toggle
    // The panel is class "hidden" sibling of the All Courses trigger
    // ============================================================
    var allCoursesBtn = null;
    document.querySelectorAll('span, div').forEach(function(el) {
      if (el.childNodes.length === 1 && el.childNodes[0].nodeType === 3 &&
          el.textContent.trim() === 'All Courses') {
        var p = el;
        for (var i = 0; i < 7; i++) {
          p = p && p.parentElement;
          if (!p) break;
          if (p.querySelector && p.querySelector('.icon-menu') && p.classList.contains('cursor-pointer')) {
            allCoursesBtn = p;
            break;
          }
        }
      }
    });

    if (allCoursesBtn) {
      console.log('[SC Menu] Found All Courses button');
      // Look for a hidden sibling div (the dropdown panel)
      var parent = allCoursesBtn.parentElement;
      var panel = null;
      if (parent) {
        for (var ii = 0; ii < parent.children.length; ii++) {
          var child = parent.children[ii];
          if (child !== allCoursesBtn && child.tagName === 'DIV' && child.classList.contains('hidden')) {
            panel = child;
            break;
          }
        }
      }

      if (panel) {
        console.log('[SC Menu] Found All Courses panel');
        var isOpen = false;
        panel.classList.remove('hidden');
        panel.style.display = 'none';

        allCoursesBtn.addEventListener('click', function(e) {
          e.stopPropagation();
          isOpen = !isOpen;
          if (isOpen) {
            panel.style.cssText = [
              'display:block',
              'position:fixed',
              'top:72px',
              'left:0',
              'right:0',
              'z-index:99999',
              'background:#f8f9fa',
              'box-shadow:0 10px 40px rgba(0,0,0,0.15)',
              'max-height:calc(100vh - 72px)',
              'overflow-y:auto'
            ].join(';');
            var innerFlex = panel.querySelector('div.flex');
            if (innerFlex) {
              innerFlex.style.maxHeight = 'calc(100vh - 72px)';
              innerFlex.style.overflow = 'auto';
              innerFlex.style.height = 'auto';
            }
          } else {
            panel.style.display = 'none';
          }
        });

        document.addEventListener('click', function(e) {
          if (isOpen && !allCoursesBtn.contains(e.target) && !panel.contains(e.target)) {
            isOpen = false;
            panel.style.display = 'none';
          }
        });
      } else {
        console.log('[SC Menu] All Courses panel NOT found');
      }
    } else {
      console.log('[SC Menu] All Courses button NOT found');
    }

  });
})();
</script>'''

with open(HEADER_PATH, 'r', encoding='utf-8') as f:
    content = f.read()

OLD_MARKER_START = '<!-- SureCertificate Mega Menu Fix'
OLD_MARKER_END   = '</script>'

idx_start = content.find(OLD_MARKER_START)
if idx_start < 0:
    print("ERROR: Cannot find the old mega menu block")
    exit(1)

idx_end = content.find(OLD_MARKER_END, idx_start)
if idx_end < 0:
    print("ERROR: Cannot find closing </script>")
    exit(1)
idx_end += len(OLD_MARKER_END)

old_block_len = idx_end - idx_start
print(f"Replacing block ({old_block_len} chars) with new v4 block ({len(MEGA_MENU_BLOCK)} chars)")

content = content[:idx_start] + MEGA_MENU_BLOCK + content[idx_end:]

with open(HEADER_PATH, 'w', encoding='utf-8') as f:
    f.write(content)

print("Done! header.php updated with v4 mega menu fix (uses exact class matching).")
