//! Example of using orb-browse TUI widget
//!
//! Run with: cargo run --example widget --features="webdriver,tui"

use orb_browse::{OrbBrowser, widget::{BrowserWidget, BrowserState, BrowserEvent}};
use ratatui::{
    backend::CrosstermBackend,
    crossterm::{
        event::{self, Event, KeyCode},
        execute,
        terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
    },
    layout::{Constraint, Direction, Layout},
    widgets::{Block, Borders, Paragraph},
    Terminal,
};
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // Create browser
    let browser = OrbBrowser::new().await?;
    let mut state = BrowserState::new();

    // Navigate to initial URL
    println!("Navigating to example.com...");
    state.navigate(&browser, "https://example.com".to_string()).await?;

    // Run TUI loop
    loop {
        terminal.draw(|f| {
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([
                    Constraint::Min(1),
                    Constraint::Length(3),
                ])
                .split(f.area());

            // Render browser widget
            let widget = BrowserWidget::new(&state)
                .block(Block::default()
                    .title("orb-browse TUI Widget")
                    .borders(Borders::ALL));
            f.render_widget(widget, chunks[0]);

            // Render controls
            let controls = Paragraph::new("Press 'q' to quit | 'r' to refresh | ↑↓ to scroll")
                .block(Block::default()
                    .title("Controls")
                    .borders(Borders::ALL));
            f.render_widget(controls, chunks[1]);
        })?;

        // Handle input
        if event::poll(std::time::Duration::from_millis(100))? {
            if let Event::Key(key) = event::read()? {
                match key.code {
                    KeyCode::Char('q') => break,
                    KeyCode::Char('r') => {
                        state.handle_event(&browser, BrowserEvent::Refresh).await?;
                    }
                    KeyCode::Up => {
                        state.handle_event(&browser, BrowserEvent::ScrollUp).await?;
                    }
                    KeyCode::Down => {
                        state.handle_event(&browser, BrowserEvent::ScrollDown).await?;
                    }
                    _ => {}
                }
            }
        }
    }

    // Cleanup
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    browser.close().await?;

    Ok(())
}
