#!/usr/bin/env python3
"""
Fix JS bugs across all product pages:
1. countrySelect → marketSelect (ID mismatch)
2. Add ProductI18n.changeMarket() on country change
3. Add ProductI18n.changeLanguage() on language change
"""

pages = ['diapers.html', 'formula.html', 'bottles.html', 'wipes.html', 'breast-pumps.html', 'baby-monitors.html']

for filename in pages:
    filepath = f'/root/clawd/stroller-app/{filename}'
    try:
        with open(filepath, 'r') as f:
            html = f.read()
    except FileNotFoundError:
        print(f'⚠️  {filename} not found')
        continue

    original = html

    # Fix 1: countrySelect → marketSelect
    html = html.replace("getElementById('countrySelect')", "getElementById('marketSelect')")
    html = html.replace('getElementById("countrySelect")', 'getElementById("marketSelect")')

    # Fix 2: On market change, call ProductI18n.changeMarket() if not already there
    # Pattern: after TrueBabyCost.changeMarket(e.target.value) in the cs.addEventListener
    old = "await TrueBabyCost.changeMarket(e.target.value); renderProducts();"
    new = "await TrueBabyCost.changeMarket(e.target.value); if (typeof ProductI18n !== 'undefined') { await ProductI18n.changeMarket(e.target.value); } renderProducts();"
    html = html.replace(old, new)

    # Also minified version (no spaces)
    old2 = "await TrueBabyCost.changeMarket(e.target.value);renderProducts();"
    new2 = "await TrueBabyCost.changeMarket(e.target.value);if(typeof ProductI18n!=='undefined'){await ProductI18n.changeMarket(e.target.value);}renderProducts();"
    html = html.replace(old2, new2)

    # Fix 3: On language change, call ProductI18n.changeLanguage() if not already there
    old3 = "await TrueBabyCost.changeLanguage(e.target.value); renderProducts();"
    new3 = "await TrueBabyCost.changeLanguage(e.target.value); if (typeof ProductI18n !== 'undefined') { await ProductI18n.changeLanguage(e.target.value); } renderProducts();"
    html = html.replace(old3, new3)

    old4 = "await TrueBabyCost.changeLanguage(e.target.value);renderProducts();"
    new4 = "await TrueBabyCost.changeLanguage(e.target.value);if(typeof ProductI18n!=='undefined'){await ProductI18n.changeLanguage(e.target.value);}renderProducts();"
    html = html.replace(old4, new4)

    if html != original:
        with open(filepath, 'w') as f:
            f.write(html)
        print(f'✓ Fixed JS bugs in {filename}')
    else:
        print(f'- No changes needed in {filename}')

print('\n✅ JS fixes applied')
