/**
 * Modern Message Box System
 * Replaces standard browser alerts with custom branded message boxes
 * Shows store name and logo from database
 */

(function() {
    'use strict';
    
    // Store information cache
    let storeInfo = {
        StoreName: 'Store',
        StoreCode: '',
        StoreLogo1: '',
        City: '',
        State: ''
    };
    
    let storeInfoLoaded = false;
    let previousActiveElement = null; // Store the element that had focus
    
    /**
     * Load store information from database
     */
    function loadStoreInfo() {
        return new Promise((resolve, reject) => {
            if (storeInfoLoaded) {
                resolve(storeInfo);
                return;
            }
            
            $.ajax({
                url: 'api/get-store-info.php',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.data) {
                        storeInfo = response.data;
                        storeInfoLoaded = true;
                        resolve(storeInfo);
                    } else {
                        resolve(storeInfo); // Use default
                    }
                },
                error: function() {
                    resolve(storeInfo); // Use default on error
                }
            });
        });
    }
    
    /**
     * Get store location string
     */
    function getStoreLocation() {
        const parts = [];
        if (storeInfo.City) parts.push(storeInfo.City);
        if (storeInfo.State) parts.push(storeInfo.State);
        return parts.join(', ') || 'Point of Sale';
    }
    
    /**
     * Get icon for message type
     */
    function getTypeIcon(type) {
        const icons = {
            success: '<i class="fas fa-check-circle"></i>',
            error: '<i class="fas fa-exclamation-circle"></i>',
            warning: '<i class="fas fa-exclamation-triangle"></i>',
            info: '<i class="fas fa-info-circle"></i>',
            confirm: '<i class="fas fa-question-circle"></i>',
            default: '<i class="fas fa-bell"></i>'
        };
        return icons[type] || icons.default;
    }
    
    /**
     * Create message box HTML
     */
    function createMessageBox(options) {
        const {
            type = 'default',
            title = '',
            message = '',
            showInput = false,
            inputPlaceholder = '',
            buttons = []
        } = options;
        
        const location = getStoreLocation();
        const typeIcon = getTypeIcon(type);
        
        const html = `
            <div class="modern-msgbox-overlay" id="modernMsgBoxOverlay">
                <div class="modern-msgbox">
                    <div class="modern-msgbox-header ${type}">
                        <div class="modern-msgbox-store-info">
                            <h6 class="modern-msgbox-store-name">${storeInfo.StoreName}</h6>
                            <p class="modern-msgbox-store-location">${location}</p>
                        </div>
                        <div class="modern-msgbox-type-icon ${type}">
                            ${typeIcon}
                        </div>
                    </div>
                    <div class="modern-msgbox-body">
                        <p class="modern-msgbox-message">${message}</p>
                        ${showInput ? `<input type="text" class="modern-msgbox-input" id="modernMsgBoxInput" placeholder="${inputPlaceholder}" autocomplete="off">` : ''}
                    </div>
                    <div class="modern-msgbox-footer" id="modernMsgBoxFooter">
                        ${buttons.map((btn, index) => `
                            <button class="modern-msgbox-btn modern-msgbox-btn-${btn.style}" data-action="${btn.action}" data-index="${index}">
                                ${btn.loading ? '<span class="modern-msgbox-loading"></span>' : ''}
                                ${btn.text}
                            </button>
                        `).join('')}
                    </div>
                </div>
            </div>
        `;
        
        return html;
    }
    
    /**
     * Show message box
     */
    function showMessageBox(options) {
        return new Promise((resolve) => {
            // Store the currently active element to restore focus later
            previousActiveElement = document.activeElement;
            
            // Remove existing message box
            $('#modernMsgBoxOverlay').remove();
            
            // Create and append new message box
            const html = createMessageBox(options);
            $('body').append(html);
            
            const $overlay = $('#modernMsgBoxOverlay');
            const $msgbox = $overlay.find('.modern-msgbox');
            const $input = $('#modernMsgBoxInput');
            
            // Helper function to close and restore focus
            const closeAndRestore = function(result) {
                $overlay.fadeOut(200, function() {
                    $(this).remove();
                    // Restore focus to the element that had focus before message box
                    if (previousActiveElement && previousActiveElement !== document.body) {
                        setTimeout(() => {
                            $(previousActiveElement).focus();
                        }, 100);
                    }
                });
                resolve(result);
            };
            
            // Button click handler
            $overlay.on('click', '.modern-msgbox-btn', function() {
                const action = $(this).data('action');
                const inputValue = $input.length ? $input.val() : null;
                
                closeAndRestore({
                    action: action,
                    value: inputValue
                });
            });
            
            // Close on overlay click (for cancel-type actions)
            $overlay.on('click', function(e) {
                if ($(e.target).is('.modern-msgbox-overlay')) {
                    closeAndRestore({
                        action: 'cancel',
                        value: null
                    });
                }
            });
            
            // Focus input if present
            if ($input.length) {
                setTimeout(() => $input.focus(), 300);
                
                // Enter key submits
                $input.on('keypress', function(e) {
                    if (e.which === 13) {
                        $overlay.find('.modern-msgbox-btn-primary, .modern-msgbox-btn-success').first().click();
                    }
                });
            } else {
                // Focus first button
                setTimeout(() => $overlay.find('.modern-msgbox-btn').first().focus(), 300);
            }
            
            // Escape key closes
            $(document).on('keydown.msgbox', function(e) {
                if (e.key === 'Escape') {
                    $(document).off('keydown.msgbox');
                    closeAndRestore({
                        action: 'cancel',
                        value: null
                    });
                }
            });
        });
    }
    
    /**
     * Modern Alert - Replaces alert()
     */
    window.MsgBox = {
        alert: async function(message, type = 'info') {
            await loadStoreInfo();
            
            return showMessageBox({
                type: type,
                message: message,
                buttons: [
                    { text: 'OK', style: 'primary', action: 'ok' }
                ]
            });
        },
        
        /**
         * Modern Confirm - Replaces confirm()
         */
        confirm: async function(message, options = {}) {
            await loadStoreInfo();
            
            const {
                type = 'confirm',
                confirmText = 'Yes',
                cancelText = 'No',
                confirmStyle = 'success',
                cancelStyle = 'secondary'
            } = options;
            
            const result = await showMessageBox({
                type: type,
                message: message,
                buttons: [
                    { text: cancelText, style: cancelStyle, action: 'cancel' },
                    { text: confirmText, style: confirmStyle, action: 'confirm' }
                ]
            });
            
            return result.action === 'confirm';
        },
        
        /**
         * Modern Prompt - Replaces prompt()
         */
        prompt: async function(message, defaultValue = '', placeholder = '') {
            await loadStoreInfo();
            
            const result = await showMessageBox({
                type: 'info',
                message: message,
                showInput: true,
                inputPlaceholder: placeholder || defaultValue,
                buttons: [
                    { text: 'Cancel', style: 'secondary', action: 'cancel' },
                    { text: 'OK', style: 'primary', action: 'ok' }
                ]
            });
            
            return result.action === 'ok' ? result.value : null;
        },
        
        /**
         * Success message
         */
        success: async function(message) {
            await loadStoreInfo();
            
            return showMessageBox({
                type: 'success',
                message: message,
                buttons: [
                    { text: 'OK', style: 'success', action: 'ok' }
                ]
            });
        },
        
        /**
         * Error message
         */
        error: async function(message) {
            await loadStoreInfo();
            
            return showMessageBox({
                type: 'error',
                message: message,
                buttons: [
                    { text: 'OK', style: 'danger', action: 'ok' }
                ]
            });
        },
        
        /**
         * Warning message
         */
        warning: async function(message) {
            await loadStoreInfo();
            
            return showMessageBox({
                type: 'warning',
                message: message,
                buttons: [
                    { text: 'OK', style: 'warning', action: 'ok' }
                ]
            });
        },
        
        /**
         * Custom message box
         */
        custom: async function(options) {
            await loadStoreInfo();
            return showMessageBox(options);
        }
    };
    
    // Pre-load store info on page load
    $(document).ready(function() {
        loadStoreInfo();
    });
    
})();
