#!/usr/bin/env python3
"""
MASTER FIX SCRIPT for SureCertificate website.
Fixes:
1. Logo display (squished logo on homepage)
2. upGrad text/logo replacement with SureCertificate branding via CSS/JS
3. Mega menu - proper KH-style with domain panel + hover subcategories
4. Inner pages - fix overflow:hidden body and CSS issues
"""

import re, os

HEADER_PATH = '/Applications/XAMPP/xamppfiles/htdocs/aaa/header.php'
CUSTOM_CSS_PATH = '/Applications/XAMPP/xamppfiles/htdocs/aaa/assets/css/custom-brand.css'

# ============================================================
# 1. Read header.php and extract its mega menu section
# ============================================================
with open(HEADER_PATH, 'r', encoding='utf-8') as f:
    header_content = f.read()

# ============================================================
# BUILD THE REPLACEMENT MEGA MENU BLOCK
# ============================================================

MEGA_MENU_REPLACEMENT = '''<!-- SureCertificate Master Fix v5 -->
<style>
/* ===== LOGO FIX ===== */
/* Fix squished logo - the img has position:absolute which distorts it */
img[alt="kh logo"],
a[href="/"] img,
header img[src*="logo"],
img[src*="logo.png"] {
  object-fit: contain !important;
  object-position: left center !important;
}

/* ===== UPGRAD LOGO OVERLAY ===== */
/* Hide upGrad text/logo and replace with SureCertificate */
/* The upGrad branding appears in images and as text */
.sc-logo-overlay-container {
  position: relative;
  display: inline-block;
}

/* ===== MEGA MENU FIX ===== */
/* All Courses panel and hover dropdowns */
.sc-all-courses-panel {
  display: none;
  position: fixed;
  top: 72px;
  left: 0;
  right: 0;
  z-index: 99999;
  background: white;
  box-shadow: 0 10px 40px rgba(0,0,0,0.15);
  max-height: calc(100vh - 72px);
  overflow-y: auto;
}
.sc-all-courses-panel.sc-open {
  display: block;
}

/* ===== INNER PAGE FIX ===== */
/* Remove overflow:hidden from body that blocks scrolling */
body {
  overflow: visible !important;
  overflow-x: hidden !important;
}

/* ===== DROPDOWN MENUS (AI Courses, Enterprise, Resources) ===== */
div.group:hover > div > div[class*="z-50"][class*="min-w-262"],
div.group:hover > div > div[class*="z-50"][class*="shadow-tooltip"] {
  display: flex !important;
  flex-direction: column !important;
}
</style>

<script>
(function() {
  'use strict';

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

  // ===== LOGO FIX =====
  ready(function() {

    // Fix squished logo container
    document.querySelectorAll('img[alt="kh logo"], img[src*="logo.png"]').forEach(function(img) {
      img.style.cssText = 'position:relative !important; width:auto !important; height:65px !important; object-fit:contain !important; max-width:240px !important; margin-top:-6px;';
      var parent = img.parentElement;
      while (parent) {
        if (parent.classList.contains('relative') && parent.style.position !== '') {
          parent.style.cssText = 'position:relative; width:240px; height:65px; overflow:visible; display:flex; align-items:center;';
          break;
        }
        parent = parent.parentElement;
      }
    });

    // ===================================================
    // UPGRAD LOGO/TEXT OVERLAY WITH SURECERTIFICATE LOGO
    // ===================================================
    // 1. Replace "upGrad" / "upgrad" / "KnowledgeHut" text nodes
    var logoPath = '/aaa/infinity_images/logo.png';
    var logoHtml = '<img src="' + logoPath + '" alt="SureCertificate" style="height:36px;width:auto;object-fit:contain;vertical-align:middle;">';

    // 2. Overlay on images containing upGrad branding
    // The hero banner shows upGrad watermark - we overlay our logo on top-left
    function addOverlayToImage(imgEl) {
      var parent = imgEl.parentElement;
      if (!parent) return;
      // Check if already overlaid
      if (parent.querySelector('.sc-brand-overlay')) return;
      var curPos = window.getComputedStyle(parent).position;
      if (curPos === 'static') parent.style.position = 'relative';

      var overlay = document.createElement('div');
      overlay.className = 'sc-brand-overlay';
      overlay.style.cssText = [
        'position:absolute',
        'top:12px',
        'left:12px',
        'z-index:10',
        'background:rgba(255,255,255,0.92)',
        'border-radius:8px',
        'padding:6px 10px',
        'display:flex',
        'align-items:center',
        'gap:6px',
        'box-shadow:0 2px 8px rgba(0,0,0,0.15)'
      ].join(';');
      overlay.innerHTML = '<img src="' + logoPath + '" alt="SureCertificate" style="height:30px;width:auto;object-fit:contain;">';
      parent.appendChild(overlay);
    }

    // Target the hero banner (has upGrad watermark text)
    document.querySelectorAll('img').forEach(function(img) {
      var src = img.getAttribute('src') || '';
      var alt = img.getAttribute('alt') || '';
      // Images that contain upGrad visual branding (promo banners, hero sections)
      if (src.toLowerCase().indexOf('homepage_banner') > -1 ||
          src.toLowerCase().indexOf('banner_agentic') > -1 ||
          alt.toLowerCase().indexOf('upgrade') > -1 ||
          alt.toLowerCase().indexOf('upgrad') > -1) {
        addOverlayToImage(img);
      }
    });

    // 3. Replace upGrad text nodes in hero section
    function replaceUpGradText(node) {
      if (node.nodeType === 3) { // text node
        if (/upGrad|upgrad|KnowledgeHut/i.test(node.textContent)) {
          // Only replace visible branded text not inside img
          var parent = node.parentElement;
          if (parent && parent.tagName !== 'SCRIPT' && parent.tagName !== 'STYLE') {
            // Keep the text as-is for now; logo image handles branding
          }
        }
      }
    }

    // ===================================================
    // MEGA MENU - DROPDOWN HOVER FIX
    // ===================================================
    // Find all dropdown panels by class signature: z-50 + min-w-262 + hidden
    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] Found ' + allDropdowns.length + ' nav dropdown panels');

    allDropdowns.forEach(function(dropdown) {
      dropdown.classList.remove('hidden');
      dropdown.style.display = 'none';

      // Find .group ancestor
      var groupEl = dropdown.parentElement;
      while (groupEl && !groupEl.classList.contains('group')) {
        groupEl = groupEl.parentElement;
      }
      if (!groupEl) return;

      var hideTimer;
      function showMenu() {
        clearTimeout(hideTimer);
        dropdown.style.display = 'flex';
        dropdown.style.flexDirection = 'column';
      }
      function hideMenu() {
        hideTimer = setTimeout(function() {
          dropdown.style.display = 'none';
        }, 150);
      }

      groupEl.addEventListener('mouseenter', showMenu);
      groupEl.addEventListener('mouseleave', hideMenu);
      dropdown.addEventListener('mouseenter', showMenu);
      dropdown.addEventListener('mouseleave', hideMenu);
    });

    // ===================================================
    // ALL COURSES MEGA PANEL (sidebar with domains)
    // ===================================================
    var allCoursesBtn = null;
    document.querySelectorAll('*').forEach(function(el) {
      if (el.childNodes.length >= 1 &&
          el.textContent.trim() === 'All Courses' &&
          el.tagName !== 'SCRIPT') {
        var p = el;
        for (var i = 0; i < 8; i++) {
          p = p && p.parentElement;
          if (!p) break;
          if (p.querySelector && p.querySelector('.icon-menu')) {
            allCoursesBtn = p;
            break;
          }
        }
      }
    });

    if (allCoursesBtn) {
      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.tagName === 'DIV' &&
              child.classList.contains('hidden')) {
            panel = child;
            break;
          }
        }
      }
      if (!panel) {
        // Try: the panel might be inside the same wrapper, look for it by content
        var wrapper = allCoursesBtn.parentElement && allCoursesBtn.parentElement.parentElement;
        if (wrapper) {
          var hiddenDivs = wrapper.querySelectorAll('div.hidden');
          hiddenDivs.forEach(function(d) {
            if (d.querySelector('.icon-ai') || d.textContent.indexOf('Artificial Intelligence') > -1) {
              panel = d;
            }
          });
        }
      }

      console.log('[SC] All Courses btn found:', !!allCoursesBtn, '| Panel found:', !!panel);

      if (panel) {
        // Mark panel and un-hide but control via display
        panel.classList.remove('hidden');
        panel.style.display = 'none';
        panel.classList.add('sc-all-courses-panel');

        var isOpen = false;

        allCoursesBtn.addEventListener('click', function(e) {
          e.stopPropagation();
          isOpen = !isOpen;
          panel.classList.toggle('sc-open', isOpen);
          if (isOpen) {
            // Ensure panel content is scrollable
            var innerFlex = panel.querySelector('.flex');
            if (innerFlex) {
              innerFlex.style.minHeight = '400px';
              innerFlex.style.maxHeight = 'calc(100vh - 72px)';
              innerFlex.style.overflowY = 'auto';
            }
          }
        });

        document.addEventListener('click', function(e) {
          if (isOpen && !panel.contains(e.target) && !allCoursesBtn.contains(e.target)) {
            isOpen = false;
            panel.classList.remove('sc-open');
          }
        });
        panel.addEventListener('click', function(e) { e.stopPropagation(); });
      }
    } else {
      console.log('[SC] All Courses button NOT found');
    }

    // ===================================================
    // INNER PAGE BODY FIX - Remove overflow:hidden
    // ===================================================
    document.body.style.overflowX = 'hidden';
    document.body.style.overflowY = 'auto';

    // Also fix any position:fixed header height mismatch
    var headers = document.querySelectorAll('header, [class*="sticky"]');
    headers.forEach(function(h) {
      if (h.style && h.style.overflowY === 'hidden') h.style.overflowY = 'visible';
    });

  }); // end ready

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

# Find and replace the old mega menu block
OLD_MARKER_START = '<!-- SureCertificate Mega Menu Fix'
OLD_MARKER_END   = '</script>'

idx_start = header_content.find(OLD_MARKER_START)
if idx_start < 0:
    print("ERROR: Cannot find old mega menu block. Looking for any injection point...")
    # Try to inject before </head>
    inject_before = '</head>'
    idx_inject = header_content.find(inject_before)
    if idx_inject >= 0:
        header_content = header_content[:idx_inject] + MEGA_MENU_REPLACEMENT + '\n' + header_content[idx_inject:]
        print("Injected before </head>")
    else:
        print("ERROR: Cannot find </head> either!")
        exit(1)
else:
    idx_end = header_content.find(OLD_MARKER_END, idx_start)
    if idx_end < 0:
        print("ERROR: Cannot find </script> after mega menu block")
        exit(1)
    idx_end += len(OLD_MARKER_END)
    old_len = idx_end - idx_start
    print(f"Replacing old block ({old_len} chars) with new v5 block ({len(MEGA_MENU_REPLACEMENT)} chars)")
    header_content = header_content[:idx_start] + MEGA_MENU_REPLACEMENT + header_content[idx_end:]

with open(HEADER_PATH, 'w', encoding='utf-8') as f:
    f.write(header_content)
print("Done! header.php updated.")

# ============================================================
# 2. Update custom-brand.css with comprehensive fixes
# ============================================================
os.makedirs(os.path.dirname(CUSTOM_CSS_PATH), exist_ok=True)

CUSTOM_CSS = '''/* ================================================================
   SureCertificate Custom Brand CSS
   Comprehensive fixes for logo, inner pages, overflow, branding
   ================================================================ */

