"""Media viewer components for high-contrast image inspection."""

from nicegui import ui


def dark_room_viewer(
    image_path: str | None,
    count_label: str = "1 Source Linked",
    *,
    container_height: str = "500px",
) -> None:
    """Isolated high-contrast container for image inspection with pan and zoom capabilities."""
    with ui.card().classes("ui-bg-viewer ui-border-viewer rounded-sm p-3 flex flex-col justify-between w-full"):
        # Viewer Header Bar
        with ui.row().classes("w-full justify-between items-center mb-2 ui-text-inverse text-xs"):
            ui.label("SOURCE MEDIA VIEWER").classes("font-mono font-bold tracking-wider")
            ui.label(count_label).classes("ui-text-accent")

        # Interactive Pan/Zoom Canvas Area
        if image_path:
            # Container with fixed height and hidden overflow for contained panning/zooming
            with ui.element("div").classes(
                "relative w-full overflow-hidden border ui-border-viewer ui-bg-viewer-overlay rounded-sm flex items-center justify-center cursor-grab active:cursor-grabbing"
            ).style(f"height: {container_height};") as viewport:

                # Image element targeted by client-side pan/zoom JS
                img = (
                    ui.image(image_path)
                    .classes("max-h-full max-w-full select-none transition-transform duration-75 ease-out")
                    .style("transform-origin: center center;")
                )

                # Client-side JavaScript state management for smooth panning and scaling
                js_pan_zoom = f"""
                const viewport = getElement('{viewport.id}');
                const img = getElement('{img.id}');
                
                let scale = 1;
                let pointX = 0;
                let pointY = 0;
                let startX = 0;
                let startY = 0;
                let isDragging = false;

                function updateTransform() {{
                    img.style.transform = `translate(${{pointX}}px, ${{pointY}}px) scale(${{scale}})`;
                }}

                // Mouse Wheel Zooming
                viewport.onwheel = function(e) {{
                    e.preventDefault();
                    const xs = (e.clientX - pointX) / scale;
                    const ys = (e.clientY - pointY) / scale;
                    
                    const delta = -e.deltaY;
                    (delta > 0) ? (scale *= 1.15) : (scale /= 1.15);
                    scale = Math.min(Math.max(0.5, scale), 8); // Constrain zoom level (0.5x to 8x)
                    
                    updateTransform();
                }};

                // Mouse Drag Panning
                viewport.onmousedown = function(e) {{
                    e.preventDefault();
                    startX = e.clientX - pointX;
                    startY = e.clientY - pointY;
                    isDragging = true;
                }};

                window.onmouseup = function() {{
                    isDragging = false;
                }};

                viewport.onmousemove = function(e) {{
                    if (!isDragging) return;
                    e.preventDefault();
                    pointX = e.clientX - startX;
                    pointY = e.clientY - startY;
                    updateTransform();
                }};

                // Global function handles for external control toolbar
                window.resetZoom_{img.id} = function() {{ scale = 1; pointX = 0; pointY = 0; updateTransform(); }};
                window.zoomIn_{img.id} = function() {{ scale = Math.min(scale * 1.25, 8); updateTransform(); }};
                window.zoomOut_{img.id} = function() {{ scale = Math.max(scale / 1.25, 0.5); updateTransform(); }};
                """
                ui.run_javascript(js_pan_zoom)

            # Control Toolbar
            with ui.row().classes("w-full justify-center items-center gap-2 mt-2 pt-2 border-t ui-border-viewer"):
                ui.button(
                    icon="zoom_in",
                    on_click=lambda: ui.run_javascript(f"window.zoomIn_{img.id}()"),
                ).props("flat round dense color=white text-xs").tooltip("Zoom In")

                ui.button(
                    icon="zoom_out",
                    on_click=lambda: ui.run_javascript(f"window.zoomOut_{img.id}()"),
                ).props("flat round dense color=white text-xs").tooltip("Zoom Out")

                ui.button(
                    icon="center_focus_strong",
                    on_click=lambda: ui.run_javascript(f"window.resetZoom_{img.id}()"),
                ).props("flat round dense color=white text-xs").tooltip("Reset View")

        else:
            # Fallback state when no image source is linked
            with ui.column().classes(
                "w-full flex-grow items-center justify-center border ui-border-viewer ui-bg-viewer-overlay-soft rounded-sm p-8"
            ).style(f"min-height: {container_height};"):
                ui.label("No source media available for inspection.").classes("ui-text-muted text-xs italic")