#!/usr/bin/env python3
"""Replace the entire script block in header.php with the new robust version."""

with open('/Applications/XAMPP/xamppfiles/htdocs/aaa/header.php', 'r', encoding='utf-8') as f:
    content = f.read()

# Find the <script> block boundaries
start_marker = '<script>\n(function() {'
end_marker = '})();\n</script>'

start_idx = content.find(start_marker)
end_idx = content.find(end_marker)

if start_idx == -1 or end_idx == -1:
    print("ERROR: Could not find script block markers!")
    print(f"  start_marker found: {start_idx > -1}")
    print(f"  end_marker found: {end_idx > -1}")
    # Try alternate detection
    s = content.find('<script>')
    e = content.rfind('</script>')
    print(f"  First <script> at: {s}")
    print(f"  Last </script> at: {e}")
    if s > 0 and e > 0:
        print("PREVIEW of JS block found:")
        print(content[s:s+100])
        print("...")
        print(content[e-100:e+10])
else:
    end_idx += len(end_marker)
    print(f"Found script block at [{start_idx}:{end_idx}]")
    
    NEW_SCRIPT = '''<script>
(function() {
  'use strict';

  function ready(fn) {
    if (document.readyState !== 'loading') fn();
    else document.addEventListener('DOMContentLoaded', fn);
  }

  ready(function() {

    // ===================================================
    // 1. LOGO FIX
    // ===================================================
    document.querySelectorAll('img[alt="kh logo"]').forEach(function(img) {
      img.style.position = 'relative';
      img.style.width = 'auto';
      img.style.height = '42px';
      img.style.maxWidth = '200px';
      img.style.objectFit = 'contain';
      img.style.left = '0'; img.style.top = '0';
      img.style.right = 'auto'; img.style.bottom = 'auto';
    });

    // ===================================================
    // 2. UPGRAD HERO IMAGE OVERLAY
    // ===================================================
    var logoPath = '/aaa/infinity_images/logo.png';
    function addOverlay(imgEl) {
      var par = imgEl.parentElement;
      if (!par || par.querySelector('.sc-brand-overlay')) return;
      if (window.getComputedStyle(par).position === 'static') par.style.position = 'relative';
      var ov = document.createElement('div');
      ov.className = 'sc-brand-overlay';
      ov.innerHTML = '<img src="' + logoPath + '" alt="SureCertificate" style="height:28px;width:auto;object-fit:contain;">';
      par.appendChild(ov);
    }
    document.querySelectorAll('img').forEach(function(img) {
      var src = (img.getAttribute('src') || '').toLowerCase();
      var alt = (img.getAttribute('alt') || '').toLowerCase();
      if (src.indexOf('homepage_banner') > -1 || src.indexOf('banner_agentic') > -1 ||
          alt.indexOf('upgrad') > -1 || alt.indexOf('upgrade your') > -1) {
        addOverlay(img);
      }
    });

    // ===================================================
    // 3. DROPDOWN MENUS (AI Courses, Enterprise, Resources)
    // ===================================================
    var dropdowns = [];
    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) {
        dropdowns.push(div);
      }
    });
    console.log('[SC] Dropdown panels found:', dropdowns.length);

    dropdowns.forEach(function(panel) {
      panel.classList.remove('hidden');
      panel.style.display = 'none';

      var group = panel;
      while (group && !group.classList.contains('group')) group = group.parentElement;
      if (!group) return;

      var timer;
      function show() { clearTimeout(timer); panel.style.display = 'flex'; panel.style.flexDirection = 'column'; }
      function hide() { timer = setTimeout(function() { panel.style.display = 'none'; }, 120); }

      group.addEventListener('mouseenter', show);
      group.addEventListener('mouseleave', hide);
      panel.addEventListener('mouseenter', show);
      panel.addEventListener('mouseleave', hide);
    });

    // ===================================================
    // 4. ALL COURSES PANEL
    // ===================================================
    var domainPanel = document.querySelector('.sc-all-domain-panel');
    var allCoursesBtn = null;

    document.querySelectorAll('.icon-menu').forEach(function(icon) {
      var p = icon.parentElement;
      while (p && p.tagName !== 'DIV') p = p.parentElement;
      if (p && p.textContent.indexOf('All Courses') > -1) allCoursesBtn = p;
    });

    if (!allCoursesBtn) {
      document.querySelectorAll('span').forEach(function(span) {
        if (span.textContent.trim() === 'All Courses') {
          var p = span.parentElement;
          if (p && p.querySelector && p.querySelector('.icon-menu')) allCoursesBtn = p;
        }
      });
    }

    console.log('[SC] domainPanel:', !!domainPanel, '| allCoursesBtn:', !!allCoursesBtn);

    if (domainPanel && allCoursesBtn) {
      var isOpen = false;

      function openPanel() {
        isOpen = true;
        var headerEl = document.querySelector('header');
        var headerBottom = headerEl ? headerEl.getBoundingClientRect().bottom : 112;
        domainPanel.style.cssText = [
          'display:block',
          'position:fixed',
          'top:' + headerBottom + 'px',
          'left:0',
          'right:0',
          'width:100%',
          'z-index:99999',
          'background:white',
          'box-shadow:0 8px 32px rgba(0,0,0,0.18)',
          'overflow:hidden',
          'max-height:calc(100vh - ' + headerBottom + 'px)'
        ].join(';');

        var inner = domainPanel.querySelector('[style*="height:calc"]');
        if (inner) {
          inner.style.height = 'auto';
          inner.style.maxHeight = 'calc(100vh - ' + headerBottom + 'px)';
          inner.style.overflowY = 'auto';
          inner.style.display = 'flex';
        }
      }

      function closePanel() {
        isOpen = false;
        domainPanel.style.display = 'none';
      }

      // Initially hide
      domainPanel.style.display = 'none';

      allCoursesBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        isOpen ? closePanel() : openPanel();
      });

      document.addEventListener('click', function(e) {
        if (isOpen && !domainPanel.contains(e.target) && !allCoursesBtn.contains(e.target)) {
          closePanel();
        }
      });
      domainPanel.addEventListener('click', function(e) { e.stopPropagation(); });

      // Domain item hover -> show right sub-panel
      domainPanel.querySelectorAll('.group').forEach(function(domainItem) {
        var subPanel = domainItem.querySelector('div.hidden, .hidden');
        if (!subPanel) return;
        subPanel.classList.remove('hidden');
        subPanel.style.display = 'none';

        var t;
        domainItem.addEventListener('mouseenter', function() {
          clearTimeout(t);
          subPanel.style.display = 'flex';
          subPanel.style.flexDirection = 'column';
        });
        domainItem.addEventListener('mouseleave', function() {
          t = setTimeout(function() { subPanel.style.display = 'none'; }, 120);
        });
        subPanel.addEventListener('mouseenter', function() { clearTimeout(t); });
        subPanel.addEventListener('mouseleave', function() {
          t = setTimeout(function() { subPanel.style.display = 'none'; }, 120);
        });
      });
    }

    // ===================================================
    // 5. BODY OVERFLOW FIX
    // ===================================================
    document.body.style.overflowY = 'auto';
    document.body.style.overflowX = 'hidden';

  }); // end ready
})();
</script>'''
    
    content = content[:start_idx] + NEW_SCRIPT + content[end_idx:]
    
    with open('/Applications/XAMPP/xamppfiles/htdocs/aaa/header.php', 'w', encoding='utf-8') as f:
        f.write(content)
    print("Script block replaced successfully!")
    print(f"New file length: {len(content)} bytes")
