// Main JavaScript for 1D Poisson Simulator

// Common utility functions

function showLoading(message = 'Loading...') {
    return `
        <div class="spinner-container">
            <div class="text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <div class="mt-2">${message}</div>
            </div>
        </div>
    `;
}

function showError(message) {
    return `
        <div class="alert alert-danger" role="alert">
            <i class="bi bi-exclamation-triangle"></i> ${message}
        </div>
    `;
}

function showSuccess(message) {
    return `
        <div class="alert alert-success" role="alert">
            <i class="bi bi-check-circle"></i> ${message}
        </div>
    `;
}

function showInfo(message) {
    return `
        <div class="alert alert-info" role="alert">
            <i class="bi bi-info-circle"></i> ${message}
        </div>
    `;
}

// Format numbers
function formatNumber(num, decimals = 3) {
    if (num === null || num === undefined) return 'N/A';
    return Number(num).toFixed(decimals);
}

function formatScientific(num, decimals = 2) {
    if (num === null || num === undefined) return 'N/A';
    return Number(num).toExponential(decimals);
}

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

// Copy to clipboard
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        console.log('Copied to clipboard');
    }, function(err) {
        console.error('Could not copy text: ', err);
    });
}

// Download file
function downloadFile(content, filename, contentType = 'text/plain') {
    const blob = new Blob([content], { type: contentType });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
}

// API helper
function apiCall(endpoint, method = 'GET', data = null) {
    const options = {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        }
    };
    
    if (data) {
        options.body = JSON.stringify(data);
    }
    
    return fetch(endpoint, options)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        });
}

// Format timestamp
function formatTimestamp(timestamp) {
    const date = new Date(timestamp * 1000);
    return date.toLocaleString();
}

// Initialize tooltips (Bootstrap)
$(document).ready(function() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});

// Global toast notification
function showToast(message, type = 'info', duration = 3000) {
    if ($('#toastContainer').length === 0) {
        $('body').append(`
            <div id="toastContainer" class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 9999;">
            </div>
        `);
    }

    const iconMap = {
        'success': 'check-circle-fill',
        'warning': 'exclamation-triangle-fill',
        'danger': 'exclamation-circle-fill',
        'info': 'info-circle-fill'
    };

    const bgColorMap = {
        'success': 'success',
        'warning': 'warning',
        'danger': 'danger',
        'info': 'primary'
    };

    const icon = iconMap[type] || iconMap['info'];
    const bgColor = bgColorMap[type] || bgColorMap['info'];
    const toastId = 'toast-' + Date.now();

    const toastHtml = `
        <div class="toast align-items-center text-white bg-${bgColor} border-0" role="alert" id="${toastId}">
            <div class="d-flex">
                <div class="toast-body">
                    <i class="bi bi-${icon} me-2"></i>${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        </div>
    `;

    $('#toastContainer').append(toastHtml);

    const toast = new bootstrap.Toast($('#' + toastId)[0], {
        autohide: true,
        delay: duration
    });

    toast.show();

    $('#' + toastId).on('hidden.bs.toast', function() {
        $(this).remove();
    });
}
