"""Synced navigation between two card stacks — source stack navigation drives target stack to same index"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/js/sync.ipynb.

# %% auto #0
__all__ = ['generate_card_stack_sync_js']

# %% ../../nbs/js/sync.ipynb #sync-imports
from typing import Optional

# %% ../../nbs/js/sync.ipynb #sync-gen
def generate_card_stack_sync_js(
    source_input_id:str,  # ID of source stack's focused_index hidden input
    target_nav_url:str,  # URL for target stack's nav_to_index route
    toggle_fn_name:str="toggleSyncedNav",  # Name for window toggle function
    sync_key:str="_cardStackSync",  # Window key for state + cleanup
) -> str:  # Standalone JS snippet (not inside any IIFE)
    """Generate JS for synced navigation between two card stacks.
    
    Source stack navigation drives target stack to the same focused index.
    Toggle on/off via window[toggle_fn_name]() or toolbar button.
    
    The settle handler and source input lookup are deferred — they work
    even if the source stack hasn't initialized when this JS first runs.
    Out-of-range indices are clamped server-side by nav_to_index.
    """
    return f"""
    (function() {{
        // Clean up previous settle handler if re-rendered
        var settleKey = '{sync_key}_settle';
        if (window[settleKey]) {{
            document.body.removeEventListener('htmx:afterSettle', window[settleKey]);
        }}

        // Sync state
        var state = window.{sync_key} = {{
            enabled: false,
            targetUrl: '{target_nav_url}',
            lastSyncedIndex: -1,
        }};

        // Toggle function (called by KeyAction or toolbar button)
        window.{toggle_fn_name} = function() {{
            state.enabled = !state.enabled;
            return state.enabled;
        }};

        // Sync function — navigate target to source's index
        function syncTarget(sourceIndex) {{
            if (!state.enabled) return;
            var idx = parseInt(sourceIndex, 10);
            if (isNaN(idx) || idx < 0) return;
            if (idx === state.lastSyncedIndex) return;
            state.lastSyncedIndex = idx;
            htmx.ajax('POST', state.targetUrl, {{
                values: {{ target_index: idx }},
                swap: 'none',
            }});
        }}

        // Settle handler — reads source input by ID on each event
        // (deferred lookup works even if source stack initializes after this JS runs)
        var settleHandler = function(evt) {{
            if (!state.enabled) return;
            var input = document.getElementById('{source_input_id}');
            if (input) syncTarget(input.value);
        }};
        window[settleKey] = settleHandler;
        document.body.addEventListener('htmx:afterSettle', settleHandler);
    }})();
    """
