import glob
import re
import os

def align_dropdowns():
    html_files = glob.glob('*.html')
    
    for file_path in html_files:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            
        original_content = content
        
        # 1. Remove hardcoded left css properties
        content = re.sub(r'#ministries-mega\s*\{\s*left:\s*\d+px;\s*\}', '#ministries-mega {\n  }', content)
        content = re.sub(r'#community-mega\s*\{\s*left:\s*\d+px;\s*\}', '#community-mega {\n  }', content)
        
        # 2. Add dynamic positioning in JS
        js_find = """      toggle.addEventListener('mouseenter', function() {
        clearTimeout(hoverTimeout);
        document.querySelectorAll('.fs-mega-menu').forEach(menu => {
          if (menu.id !== menuId) menu.classList.remove('show');
        });
        megaMenu.classList.add('show');
      });"""
        
        js_replace = """      toggle.addEventListener('mouseenter', function() {
        clearTimeout(hoverTimeout);
        document.querySelectorAll('.fs-mega-menu').forEach(menu => {
          if (menu.id !== menuId) menu.classList.remove('show');
        });
        
        // Position exactly under the main menu item
        const rect = toggle.getBoundingClientRect();
        megaMenu.style.left = rect.left + 'px';
        
        megaMenu.classList.add('show');
      });"""
        
        # In case the exact formatting doesn't match perfectly, we can use a regex replacement
        if js_find in content:
            content = content.replace(js_find, js_replace)
        else:
            # Fallback regex just in case
            regex_find = r"(toggle\.addEventListener\('mouseenter',\s*function\(\)\s*\{[\s\S]*?megaMenu\.classList\.add\('show'\);\s*\}\);)"
            
            def replace_func(match):
                block = match.group(1)
                if 'megaMenu.style.left' not in block:
                    return block.replace("megaMenu.classList.add('show');", "const rect = toggle.getBoundingClientRect();\n        megaMenu.style.left = rect.left + 'px';\n        megaMenu.classList.add('show');")
                return block
                
            content = re.sub(regex_find, replace_func, content)
            
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"Updated {file_path}")

if __name__ == '__main__':
    align_dropdowns()
