use night_fury_core::BrowserSession;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let session = BrowserSession::builder()
        .connect_to("ws://127.0.0.1:9222")
        .build()
        .await?;

    session.navigate("https://grok.com").await?;

    // Wait for Cloudflare to resolve — poll every 2 seconds
    for i in 0..15 {
        tokio::time::sleep(Duration::from_secs(2)).await;
        let title = session.eval("document.title").await?;
        let title_str = title.as_str().unwrap_or("");
        println!("[{}s] title={}", (i + 1) * 2, title_str);
        if title_str == "Grok" {
            println!("Cloudflare passed!");
            break;
        }
    }

    // Check final state
    let scan = session
        .eval(
            r#"
    JSON.stringify({
        title: document.title,
        textareas: document.querySelectorAll('textarea').length,
        buttons: document.querySelectorAll('button').length,
        bodySnippet: document.body?.innerText?.substring(0, 200)
    })
    "#,
        )
        .await?;
    println!("Final state: {}", scan);

    Ok(())
}
