/**
 * Channel grid keyboard navigation.
 *
 * PgDn / ArrowDown: move focus to the next row in the channel grid.
 * PgUp / ArrowUp:   move focus to the previous row.
 *
 * Simulates a click on the target row's first cell, which triggers
 * Dash's active_cell callback and updates the focus channel.
 */
(function () {
    "use strict";

    document.addEventListener("keydown", function (e) {
        if (e.key !== "PageDown" && e.key !== "PageUp" &&
            e.key !== "ArrowDown" && e.key !== "ArrowUp") {
            return;
        }

        // Don't intercept if user is typing in an input field
        var tag = (e.target.tagName || "").toLowerCase();
        if (tag === "input" || tag === "textarea" || tag === "select") {
            return;
        }

        var table = document.getElementById("channel-grid");
        if (!table) return;

        var rows = table.querySelectorAll("tbody tr");
        if (rows.length === 0) return;

        // Find the currently active (focused) row
        var activeRow = table.querySelector("tbody tr.focused, tbody tr td.focused");
        var currentIdx = -1;
        if (activeRow) {
            var row = activeRow.closest("tr");
            currentIdx = Array.prototype.indexOf.call(rows, row);
        }

        // Also check for active cell via Dash's cell-active class
        if (currentIdx < 0) {
            var activeCell = table.querySelector("td.cell--active, td.dash-cell--active, td.focused");
            if (activeCell) {
                var parentRow = activeCell.closest("tr");
                currentIdx = Array.prototype.indexOf.call(rows, parentRow);
            }
        }

        var direction = (e.key === "PageDown" || e.key === "ArrowDown") ? 1 : -1;
        var nextIdx = currentIdx + direction;

        // Clamp to valid range
        if (nextIdx < 0) nextIdx = 0;
        if (nextIdx >= rows.length) nextIdx = rows.length - 1;

        // Click the first data cell of the target row to trigger active_cell
        var targetRow = rows[nextIdx];
        if (targetRow) {
            var cell = targetRow.querySelector("td");
            if (cell) {
                cell.click();
                // Scroll the row into view
                targetRow.scrollIntoView({ block: "nearest", behavior: "smooth" });
            }
        }

        e.preventDefault();
    });
})();
