/**
 * Modern Message Box System - Global Version
 * Replaces standard browser alerts with custom branded message boxes
 * Shows store name and logo from database
 * Works across all modules: Sales, Purchase, Items, Reports, etc.
 * 
 * Usage:
 * - MsgBox.alert('Message', 'success|error|warning|info')
 * - MsgBox.confirm('Question?', { confirmText: 'Yes', cancelText: 'No' })
 * - MsgBox.prompt('Enter value:', 'default', 'placeholder')
 * - MsgBox.success('Success message')
 * - MsgBox.error('Error message')
 * - MsgBox.warning('Warning message')
 */

(function() {
    'use strict';
    
    // Store information cache
    let storeInfo = {
        StoreName: 'Store',
        StoreCode: '',
        StoreLogo1: '',
        City: '',
        State: ''
    };
    
    let storeInfoLoaded = false;
    let previousActiveElement = null;
    let currentZIndex = 99999;
    
    /**
     * Detect the correct API path based on current location
     */
    function getApiPath() {
        const currentPath = window.location.pathname;
        const pathParts = currentPath.split('/');
        
        // Check if we're in a subdirectory (Sales, Purchase, Items, etc.)
        const knownModules = ['Sales', 'Purchase', 'Items', 'PurchaseReports', 'SalesReports', 'StoreSettings'];
        const inModule = knownModules.some(module => currentPath.includes('/' + module + '/'));
        
        if (inModule) {
            return '../api/get-store-info.php';
        }
        return 'api/get-store-info.php';
    }
    
    /**
     * Load store information from database
     */
    function loadStoreInfo() {
        return new Promise((resolve, reject) => {
            if (storeInfoLoaded) {
                resolve(storeInfo);
                return;
            }
            
            // Use jQuery if available, otherwise fallback to fetch
            if (typeof $ !== 'undefined' && $.ajax) {
                $.ajax({
                    url: getApiPath(),
                    method: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.success && response.data) {
                            storeInfo = response.data;
                            storeInfoLoaded = true;
                            resolve(storeInfo);
                        } else {
                            resolve(storeInfo);
                        }
                    },
                    error: function() {
                        resolve(storeInfo);
                    }
                });
            } else {
                // Fallback to fetch API
                fetch(getApiPath())
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.data) {
                            storeInfo = data.data;
                            storeInfoLoaded = true;
                        }
                        resolve(storeInfo);
                    })
                    .catch(() => resolve(storeInfo));
            }
        });
    }
    
    /**
     * 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,
            inputValue = '',
            inputPlaceholder = '',
            inputType = 'text',
            buttons = [],
            allowClose = true
        } = options;
        
        const location = getStoreLocation();
        const typeIcon = getTypeIcon(type);
        const uniqueId = 'msgbox-' + Date.now();
        
        const html = `
            <div class="modern-msgbox-overlay" id="${uniqueId}" style="z-index: ${currentZIndex++};">
                <div class="modern-msgbox">
                    <div class="modern-msgbox-header ${type}">
                        <div class="modern-msgbox-store-info">
                            <h6 class="modern-msgbox-store-name">${escapeHtml(storeInfo.StoreName)}</h6>
                            <p class="modern-msgbox-store-location">${escapeHtml(location)}</p>
                        </div>
                        <div class="modern-msgbox-type-icon ${type}">
                            ${typeIcon}
                        </div>
                    </div>
                    <div class="modern-msgbox-body">
                        <p class="modern-msgbox-message">${escapeHtml(message)}</p>
                        ${showInput ? `<input type="${inputType}" class="modern-msgbox-input" id="${uniqueId}-input" value="${escapeHtml(inputValue)}" placeholder="${escapeHtml(inputPlaceholder)}" autocomplete="off">` : ''}
                    </div>
                    <div class="modern-msgbox-footer">
                        ${buttons.map((btn, index) => `
                            <button class="modern-msgbox-btn modern-msgbox-btn-${btn.style}" data-action="${btn.action}" data-index="${index}" ${btn.disabled ? 'disabled' : ''}>
                                ${btn.loading ? '<span class="modern-msgbox-loading"></span>' : ''}
                                ${escapeHtml(btn.text)}
                            </button>
                        `).join('')}
                    </div>
                </div>
            </div>
        `;
        
        return { html, uniqueId };
    }
    
    /**
     * Escape HTML to prevent XSS
     */
    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    /**
     * Show message box
     */
    function showMessageBox(options) {
        return new Promise((resolve) => {
            previousActiveElement = document.activeElement;
            
            const { html, uniqueId } = createMessageBox(options);
            document.body.insertAdjacentHTML('beforeend', html);
            
            const overlay = document.getElementById(uniqueId);
            const msgbox = overlay.querySelector('.modern-msgbox');
            const input = overlay.querySelector('.modern-msgbox-input');
            const buttons = overlay.querySelectorAll('.modern-msgbox-btn');
            
            // Helper function to close and restore focus
            const closeAndRestore = function(result) {
                overlay.style.opacity = '0';
                setTimeout(() => {
                    overlay.remove();
                    if (previousActiveElement && previousActiveElement !== document.body) {
                        setTimeout(() => {
                            try {
                                previousActiveElement.focus();
                            } catch(e) {
                                // Element might not be focusable anymore
                            }
                        }, 100);
                    }
                }, 200);
                resolve(result);
            };
            
            // Button click handler
            buttons.forEach(button => {
                button.addEventListener('click', function() {
                    const action = this.getAttribute('data-action');
                    const inputValue = input ? input.value : null;
                    
                    closeAndRestore({
                        action: action,
                        value: inputValue,
                        confirmed: action === 'confirm' || action === 'ok'
                    });
                });
            });
            
            // Close on overlay click (optional)
            if (options.allowClose !== false) {
                overlay.addEventListener('click', function(e) {
                    if (e.target === overlay) {
                        closeAndRestore({
                            action: 'cancel',
                            value: null,
                            confirmed: false
                        });
                    }
                });
            }
            
            // Focus input if present
            if (input) {
                setTimeout(() => input.focus(), 300);
                
                // Enter key submits
                input.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        const primaryBtn = overlay.querySelector('.modern-msgbox-btn-primary, .modern-msgbox-btn-success');
                        if (primaryBtn) primaryBtn.click();
                    }
                });
            } else {
                // Focus first button
                if (buttons.length > 0) {
                    setTimeout(() => buttons[buttons.length - 1].focus(), 300);
                }
            }
            
            // Escape key closes (if allowed)
            const escapeHandler = function(e) {
                if (e.key === 'Escape' && options.allowClose !== false) {
                    document.removeEventListener('keydown', escapeHandler);
                    closeAndRestore({
                        action: 'cancel',
                        value: null,
                        confirmed: false
                    });
                }
            };
            document.addEventListener('keydown', escapeHandler);
        });
    }
    
    /**
     * Global MsgBox API
     */
    window.MsgBox = {
        /**
         * Alert - Replaces alert()
         * @param {string} message - Message to display
         * @param {string} type - Type: 'success', 'error', 'warning', 'info', 'default'
         */
        alert: async function(message, type = 'info') {
            await loadStoreInfo();
            
            return showMessageBox({
                type: type,
                message: message,
                buttons: [
                    { text: 'OK', style: 'primary', action: 'ok' }
                ]
            });
        },
        
        /**
         * Confirm - Replaces confirm()
         * @param {string} message - Question to ask
         * @param {object} options - Customization options
         * @returns {boolean} - true if confirmed, false if cancelled
         */
        confirm: async function(message, options = {}) {
            await loadStoreInfo();
            
            const {
                type = 'confirm',
                confirmText = 'Yes',
                cancelText = 'No',
                confirmStyle = 'success',
                cancelStyle = 'secondary',
                dangerMode = false
            } = options;
            
            const result = await showMessageBox({
                type: dangerMode ? 'error' : type,
                message: message,
                allowClose: true,
                buttons: [
                    { text: cancelText, style: cancelStyle, action: 'cancel' },
                    { text: confirmText, style: dangerMode ? 'danger' : confirmStyle, action: 'confirm' }
                ]
            });
            
            return result.confirmed;
        },
        
        /**
         * Prompt - Replaces prompt()
         * @param {string} message - Message to display
         * @param {string} defaultValue - Default input value
         * @param {string} placeholder - Input placeholder
         * @returns {string|null} - Input value or null if cancelled
         */
        prompt: async function(message, defaultValue = '', placeholder = '') {
            await loadStoreInfo();
            
            const result = await showMessageBox({
                type: 'info',
                message: message,
                showInput: true,
                inputValue: defaultValue,
                inputPlaceholder: placeholder || defaultValue,
                buttons: [
                    { text: 'Cancel', style: 'secondary', action: 'cancel' },
                    { text: 'OK', style: 'primary', action: 'ok' }
                ]
            });
            
            return result.confirmed ? 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' }
                ]
            });
        },
        
        /**
         * Delete confirmation (shorthand for dangerous confirm)
         */
        confirmDelete: async function(message = 'Are you sure you want to delete this item?\n\nThis action cannot be undone!') {
            return this.confirm(message, {
                confirmText: 'Delete',
                cancelText: 'Cancel',
                dangerMode: true
            });
        },
        
        /**
         * Custom message box with full control
         */
        custom: async function(options) {
            await loadStoreInfo();
            return showMessageBox(options);
        },
        
        /**
         * Pre-load store information (call on page load for faster display)
         */
        preload: function() {
            loadStoreInfo();
        }
    };
    
    // Auto-preload on DOM ready if jQuery is available
    if (typeof $ !== 'undefined') {
        $(document).ready(function() {
            MsgBox.preload();
        });
    } else if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            MsgBox.preload();
        });
    } else {
        MsgBox.preload();
    }
    
})();
