#!/usr/bin/env python3
"""
Copy COMPLETE navigation system from index.html to all product pages.
Includes: nav HTML, mobile dropdown, JavaScript, and CSS.
"""

import re

# Read index.html
with open('/root/clawd/stroller-app/index.html', 'r') as f:
    index_content = f.read()

# ═══ PART 1: Extract Navigation HTML (nav + mobile dropdown) ═══
nav_start = index_content.find('<nav class="site-nav">')
if nav_start == -1:
    print("ERROR: Could not find nav in index.html")
    exit(1)

# Find the end of nav-mobile div (which comes AFTER </nav>)
nav_mobile_start = index_content.find('<div class="nav-mobile"', nav_start)
nav_mobile_end = index_content.find('</div>', nav_mobile_start)

if nav_mobile_end == -1:
    print("ERROR: Could not find nav-mobile end")
    exit(1)

# Extract full nav section (nav + mobile dropdown)
full_nav_html = index_content[nav_start:nav_mobile_end + 6]  # +6 for </div>

print(f"✓ Extracted nav HTML ({len(full_nav_html)} chars)")

# ═══ PART 2: Extract toggleMobileNav JavaScript ═══
js_start = index_content.find('function toggleMobileNav()')
if js_start == -1:
    print("ERROR: Could not find toggleMobileNav function")
    exit(1)

# Find the end of the function (closing brace)
brace_count = 0
i = index_content.find('{', js_start)
js_end = i
for char in index_content[i:]:
    if char == '{':
        brace_count += 1
    elif char == '}':
        brace_count -= 1
        if brace_count == 0:
            js_end = index_content.find('}', js_end) + 1
            break
    js_end += 1

toggle_function = index_content[js_start:js_end]
print(f"✓ Extracted toggleMobileNav() ({len(toggle_function)} chars)")

# ═══ PART 3: Extract Navigation CSS ═══
# Find all nav-related CSS (from .site-nav to end of @media mobile styles)
css_start = index_content.find('.site-nav {')
if css_start == -1:
    print("ERROR: Could not find nav CSS")
    exit(1)

# Find the end - look for the next major section (usually .hero or main content styles)
# Go through @media queries too
css_end = index_content.find('@media (max-width: 768px)', css_start)
if css_end > css_start:
    # Find the end of the media query
    # Look for the closing brace of @media block
    media_brace_count = 0
    i = index_content.find('{', css_end)
    for idx in range(i, len(index_content)):
        if index_content[idx] == '{':
            media_brace_count += 1
        elif index_content[idx] == '}':
            media_brace_count -= 1
            if media_brace_count == 0:
                css_end = idx + 1
                break

nav_css = index_content[css_start:css_end]
print(f"✓ Extracted nav CSS ({len(nav_css)} chars)")

# ═══ PART 4: Define pages to update ═══
pages_to_update = {
    'diapers.html': 'diapers.html',
    'formula.html': 'formula.html',
    'wipes.html': 'wipes.html',
    'bottles.html': 'bottles.html',
    'breast-pumps.html': 'breast-pumps.html',
    'baby-monitors.html': 'baby-monitors.html'
}

def get_nav_with_active(nav_html, active_page):
    """Set the correct active class for a given page"""
    # Remove all existing active classes
    nav = re.sub(r'class="nav-link active"', 'class="nav-link"', nav_html)
    
    # Add active to the correct page (in both desktop and mobile nav)
    nav = nav.replace(
        f'href="{active_page}" class="nav-link"',
        f'href="{active_page}" class="nav-link active"'
    )
    
    return nav

# ═══ PART 5: Update each page ═══
for filename, active_page in pages_to_update.items():
    filepath = f'/root/clawd/stroller-app/{filename}'
    
    try:
        with open(filepath, 'r') as f:
            html = f.read()
    except FileNotFoundError:
        print(f'⚠️  {filename} not found, skipping')
        continue
    
    print(f'\n─── Processing {filename} ───')
    
    # Get nav with correct active state
    page_nav = get_nav_with_active(full_nav_html, active_page)
    
    # ═══ Step 1: Replace nav HTML ═══
    # Find existing nav
    old_nav_start = html.find('<nav class="site-nav">')
    if old_nav_start == -1:
        # No nav found, insert after <body>
        body_pos = html.find('<body>')
        if body_pos == -1:
            print(f'  ⚠️  No <body> tag found, skipping')
            continue
        html = html[:body_pos + 6] + '\n  ' + page_nav + '\n' + html[body_pos + 6:]
        print(f'  ✓ Inserted new nav (no existing nav found)')
    else:
        # Find end of old nav section
        # Look for either </nav> or nav-mobile div end
        old_nav_end = html.find('</nav>', old_nav_start)
        
        # Check if there's a nav-mobile div after it
        nav_mobile_pos = html.find('<div class="nav-mobile"', old_nav_start)
        if nav_mobile_pos > old_nav_start and nav_mobile_pos < old_nav_end + 100:
            # Has mobile nav, include it
            old_nav_end = html.find('</div>', nav_mobile_pos) + 6
        else:
            old_nav_end = old_nav_end + 6  # +6 for </nav>
        
        # Replace
        html = html[:old_nav_start] + page_nav + html[old_nav_end:]
        print(f'  ✓ Replaced nav HTML')
    
    # ═══ Step 2: Ensure toggleMobileNav function exists ═══
    if 'function toggleMobileNav()' not in html:
        # Find a good place to insert it (usually before closing </script> tag near the end)
        # Or before the closing </body>
        script_insert = html.rfind('</script>')
        if script_insert != -1:
            html = html[:script_insert] + toggle_function + '\n\n' + html[script_insert:]
            print(f'  ✓ Added toggleMobileNav() function')
        else:
            print(f'  ⚠️  Could not find place to insert JavaScript')
    else:
        print(f'  - toggleMobileNav() already exists')
    
    # ═══ Step 3: Nav CSS is now in css/nav.css (shared file) — skip inline injection ═══
    print(f'  - Nav CSS handled by css/nav.css')
    
    # Write updated HTML
    with open(filepath, 'w') as f:
        f.write(html)
    
    print(f'  ✅ Updated {filename}')

print('\n' + '═'*50)
print('✅ All pages updated with complete navigation system!')
print('   - Nav HTML (desktop + mobile dropdown)')
print('   - toggleMobileNav() JavaScript')
print('   - Complete CSS (desktop + mobile)')
print('='*50)
