"""Test board creation using React-compatible input method."""
import sys, time
from pathlib import Path
sys.path.insert(0, '/app')
from pinterest.client import PinterestClient

TEST_BOARD_NAME = 'RMPropWorks Test Delete'

data_dir = Path('/app/data/pinterest')
with PinterestClient(data_dir) as client:
    client.is_authenticated()
    client.page.goto('https://www.pinterest.com/rmacsparran/_created/', timeout=60000)
    time.sleep(4)

    # Click Created tab
    action_bar = client.page.query_selector('[data-test-id="action-bar"]')
    if action_bar:
        for l in action_bar.query_selector_all('a, button, [role="tab"]'):
            if 'Created' in (l.inner_text() or ''):
                l.click()
                break
    time.sleep(5)
    client.page.evaluate('window.scrollTo(0, 500)')
    time.sleep(2)

    # Step 1: Open Create menu
    try:
        client.page.wait_for_selector('[data-test-id="boardActionsButton"]', timeout=10000)
    except Exception:
        pass
    create_btn = client.page.query_selector('[data-test-id="boardActionsButton"]')
    if not create_btn:
        print('ERROR: boardActionsButton not found')
        sys.exit(1)
    create_btn.click(force=True)
    time.sleep(2)

    # Step 2: Click "Create board" menu item
    board_item = client.page.query_selector('[data-test-id="Create board"]')
    if not board_item:
        print('Create board menu item not found!')
        sys.exit(1)
    client.page.evaluate('el => el.click()', board_item)
    time.sleep(2)

    # Step 3: Wait for name input — board name input, not search/collaborator
    # Board name input has placeholder like "Name" or "Board name", NOT "search" or "email"
    name_input = None
    for _ in range(10):
        time.sleep(0.5)
        all_inputs = client.page.query_selector_all('input[type="text"], input:not([type])')
        for inp in all_inputs:
            ph = (inp.get_attribute('placeholder') or '').lower()
            if 'search' not in ph and 'email' not in ph and 'collaborat' not in ph:
                name_input = inp
                print(f'Name input found: placeholder={inp.get_attribute("placeholder")!r}')
                break
        if name_input:
            break

    if not name_input:
        print('ERROR: Name input not found after retries')
        # Dump all inputs
        for inp in client.page.query_selector_all('input'):
            print(f'  input: type={inp.get_attribute("type")!r} placeholder={inp.get_attribute("placeholder")!r} name={inp.get_attribute("name")!r}')
        sys.exit(1)

    # Step 4: Use React native value setter to properly trigger onChange
    client.page.evaluate('''([el, value]) => {
        const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
            window.HTMLInputElement.prototype, 'value'
        ).set;
        nativeInputValueSetter.call(el, value);
        el.dispatchEvent(new Event('input', { bubbles: true }));
        el.dispatchEvent(new Event('change', { bubbles: true }));
    }''', [name_input, TEST_BOARD_NAME])
    time.sleep(0.5)

    # Check button state
    btn = client.page.query_selector('[data-test-id="board-form-submit-button"]')
    if btn:
        disabled = btn.get_attribute('disabled')
        txt = btn.inner_text().strip()
        print(f'Submit button: txt={txt!r} disabled={disabled!r}')
    else:
        print('Submit button not found with known testid, dumping buttons:')
        for b in client.page.query_selector_all('button'):
            t = (b.inner_text() or '').strip()
            d = b.get_attribute('disabled')
            tid = b.get_attribute('data-test-id') or ''
            if t and len(t) < 20:
                print(f'  btn: txt={t!r} disabled={d!r} testid={tid!r}')

    # Step 5: Click submit
    if btn:
        client.page.evaluate('el => el.click()', btn)
        print('Submit clicked')
    else:
        # Try pressing Enter
        client.page.keyboard.press('Enter')
        print('Pressed Enter')

    time.sleep(4)
    print('Final URL:', client.page.url)
