#!/usr/bin/env bash
# Unified wrapper for F4/F5 sidebars.
# Handles switching between trail and status, and scrollback navigation.
# First argument: "trail" or "status"

MODE="${1:-trail}"

while true; do
    rm -f ~/.config/mux/.trail-navigate ~/.config/mux/.trail-switch

    if [ "$MODE" = "trail" ]; then
        python3 ~/.config/mux/trail-popup.py
    else
        python3 ~/.config/mux/status-popup.py
    fi

    # Switch to other sidebar?
    if [ -f ~/.config/mux/.trail-switch ]; then
        TARGET=$(cat ~/.config/mux/.trail-switch)
        rm -f ~/.config/mux/.trail-switch
        if [ "$TARGET" = "trail" ] || [ "$TARGET" = "status" ]; then
            MODE="$TARGET"
            continue
        fi
    fi

    # Navigate scrollback? (trail only)
    if [ -f ~/.config/mux/.trail-navigate ]; then
        NAV=$(cat ~/.config/mux/.trail-navigate)
        rm -f ~/.config/mux/.trail-navigate

        PANE=$(tmux list-panes -F '#{pane_id} #{pane_active}' | grep ' 1$' | cut -d' ' -f1)

        NAV_MODE=$(echo "$NAV" | head -1)
        VALUE=$(echo "$NAV" | tail -1)

        if [ -n "$PANE" ] && [ -n "$VALUE" ]; then
            if [ "$NAV_MODE" = "scroll" ]; then
                CURRENT_HIST=$(tmux display-message -t "$PANE" -p '#{history_size}')
                CURRENT_CURSOR=$(tmux display-message -t "$PANE" -p '#{cursor_y}')
                CURRENT_TOTAL=$((CURRENT_HIST + CURRENT_CURSOR))
                GOTO=$((CURRENT_TOTAL - VALUE))
                if [ "$GOTO" -lt 0 ]; then GOTO=0; fi
                tmux copy-mode -t "$PANE"
                sleep 0.1
                tmux send-keys -t "$PANE" -X goto-line "$GOTO"
            elif [ "$NAV_MODE" = "search" ]; then
                tmux copy-mode -t "$PANE"
                sleep 0.1
                tmux send-keys -t "$PANE" -X search-backward "$VALUE"
            fi
        fi
    fi

    break
done
