from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp('http://localhost:9222')
    page = browser.contexts[0].pages[0]
    
    url = 'https://www.facebook.com/profile.php?id=61594841053758&sk=about_details'
    page.goto(url, wait_until='domcontentloaded', timeout=30000)
    page.wait_for_timeout(3000)
    
    # Tìm nút edit bút chì bên cạnh About You
    # Trên Facebook, các icon Options/Edit nằm trong container của mục đó
    print('Hovering on About You...')
    about_sec = page.locator("text=/Du học sinh & Content Creator/i").first
    about_sec.hover()
    page.wait_for_timeout(500)
    
    # Tìm nút có icon bút chì hoặc 3 chấm cạnh đó
    edit_btn = page.locator("div[role='main'] div[role='button']:has(i)").first
    print('Clicking edit button on About You...')
    edit_btn.click()
    page.wait_for_timeout(1000)
    
    # Nếu có menu mở ra (Edit, Delete), click 'Edit'
    menu_edit = page.locator("div[role='menuitem']:has-text('Edit'), span:has-text('Edit')").first
    if menu_edit.is_visible():
        menu_edit.click()
        page.wait_for_timeout(1000)
        
    textbox = page.locator("textarea").first
    if textbox.is_visible():
        print('Replacing Vietnamese text with English...')
        textbox.click()
        page.keyboard.down('Control')
        page.keyboard.press('a')
        page.keyboard.up('Control')
        page.keyboard.press('Backspace')
        
        en_text = '''Vietnamese Filmmaker & Creator based in California 🌴 Passionate about bringing ancient Asian history and legendary naval warfare to life through 4K animation. Founder & Producer of the 'Forgotten Battles' documentary series on YouTube 🇻🇳🇺🇸'''
        textbox.fill(en_text)
        page.wait_for_timeout(1000)
        
        save_btn = page.locator("div[aria-label='Save'], button:has-text('Save')").first
        if save_btn.is_visible():
            save_btn.click()
            print('Successfully saved English Details!')
            page.wait_for_timeout(3000)
            
    browser.close()
