/**
 * Keyboard Shortcuts for POS System
 * Provides complete keyboard navigation without mouse
 */

(function() {
    'use strict';
    
    // Configuration
    const config = {
        focusHighlightClass: 'keyboard-focus-active',
        modalOpenClass: 'modal-keyboard-open',
        showIndicator: false
    };
    
    // Track current focus context
    let currentContext = 'main'; // main, modal, cart
    let cartFocusIndex = 0;
    let modalStack = [];
    
    /**
     * Initialize keyboard shortcuts
     */
    function initKeyboardShortcuts() {
        console.log('Initializing keyboard shortcuts...');
        
        // Main keyboard event listener
        $(document).on('keydown', handleKeyboardShortcut);
        
        // Focus management for inputs
        setupFocusManagement();
        
        // Modal keyboard handling
        setupModalKeyboardHandling();
        
        // Cart keyboard navigation
        setupCartKeyboardNavigation();
        
        // Show keyboard indicator on page load
        showKeyboardIndicator();
        
        console.log('Keyboard shortcuts initialized');
    }
    
    /**
     * Main keyboard shortcut handler
     */
    function handleKeyboardShortcut(e) {
        // Don't interfere when typing in textarea or specific inputs
        if (isTypingContext(e)) {
            // Allow Esc to exit from inputs
            if (e.key === 'Escape') {
                $(e.target).blur();
                e.preventDefault();
                return false;
            }
            return;
        }
        
        const key = e.key.toLowerCase();
        const ctrl = e.ctrlKey;
        const alt = e.altKey;
        const shift = e.shiftKey;
        
        // Global shortcuts (work everywhere)
        
        // F1 - Help
        if (key === 'f1') {
            e.preventDefault();
            showKeyboardHelp();
            return false;
        }
        
        // Esc - Close modals or clear focus
        if (key === 'escape') {
            e.preventDefault();
            handleEscape();
            return false;
        }
        
        // Alt + H - Home
        if (alt && key === 'h') {
            e.preventDefault();
            window.location.href = '../customer-management.php';
            return false;
        }
        
        // Check if any modal is open
        if ($('.modal.show').length > 0) {
            handleModalShortcuts(e, key, ctrl, alt, shift);
            return;
        }
        
        // Main screen shortcuts
        handleMainShortcuts(e, key, ctrl, alt, shift);
    }
    
    /**
     * Handle main screen shortcuts
     */
    function handleMainShortcuts(e, key, ctrl, alt, shift) {
        // F2 - Focus on Product Code
        if (key === 'f2') {
            e.preventDefault();
            focusProductCode();
            return false;
        }
        
        // F3 - Open Product Search Modal
        if (key === 'f3') {
            e.preventDefault();
            openProductSearchModal();
            return false;
        }
        
        // F4 - Focus on Rate
        if (key === 'f4') {
            e.preventDefault();
            $('#rate, #rateMobile').first().focus().select();
            return false;
        }
        
        // F5 - Focus on Quantity
        if (key === 'f5') {
            e.preventDefault();
            $('#quantity, #quantityMobile').first().focus().select();
            return false;
        }
        
        // F6 - Add to Cart
        if (key === 'f6') {
            e.preventDefault();
            $('#addToCart, #addToCartMobile').first().click();
            return false;
        }
        
        // F7 - Focus on Customer Search
        if (key === 'f7') {
            e.preventDefault();
            $('#customerSearch').focus().select();
            return false;
        }
        
        // F8 - Open Barcode Scanner
        if (key === 'f8') {
            e.preventDefault();
            openBarcodeScanner();
            return false;
        }
        
        // F9 - Save & Print Bill
        if (key === 'f9') {
            e.preventDefault();
            $('#saveBill').click();
            return false;
        }
        
        // F10 - View GST Details
        if (key === 'f10') {
            e.preventDefault();
            $('#btnGSTDetails').click();
            return false;
        }
        
        // F11 - Full Screen (browser default, but we can enhance)
        if (key === 'f11') {
            // Let browser handle it, but prevent if we want custom behavior
            // e.preventDefault();
        }
        
        // F12 - Quick Actions Menu
        if (key === 'f12') {
            e.preventDefault();
            $('#quickActionsModal').modal('show');
            return false;
        }
        
        // Ctrl + S - Save Bill
        if (ctrl && key === 's') {
            e.preventDefault();
            $('#saveBill').click();
            return false;
        }
        
        // Ctrl + N - New Sale
        if (ctrl && key === 'n') {
            e.preventDefault();
            $('#newSale').click();
            return false;
        }
        
        // Ctrl + H - Hold Bill
        if (ctrl && key === 'h') {
            e.preventDefault();
            $('#btnHoldBill').click();
            return false;
        }
        
        // Ctrl + L - View Hold Bills
        if (ctrl && key === 'l') {
            e.preventDefault();
            $('#btnViewHoldBills').click();
            return false;
        }
        
        // Ctrl + D - Apply Discount
        if (ctrl && key === 'd') {
            e.preventDefault();
            $('#discount').focus().select();
            return false;
        }
        
        // Ctrl + P - Print Preview (if save is done)
        if (ctrl && key === 'p') {
            e.preventDefault();
            // Custom print logic if needed
            return false;
        }
        
        // Ctrl + K - Clear Cart
        if (ctrl && key === 'k') {
            e.preventDefault();
            $('#clearCart').click();
            return false;
        }
        
        // Ctrl + G - GST Details
        if (ctrl && key === 'g') {
            e.preventDefault();
            $('#btnGSTDetails').click();
            return false;
        }
        
        // Ctrl + T - Transport Details
        if (ctrl && key === 't') {
            e.preventDefault();
            $('#btnTransportGST').click();
            return false;
        }
        
        // Ctrl + E - Expenses
        if (ctrl && key === 'e') {
            e.preventDefault();
            $('#btnExpenses').click();
            return false;
        }
        
        // Ctrl + M - Customer Modal
        if (ctrl && key === 'm') {
            e.preventDefault();
            $('#addCustomerModal').modal('show');
            setTimeout(() => $('#newCustomerName').focus(), 300);
            return false;
        }
        
        // Ctrl + Y - Loyalty Points
        if (ctrl && key === 'y') {
            e.preventDefault();
            $('#btnLoyaltyPoints').click();
            return false;
        }
        
        // Ctrl + U - Loyalty Settings
        if (ctrl && key === 'u') {
            e.preventDefault();
            $('#loyaltySettingsModal').modal('show');
            return false;
        }
        
        // Ctrl + I - Shipping Details
        if (ctrl && key === 'i') {
            e.preventDefault();
            $('#btnShippingDetails').click();
            return false;
        }
        
        // Ctrl + B - Toggle Barcode Scan Mode
        if (ctrl && key === 'b') {
            e.preventDefault();
            toggleBarcodeScanMode();
            return false;
        }
        
        // Alt + 1 to 9 - Sales Type Quick Switch
        if (alt && key >= '1' && key <= '9') {
            e.preventDefault();
            const index = parseInt(key) - 1;
            $('#salesType option').eq(index).prop('selected', true);
            $('#salesType').trigger('change');
            return false;
        }
        
        // Arrow keys for cart navigation when not in input
        // Disabled: Cart navigation is now handled directly in sales.js for Rate/Qty inputs
        // if (['arrowup', 'arrowdown', 'arrowleft', 'arrowright'].includes(key)) {
        //     if (!$(e.target).is('input, select, textarea')) {
        //         e.preventDefault();
        //         navigateCart(key);
        //         return false;
        //     }
        // }
        
        // Delete - Remove focused cart item
        if (key === 'delete') {
            if (!$(e.target).is('input, select, textarea')) {
                e.preventDefault();
                deleteCartItem();
                return false;
            }
        }
        
        // Enter - Edit focused cart item
        if (key === 'enter') {
            if (!$(e.target).is('input, select, textarea, button')) {
                e.preventDefault();
                editCartItem();
                return false;
            }
        }
        
        // Space - Toggle cart item selection
        if (key === ' ') {
            if (!$(e.target).is('input, select, textarea')) {
                e.preventDefault();
                toggleCartItemSelection();
                return false;
            }
        }
        
        // Ctrl + A - Select all cart items
        if (ctrl && key === 'a') {
            if (!$(e.target).is('input, textarea')) {
                e.preventDefault();
                selectAllCartItems();
                return false;
            }
        }
    }
    
    /**
     * Handle modal shortcuts
     */
    function handleModalShortcuts(e, key, ctrl, alt, shift) {
        const $activeModal = $('.modal.show').last();
        const modalId = $activeModal.attr('id');
        
        // Enter - Click primary button in modal
        if (key === 'enter') {
            if (!$(e.target).is('textarea')) {
                e.preventDefault();
                const $primaryBtn = $activeModal.find('.modal-footer .btn-primary, .modal-footer .btn-success').first();
                if ($primaryBtn.length) {
                    $primaryBtn.click();
                }
                return false;
            }
        }
        
        // Tab navigation within modal
        if (key === 'tab') {
            trapFocusInModal(e, $activeModal);
        }
        
        // Ctrl + W - Close modal
        if (ctrl && key === 'w') {
            e.preventDefault();
            $activeModal.modal('hide');
            return false;
        }
        
        // Product Search Modal specific shortcuts
        if (modalId === 'productSelectionModal' || modalId === 'mobileProductSearchModal') {
            // Arrow keys to navigate product results
            if (['arrowup', 'arrowdown'].includes(key)) {
                e.preventDefault();
                navigateProductResults(key === 'arrowdown' ? 1 : -1);
                return false;
            }
        }
        
        // Hold Bills Modal specific shortcuts
        if (modalId === 'holdBillsModal') {
            // Number keys 1-9 to quickly select hold bill
            if (!ctrl && !alt && key >= '1' && key <= '9') {
                e.preventDefault();
                const index = parseInt(key) - 1;
                const $holdBill = $('.hold-bill-item').eq(index);
                if ($holdBill.length) {
                    $holdBill.click();
                }
                return false;
            }
        }
    }
    
    /**
     * Check if user is typing in a context where shortcuts should be disabled
     */
    function isTypingContext(e) {
        const $target = $(e.target);
        const tagName = e.target.tagName.toLowerCase();
        
        // Allow shortcuts in these specific inputs even when focused
        if ($target.is('#productCode, #customerSearch')) {
            return false;
        }
        
        // Disable shortcuts when typing in inputs/textareas
        if (tagName === 'textarea') {
            return true;
        }
        
        if (tagName === 'input') {
            const type = $target.attr('type');
            // Allow shortcuts on buttons and checkboxes
            if (type === 'button' || type === 'submit' || type === 'checkbox' || type === 'radio') {
                return false;
            }
            return true;
        }
        
        if (tagName === 'select') {
            return true;
        }
        
        // Check if element is contenteditable
        if ($target.attr('contenteditable') === 'true') {
            return true;
        }
        
        return false;
    }
    
    /**
     * Handle Escape key
     */
    function handleEscape() {
        // Close any open modal
        const $openModal = $('.modal.show').last();
        if ($openModal.length) {
            $openModal.modal('hide');
            return;
        }
        
        // Clear any focused element
        if (document.activeElement) {
            $(document.activeElement).blur();
        }
        
        // Hide suggestions
        $('#customerSuggestions, #productSuggestions').hide();
        
        // If no modal is open and nothing is focused, reload page for new sale
        if (!$('.modal.show').length && !$(document.activeElement).is('input, textarea, select')) {
            MsgBox.confirm('Start a new sale? This will reload the page.', {
                type: 'confirm',
                confirmText: 'Yes, New Sale',
                cancelText: 'Cancel'
            }).then(function(confirmed) {
                if (confirmed) {
                    location.reload();
                }
            });
        }
    }
    
    /**
     * Focus on product code input
     */
    function focusProductCode() {
        const $input = $('#productCode').first();
        if ($input.length) {
            $input.focus().select();
            
            // Scroll into view if needed
            $input[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    }
    
    /**
     * Open product search modal
     */
    function openProductSearchModal() {
        const isMobile = window.innerWidth <= 768;
        
        if (isMobile) {
            $('#mobileProductSearchModal').modal('show');
            setTimeout(() => $('#mobileSearchInput').focus(), 300);
        } else {
            $('#productSelectionModal').modal('show');
            setTimeout(() => $('#productSearchInput').focus(), 300);
        }
    }
    
    /**
     * Open barcode scanner
     */
    function openBarcodeScanner() {
        if (typeof startScanner === 'function') {
            startScanner();
        } else if (typeof openBarcodeScanner === 'function') {
            window.openBarcodeScanner();
        } else {
            // Fallback: click scanner button
            $('#cameraBtn, #scannerBtn, [data-action="scan"]').first().click();
        }
    }
    
    /**
     * Toggle Barcode Scan Mode
     */
    function toggleBarcodeScanMode() {
        const $checkbox = $('#barcodeScanMode');
        if ($checkbox.length) {
            // Toggle the checkbox
            $checkbox.prop('checked', !$checkbox.is(':checked'));
            
            // Trigger the change event to save to database
            $checkbox.trigger('change');
            
            // Focus back to product code
            setTimeout(() => {
                $('#productCode').focus();
            }, 100);
        }
    }
    
    /**
     * Navigate cart with arrow keys
     */
    function navigateCart(direction) {
        const $cartRows = $('#cartItems tr, .mobile-cart-item');
        
        if ($cartRows.length === 0) return;
        
        // Remove current focus
        $cartRows.removeClass('keyboard-focused');
        
        if (direction === 'arrowdown') {
            cartFocusIndex = Math.min(cartFocusIndex + 1, $cartRows.length - 1);
        } else if (direction === 'arrowup') {
            cartFocusIndex = Math.max(cartFocusIndex - 1, 0);
        }
        
        // Add focus to new item
        const $focusedRow = $cartRows.eq(cartFocusIndex);
        $focusedRow.addClass('keyboard-focused');
        
        // Scroll into view
        $focusedRow[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }
    
    /**
     * Delete focused cart item
     */
    function deleteCartItem() {
        const $focusedRow = $('#cartItems tr.keyboard-focused, .mobile-cart-item.keyboard-focused');
        
        if ($focusedRow.length) {
            const $deleteBtn = $focusedRow.find('.btn-delete, .delete-btn, [onclick*="removeFromCart"]');
            if ($deleteBtn.length) {
                $deleteBtn.click();
                cartFocusIndex = Math.max(0, cartFocusIndex - 1);
            }
        }
    }
    
    /**
     * Edit focused cart item
     */
    function editCartItem() {
        const $focusedRow = $('#cartItems tr.keyboard-focused, .mobile-cart-item.keyboard-focused');
        
        if ($focusedRow.length) {
            // Desktop: click on the row or edit button
            const $editBtn = $focusedRow.find('.btn-edit, .edit-btn, [onclick*="editCartItem"]');
            if ($editBtn.length) {
                $editBtn.click();
            } else {
                // Mobile: trigger click on the card
                $focusedRow.click();
            }
        }
    }
    
    /**
     * Toggle cart item selection
     */
    function toggleCartItemSelection() {
        const $focusedRow = $('#cartItems tr.keyboard-focused, .mobile-cart-item.keyboard-focused');
        
        if ($focusedRow.length) {
            $focusedRow.toggleClass('selected');
        }
    }
    
    /**
     * Select all cart items
     */
    function selectAllCartItems() {
        $('#cartItems tr, .mobile-cart-item').addClass('selected');
    }
    
    /**
     * Navigate product search results
     */
    function navigateProductResults(direction) {
        const $results = $('.product-result-item, .mobile-search-result-item');
        if ($results.length === 0) return;
        
        let currentIndex = $results.index($results.filter('.keyboard-focused'));
        
        $results.removeClass('keyboard-focused');
        
        if (currentIndex === -1) {
            currentIndex = direction > 0 ? 0 : $results.length - 1;
        } else {
            currentIndex += direction;
            if (currentIndex < 0) currentIndex = $results.length - 1;
            if (currentIndex >= $results.length) currentIndex = 0;
        }
        
        const $focused = $results.eq(currentIndex);
        $focused.addClass('keyboard-focused');
        
        // Scroll into view
        $focused[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        
        // On Enter, select this product
        $(document).one('keydown', function(e) {
            if (e.key === 'Enter' && $focused.hasClass('keyboard-focused')) {
                e.preventDefault();
                $focused.click();
            }
        });
    }
    
    /**
     * Trap focus within modal (accessibility)
     */
    function trapFocusInModal(e, $modal) {
        const $focusableElements = $modal.find('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
        const $firstFocusable = $focusableElements.first();
        const $lastFocusable = $focusableElements.last();
        
        if (e.shiftKey) {
            if ($(document.activeElement).is($firstFocusable)) {
                e.preventDefault();
                $lastFocusable.focus();
            }
        } else {
            if ($(document.activeElement).is($lastFocusable)) {
                e.preventDefault();
                $firstFocusable.focus();
            }
        }
    }
    
    /**
     * Setup focus management
     */
    function setupFocusManagement() {
        // Add visual indicator when elements receive keyboard focus
        $(document).on('focus', 'input, select, textarea, button', function() {
            $(this).addClass(config.focusHighlightClass);
        }).on('blur', 'input, select, textarea, button', function() {
            $(this).removeClass(config.focusHighlightClass);
        });
        
        // Auto-select text on focus for number inputs
        $(document).on('focus', 'input[type="number"], input[type="text"].auto-select', function() {
            $(this).select();
        });
    }
    
    /**
     * Setup modal keyboard handling
     */
    function setupModalKeyboardHandling() {
        // Track modal open/close
        $(document).on('show.bs.modal', '.modal', function() {
            modalStack.push($(this).attr('id'));
            
            // Auto-focus first input when modal opens
            const $modal = $(this);
            setTimeout(() => {
                const $firstInput = $modal.find('input, select, textarea').not('[readonly], [disabled]').first();
                if ($firstInput.length) {
                    $firstInput.focus().select();
                }
            }, 300);
        });
        
        $(document).on('hidden.bs.modal', '.modal', function() {
            modalStack.pop();
        });
    }
    
    /**
     * Setup cart keyboard navigation
     */
    function setupCartKeyboardNavigation() {
        // Click handler for cart rows - only for mouse clicks, not keyboard navigation
        $(document).on('click', '#cartItems tr, .mobile-cart-item', function(e) {
            // Don't select row if clicking on input fields
            if ($(e.target).is('input, button') || $(e.target).closest('input, button').length) {
                return;
            }
            
            const $rows = $('#cartItems tr, .mobile-cart-item');
            $rows.removeClass('keyboard-focused');
            $(this).addClass('keyboard-focused');
            cartFocusIndex = $rows.index(this);
        });
        
        // Reset focus index when cart is cleared
        $(document).on('click', '#clearCart, #newSale', function() {
            cartFocusIndex = 0;
            $('#cartItems tr, .mobile-cart-item').removeClass('keyboard-focused');
        });
    }
    
    /**
     * Show keyboard help modal
     */
    function showKeyboardHelp() {
        $('#keyboardShortcutsModal').modal('show');
    }
    
    /**
     * Show keyboard indicator
     */
    function showKeyboardIndicator() {
        if (!config.showIndicator) {
            return;
        }

        // Create indicator if it doesn't exist
        if ($('#keyboardIndicator').length === 0) {
            const $indicator = $(`
                <div id="keyboardIndicator" class="keyboard-indicator">
                    <i class="fas fa-keyboard"></i>
                    <span>Press <kbd>F1</kbd> for shortcuts</span>
                </div>
            `);
            
            $('body').append($indicator);
            
            // Auto-hide after 5 seconds
            setTimeout(() => {
                $indicator.fadeOut();
            }, 5000);
            
            // Show on mouse move initially
            let hasMovedMouse = false;
            $(document).one('mousemove', function() {
                if (!hasMovedMouse) {
                    hasMovedMouse = true;
                    $indicator.fadeIn();
                }
            });
        }
    }
    
    /**
     * Add keyboard shortcut hints to buttons
     */
    function addKeyboardHints() {
        // Add hints to common buttons
        const hints = {
            '#saveBill': 'F9',
            '#newSale': 'Ctrl+N',
            '#clearCart': 'Ctrl+K',
            '#btnHoldBill': 'Ctrl+H',
            '#btnGSTDetails': 'F10',
            '#addToCart': 'F6',
            '#barcodeScanMode': 'Ctrl+B'
        };
        
        Object.keys(hints).forEach(selector => {
            const $btn = $(selector);
            if ($btn.length && !$btn.find('.kbd-hint').length) {
                const hint = hints[selector];
                
                // For checkbox, add hint to the label
                if ($btn.is(':checkbox')) {
                    const $label = $btn.next('label');
                    if ($label.length && !$label.find('.kbd-hint').length) {
                        $label.append(` <span class="kbd-hint ml-1">${hint}</span>`);
                    }
                } else {
                    $btn.append(` <span class="kbd-hint">${hint}</span>`);
                }
            }
        });
    }
    
    // Initialize on document ready
    $(document).ready(function() {
        initKeyboardShortcuts();
        addKeyboardHints();
        
        console.log('Keyboard shortcuts ready. Press F1 for help.');
    });
    
    // Expose some functions globally if needed
    window.KeyboardShortcuts = {
        showHelp: showKeyboardHelp,
        focusProductCode: focusProductCode,
        navigateCart: navigateCart
    };
    
})();