/* ===== BODY OVERFLOW FIX ===== */
/* The original Next.js CSS sets overflow:hidden on body which breaks scrolling */
html, body {
  overflow-x: hidden !important;
}
body {
  overflow-y: auto !important;
}

/* ===== LOGO FIX ===== */
/* The logo img has position:absolute with explicit width:100% height:100% 
   which squishes it into its container dimensions */
img[alt="kh logo"] {
  position: relative !important;
  width: auto !important;
  height: 65px !important;
  max-width: 240px !important;
  object-fit: contain !important;
  object-position: left center !important;
  left: 0 !important;
  top: 0 !important;
  margin-top: -6px !important;
}
/* The span container that wraps the logo */
span.relative:has(img[alt="kh logo"]),
div.relative:has(img[alt="kh logo"]) {
  width: 240px !important;
  height: 65px !important;
  overflow: visible !important;
  display: block !important;
}

/* ===== NAV AND HEADER FIXES ===== */
/* Ensure nav is visible and not clipped */
header, nav, section:first-child {
  overflow: visible !important;
}

/* ===== INNER PAGE FIXES ===== */
/* Prevent content overflow issues on course pages */
main, [role="main"],
div#__next > div,
div#__next > section {
  overflow: visible !important;
}

/* Fix z-index stacking on inner pages */
.sticky, [class*="sticky"] {
  z-index: 1000;
}

