"""Keyboard navigation focus zone and action factories for the virtual collection."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/keyboard/actions.ipynb.

# %% auto #0
__all__ = ['create_collection_focus_zone', 'create_collection_nav_actions', 'build_collection_url_map', 'apply_nav_sync']

# %% ../../nbs/keyboard/actions.ipynb #bb66821d
from typing import Dict, Optional, Tuple

from cjm_fasthtml_keyboard_navigation.core.focus_zone import FocusZone
from cjm_fasthtml_keyboard_navigation.core.actions import KeyAction
from cjm_fasthtml_keyboard_navigation.core.navigation import ScrollOnly
from cjm_fasthtml_keyboard_navigation.components.system import KeyboardSystem

from ..core.html_ids import VirtualCollectionHtmlIds
from ..core.button_ids import VirtualCollectionButtonIds
from ..core.models import VirtualCollectionUrls

# %% ../../nbs/keyboard/actions.ipynb #6b41ba6b
def create_collection_focus_zone(
    ids: VirtualCollectionHtmlIds,  # HTML IDs for this collection instance
    hidden_input_prefix: Optional[str] = None,  # Prefix for keyboard nav hidden inputs
) -> FocusZone:  # Configured focus zone for the collection
    """Create a focus zone for a virtual collection viewport."""
    return FocusZone(
        id=ids.collection,
        item_selector=None,
        navigation=ScrollOnly(),
        zone_focus_classes=(),
        item_focus_classes=(),
        hidden_input_prefix=hidden_input_prefix or f"{ids.prefix}-vc",
    )

# %% ../../nbs/keyboard/actions.ipynb #13ab7240
def create_collection_nav_actions(
    zone_id: str,  # Focus zone ID to restrict actions to
    button_ids: VirtualCollectionButtonIds,  # Button IDs for HTMX triggers
    disable_in_modes: Tuple[str, ...] = (),  # Mode names that disable navigation
) -> Tuple[KeyAction, ...]:  # Standard collection navigation actions
    """Create standard keyboard navigation actions for a virtual collection."""
    zone_ids = (zone_id,)
    not_modes = disable_in_modes if disable_in_modes else ()

    return (
        # --- Row navigation ---
        KeyAction(
            key="ArrowUp",
            htmx_trigger=button_ids.nav_up,
            zone_ids=zone_ids,
            not_modes=not_modes,
            description="Previous row",
            hint_group="Navigation",
        ),
        KeyAction(
            key="ArrowDown",
            htmx_trigger=button_ids.nav_down,
            zone_ids=zone_ids,
            not_modes=not_modes,
            description="Next row",
            hint_group="Navigation",
        ),

        # --- Page jump ---
        KeyAction(
            key="PageUp",
            htmx_trigger=button_ids.nav_page_up,
            zone_ids=zone_ids,
            not_modes=not_modes,
            description="Page up",
            hint_group="Navigation",
        ),
        KeyAction(
            key="PageDown",
            htmx_trigger=button_ids.nav_page_down,
            zone_ids=zone_ids,
            not_modes=not_modes,
            description="Page down",
            hint_group="Navigation",
        ),

        # --- First/last ---
        KeyAction(
            key="Home",
            htmx_trigger=button_ids.nav_first,
            zone_ids=zone_ids,
            not_modes=not_modes,
            description="First row",
            hint_group="Navigation",
        ),
        KeyAction(
            key="End",
            htmx_trigger=button_ids.nav_last,
            zone_ids=zone_ids,
            not_modes=not_modes,
            description="Last row",
            hint_group="Navigation",
        ),

        # --- Activate focused row ---
        KeyAction(
            key="Enter",
            htmx_trigger=button_ids.activate,
            zone_ids=zone_ids,
            not_modes=not_modes,
            description="Activate row",
            hint_group="Actions",
        ),
        KeyAction(
            key=" ",
            htmx_trigger=button_ids.activate,
            zone_ids=zone_ids,
            not_modes=not_modes,
            description="Activate row",
            hint_group="Actions",
            show_in_hints=False,
        ),
    )

# %% ../../nbs/keyboard/actions.ipynb #5f99c1cd
def build_collection_url_map(
    button_ids: VirtualCollectionButtonIds,  # Button IDs for this collection
    urls: VirtualCollectionUrls,  # URL bundle for routing
) -> Dict[str, str]:  # Mapping of button ID -> route URL
    """Build url_map for render_keyboard_system with all collection buttons."""
    return {
        button_ids.nav_up: urls.nav_up,
        button_ids.nav_down: urls.nav_down,
        button_ids.nav_page_up: urls.nav_page_up,
        button_ids.nav_page_down: urls.nav_page_down,
        button_ids.nav_first: urls.nav_first,
        button_ids.nav_last: urls.nav_last,
        button_ids.activate: urls.activate,
    }

# %% ../../nbs/keyboard/actions.ipynb #5a7ed9r32zc
def apply_nav_sync(
    kb_system: KeyboardSystem,         # Rendered keyboard system to patch
    ids: VirtualCollectionHtmlIds,     # HTML IDs for this collection
) -> None:  # Modifies kb_system.action_buttons in place
    """Add hx-sync to nav buttons so rapid input aborts stale in-flight requests.

    Prevents race conditions between cursor-only and full-window OOB responses
    during rapid keyboard or scroll wheel navigation.
    """
    sync_target = f"#{ids.collection}:abort"
    nav_prefix = f"{ids.prefix}-btn-nav-"
    for child in kb_system.action_buttons.children:
        if hasattr(child, 'attrs') and child.attrs.get('id', '').startswith(nav_prefix):
            child.attrs['hx-sync'] = sync_target
