use web_sys::MouseEvent;
use yew::prelude::*;

#[derive(Properties, PartialEq)]
pub struct CalendarContextMenuProps {
    pub is_open: bool,
    pub x: i32,
    pub y: i32,
    pub on_close: Callback<()>,
    pub on_create_event: Callback<MouseEvent>,
}

#[function_component(CalendarContextMenu)]
pub fn calendar_context_menu(props: &CalendarContextMenuProps) -> Html {
    let menu_ref = use_node_ref();

    if !props.is_open {
        return html! {};
    }

    // Smart positioning to keep menu within viewport
    let (x, y) = {
        let mut x = props.x;
        let mut y = props.y;
        
        // Try to get actual viewport dimensions
        if let Some(window) = web_sys::window() {
            if let (Ok(width), Ok(height)) = (window.inner_width(), window.inner_height()) {
                if let (Some(w), Some(h)) = (width.as_f64(), height.as_f64()) {
                    let viewport_width = w as i32;
                    let viewport_height = h as i32;
                    
                    // Calendar context menu: "Create Event" with icon
                    let menu_width = 180; // "Create Event" text + icon + padding
                    let menu_height = 60; // Single item + padding + margins
                    
                    // Adjust horizontally if too close to right edge
                    if x + menu_width > viewport_width - 10 {
                        x = x.saturating_sub(menu_width);
                    }
                    
                    // Adjust vertically if too close to bottom edge
                    if y + menu_height > viewport_height - 10 {
                        y = y.saturating_sub(menu_height);
                    }
                    
                    // Ensure minimum margins from edges
                    x = x.max(5);
                    y = y.max(5);
                }
            }
        }
        
        (x, y)
    };

    let style = format!(
        "position: fixed; left: {}px; top: {}px; z-index: 1001;",
        x, y
    );

    let on_create_event_click = {
        let on_create_event = props.on_create_event.clone();
        let on_close = props.on_close.clone();
        Callback::from(move |e: MouseEvent| {
            on_create_event.emit(e);
            on_close.emit(());
        })
    };

    html! {
        <div
            ref={menu_ref}
            class="context-menu"
            style={style}
        >
            <div class="context-menu-item context-menu-create" onclick={on_create_event_click}>
                <span class="context-menu-icon">{"+"}</span>
                {"Create Event"}
            </div>
        </div>
    }
}
