/**
 * Douzone ERP Keyboard Engine & Hotkey Manager
 * Standard: Enter-key focus traversal, Tab/Shift+Tab grid navigation, F-Key bindings (F2, F3, F4, F5, F7).
 */
document.addEventListener("DOMContentLoaded", function () {
    // 1. Enter Key Focus Traversal
    document.addEventListener("keydown", function (e) {
        if (e.key === "Enter") {
            const target = e.target;
            
            // Do not intercept Enter key on submit buttons or textareas
            if (target.tagName === "TEXTAREA" || (target.tagName === "BUTTON" && target.type === "submit")) {
                return;
            }

            const focusableElements = Array.from(
                document.querySelectorAll("input:not([type='hidden']):not([disabled]):not([readonly]), select:not([disabled]), button:not([disabled])")
            );

            const index = focusableElements.indexOf(target);
            if (index > -1 && index < focusableElements.length - 1) {
                e.preventDefault();
                focusableElements[index + 1].focus();
            }
        }
    });

    // 2. Douzone F-Key Hotkey Standard Listeners
    document.addEventListener("keydown", function (e) {
        switch (e.key) {
            case "F3": // 조회 (Search / Inquire)
                e.preventDefault();
                const btnSearch = document.getElementById("btnDouzoneSearch") || document.querySelector(".btn-douzone-search");
                if (btnSearch) btnSearch.click();
                break;
            case "F4": // 저장 (Save)
                e.preventDefault();
                const btnSave = document.getElementById("btnDouzoneSave") || document.querySelector(".btn-douzone-save");
                if (btnSave) btnSave.click();
                break;
            case "F5": // 삭제 (Delete)
                e.preventDefault();
                const btnDelete = document.getElementById("btnDouzoneDelete") || document.querySelector(".btn-douzone-delete");
                if (btnDelete) btnDelete.click();
                break;
            case "F7": // 엑셀 다운로드 (Excel Export)
                e.preventDefault();
                const btnExcel = document.getElementById("btnDouzoneExcel") || document.querySelector(".btn-douzone-excel");
                if (btnExcel) btnExcel.click();
                break;
        }
    });
});
