// MobiVault360 - Main JavaScript

import 'bootstrap';
import '@fortawesome/fontawesome-free/js/all.min.js';

// Initialize on DOM ready
document.addEventListener('DOMContentLoaded', function () {
    initSidebar();
    initTooltips();
    initConfirmDialogs();
    initPrint();
});

// Sidebar toggle
function initSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const toggle = document.querySelector('[data-toggle-sidebar]');

    if (toggle && sidebar) {
        toggle.addEventListener('click', function () {
            sidebar.classList.toggle('show');
        });

        // Close sidebar on click outside (mobile)
        document.addEventListener('click', function (e) {
            if (window.innerWidth < 992 &&
                sidebar.classList.contains('show') &&
                !sidebar.contains(e.target) &&
                !toggle.contains(e.target)) {
                sidebar.classList.remove('show');
            }
        });
    }
}

// Initialize Bootstrap tooltips
function initTooltips() {
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    [...tooltipTriggerList].map(el => new bootstrap.Tooltip(el));
}

// Confirm dialogs for destructive actions
function initConfirmDialogs() {
    document.querySelectorAll('[data-confirm]').forEach(function (el) {
        el.addEventListener('click', function (e) {
            const message = this.getAttribute('data-confirm') || 'Are you sure?';
            if (!confirm(message)) {
                e.preventDefault();
                e.stopPropagation();
            }
        });
    });
}

// Print functionality
function initPrint() {
    document.querySelectorAll('[data-print]').forEach(function (el) {
        el.addEventListener('click', function (e) {
            e.preventDefault();
            const printArea = document.querySelector(this.getAttribute('data-print'));
            if (printArea) {
                printContent(printArea.innerHTML);
            } else {
                window.print();
            }
        });
    });
}

// Print specific content
function printContent(content) {
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Print</title>
            <link rel="stylesheet" href="/css/print.css">
            <style>
                body { font-family: 'Courier New', monospace; }
            </style>
        </head>
        <body onload="window.print();window.close();">
            ${content}
        </body>
        </html>
    `);
    printWindow.document.close();
}

// Format currency
window.formatCurrency = function (amount, currency = 'EGP') {
    return new Intl.NumberFormat('en-EG', {
        style: 'currency',
        currency: currency
    }).format(amount);
};

// Format number
window.formatNumber = function (number, decimals = 2) {
    return new Intl.NumberFormat('en-EG', {
        minimumFractionDigits: decimals,
        maximumFractionDigits: decimals
    }).format(number);
};

// Show toast notification
window.showToast = function (message, type = 'success') {
    const toastContainer = document.getElementById('toast-container');
    if (!toastContainer) return;

    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type} border-0`;
    toast.setAttribute('role', 'alert');
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">${message}</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;

    toastContainer.appendChild(toast);
    const bsToast = new bootstrap.Toast(toast, { autohide: true, delay: 5000 });
    bsToast.show();

    toast.addEventListener('hidden.bs.toast', () => toast.remove());
};

// Loading spinner
window.showLoading = function () {
    let spinner = document.getElementById('loading-spinner');
    if (!spinner) {
        spinner = document.createElement('div');
        spinner.id = 'loading-spinner';
        spinner.className = 'spinner-overlay';
        spinner.innerHTML = `
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        `;
        document.body.appendChild(spinner);
    }
    spinner.style.display = 'flex';
};

window.hideLoading = function () {
    const spinner = document.getElementById('loading-spinner');
    if (spinner) {
        spinner.style.display = 'none';
    }
};

// Debounce function
window.debounce = function (func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
};

// Export for modules
export { printContent };
