#!/usr/bin/env python3
"""
Replace the mega menu JS in header.php with a definitive CSS + JS fix.
The approach: 
- Use CSS to make ::before overlay and JS to detect hover on specific elements
- Key insight from browser: elements with 'group-hover:block' class are the dropdowns
  These are generated Tailwind classes that don't work without the Tailwind JIT.
  We add a <style> block that mimics the Tailwind group-hover behavior purely in CSS
  by restoring the parent .group:hover > child [display] relationship.
"""

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

# This is the DEFINITIVE mega menu fix
# Strategy: Use CSS to add hover behavior directly without JS complexity
MEGA_MENU_BLOCK = '''<!-- SureCertificate Mega Menu Fix v3 -->
<style>
/* ====================================================
   DROPDOWN HOVER FIX
   The Tailwind 'group-hover:block' class doesn't work without Tailwind JIT.
   We replicate the effect by making divs with z-50 visible on parent hover.
   ==================================================== */

/* AI Courses, Enterprise, Resources dropdowns */
/* Target: div.group:hover > div.relative > div.absolute (the dropdown panel) */
div.group:hover > div.relative > div.absolute,
div.group:hover > div.relative + div.relative > div.absolute {
  display: flex !important;
  flex-direction: column;
}

/* The dropdown panels use 'hidden' class - remove it on group hover */
div.group:hover div[class*="z-50"].hidden,
div.group:hover div[class*="z-50"][class*="flex-col"].hidden {
  display: flex !important;
  flex-direction: column;
}

/* More specific: target the direct dropdown structure */
div.group:hover > div:last-child > div.absolute {
  display: flex !important;
  flex-direction: column;
}

/* Make sure the dropdowns with min-w class show on hover */
div.group:hover [class*="min-w-262"] {
  display: flex !important;
  flex-direction: column;
}
</style>
<script>
(function() {
  document.addEventListener('DOMContentLoaded', function() {

    // ============================================================
    // "All Courses" Mega Panel Toggle (click to show/hide sidebar)
    // ============================================================
    // Find the All Courses trigger button
    var allCoursesBtn = null;
    document.querySelectorAll('*').forEach(function(el) {
      if (el.childElementCount === 0 && el.textContent.trim() === 'All Courses') {
        var p = el.parentElement;
        for (var i = 0; i < 6; i++) {
          if (!p) break;
          // The trigger button has icon-menu
          if (p.querySelector && p.querySelector('.icon-menu')) {
            allCoursesBtn = p;
            break;
          }
          p = p.parentElement;
        }
      }
    });

    if (allCoursesBtn) {
      // The panel is the next div sibling with class "hidden" inside the same parent
      var parent = allCoursesBtn.parentElement;
      var panel = null;
      if (parent) {
        for (var i = 0; i < parent.children.length; i++) {
          var child = parent.children[i];
          if (child !== allCoursesBtn && child.classList && child.classList.contains('hidden')) {
            panel = child;
            break;
          }
        }
      }

      if (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:white;box-shadow:0 8px 40px rgba(0,0,0,0.2);max-height:calc(100vh - 72px);overflow-y:auto;';
            // Ensure inner flex div is properly laid out
            var flexDiv = panel.querySelector('div.flex');
            if (flexDiv) {
              flexDiv.style.cssText = 'display:flex;height:auto;max-height:calc(100vh - 72px);';
            }
          } else {
            panel.style.display = 'none';
          }
        });

        document.addEventListener('click', function(e) {
          if (isOpen && !panel.contains(e.target)) {
            isOpen = false;
            panel.style.display = 'none';
          }
        });
      }
    }

    // ============================================================
    // Dropdown menus: fix via JS hover since CSS may not match
    // Find all divs that have [class*="min-w-262"] (the dropdown panels)
    // and make their closest ancestor with 'group' in class work
    // ============================================================
    document.querySelectorAll('[class*="min-w-262"]').forEach(function(dropdown) {
      // Find the containing group ancestor
      var groupAncestor = dropdown.parentElement;
      while (groupAncestor) {
        if (groupAncestor.classList && groupAncestor.classList.contains('group')) {
          break;
        }
        groupAncestor = groupAncestor.parentElement;
      }
      if (!groupAncestor) return;

      // Get the outermost groupAncestor that is still before nav
      dropdown.classList.remove('hidden');
      dropdown.style.display = 'none';

      groupAncestor.addEventListener('mouseenter', function() {
        dropdown.style.display = 'flex';
        dropdown.style.flexDirection = 'column';
      });
      groupAncestor.addEventListener('mouseleave', function() {
        // Small delay to allow moving into dropdown
        setTimeout(function() {
          if (!groupAncestor.matches(':hover')) {
            dropdown.style.display = 'none';
          }
        }, 100);
      });
    });

  });
})();
</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: Could not find old mega menu block")
    exit(1)

# find end: the </script> after start
idx_end = content.find(OLD_MARKER_END, idx_start)
if idx_end < 0:
    print("ERROR: Could not find </script> after mega menu block")
    exit(1)
idx_end += len(OLD_MARKER_END)

print(f"Replacing block at [{idx_start}:{idx_end}] ({idx_end - idx_start} 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 v3 mega menu fix.")