/* ===== MEGA MENU STYLES ===== */
.sc-all-courses-panel {
  display: none;
}
.sc-all-courses-panel.sc-open {
  display: block !important;
  position: fixed !important;
  top: 72px !important;
  left: 0 !important;
  right: 0 !important;
  z-index: 99999 !important;
  background: white !important;
  box-shadow: 0 10px 40px rgba(0,0,0,0.18) !important;
  max-height: calc(100vh - 72px) !important;
  overflow-y: auto !important;
}

/* ===== UPGRAD OVERLAY BRANDING ===== */
.sc-brand-overlay {
  position: absolute;
  top: 12px;
  left: 12px;
  z-index: 10;
  background: rgba(255,255,255,0.92);
  border-radius: 8px;
  padding: 6px 10px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}

/* ===== SCROLLBAR FIX (inner pages) ===== */
::-webkit-scrollbar {
  width: 6px;
}
::-webkit-scrollbar-track {
  background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
  background: #5DA363;
  border-radius: 3px;
}

/* ===== COLOR BRAND OVERRIDES ===== */
/* Replace upGrad orange with SureCertificate green accent */
.text-primary-main {
  color: #5DA363 !important;
}
.bg-primary-main {
  background-color: #5DA363 !important;
}
.border-primary-main {
  border-color: #5DA363 !important;
}
'''

with open(CUSTOM_CSS_PATH, 'w', encoding='utf-8') as f:
    f.write(CUSTOM_CSS)
print(f"Done! custom-brand.css updated ({len(CUSTOM_CSS)} chars).")

print("\n=== All fixes applied! ===")
