"""Focus position resolution, viewport window calculation, and OOB focus sync."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/helpers/focus.ipynb.

# %% auto #0
__all__ = ['resolve_focus_slot', 'calculate_viewport_window', 'render_focus_oob']

# %% ../../nbs/helpers/focus.ipynb #f1000003
from typing import List, Optional, Tuple

from fasthtml.common import Hidden

from ..core.html_ids import CardStackHtmlIds

# %% ../../nbs/helpers/focus.ipynb #f1000005
def resolve_focus_slot(
    focus_position: Optional[int],  # Slot offset (None=center, -1=bottom, 0=top)
    visible_count: int,  # Number of visible card slots
) -> int:  # Resolved 0-indexed slot position
    """Resolve focus_position to an actual slot index within the viewport."""
    if focus_position is None:
        return visible_count // 2
    if focus_position < 0:
        slot = visible_count + focus_position
    else:
        slot = focus_position
    return max(0, min(slot, visible_count - 1))

# %% ../../nbs/helpers/focus.ipynb #f1000011
def calculate_viewport_window(
    focused_index: int,  # Index of the focused item
    total_items: int,  # Total number of items
    visible_count: int,  # Number of visible card slots
    focus_position: Optional[int] = None,  # Focus slot (None=center)
) -> List[int]:  # Item indices for each slot (negative or >= total_items for placeholders)
    """Calculate which item indices should be visible in each viewport slot."""
    focus_slot = resolve_focus_slot(focus_position, visible_count)
    slots_before = focus_slot
    slots_after = visible_count - focus_slot - 1

    result = []

    # Slots before focused (may include negative indices for placeholders)
    for offset in range(slots_before, 0, -1):
        result.append(focused_index - offset)

    # Focused slot
    result.append(focused_index)

    # Slots after focused (may include indices >= total_items for placeholders)
    for offset in range(1, slots_after + 1):
        result.append(focused_index + offset)

    return result

# %% ../../nbs/helpers/focus.ipynb #f1000019
def render_focus_oob(
    focused_index: int,  # The item index to focus
    ids: CardStackHtmlIds,  # HTML IDs for this card stack instance
    form_input_name: str = "focused_index",  # Field name for the form input
) -> Tuple[Hidden, ...]:  # Hidden inputs with OOB swap
    """Render OOB hidden inputs to synchronize focus after HTMX swap."""
    return (
        Hidden(
            id=ids.focused_index_input,
            name=form_input_name,
            value=str(focused_index),
            hx_swap_oob="true",
        ),
    )
