/**
 * Toast Notifications Module
 *
 * Provides a unified interface for displaying toast notifications
 * using Toastr library with consistent styling.
 *
 * Usage:
 *   import { showSuccess, showError, showWarning, showInfo } from './modules/toast-notifications';
 *
 *   showSuccess('Item saved successfully!');
 *   showError('Failed to save item.');
 *   showWarning('Please fill all required fields.');
 *   showInfo('Processing your request...');
 */

/**
 * Default Toastr configuration
 */
const defaultOptions = {
    closeButton: true,
    progressBar: true,
    positionClass: 'toast-top-right',
    timeOut: 5000,
    extendedTimeOut: 2000,
    showEasing: 'swing',
    hideEasing: 'linear',
    showMethod: 'fadeIn',
    hideMethod: 'fadeOut',
    preventDuplicates: true,
    newestOnTop: true
};

/**
 * Initialize Toastr with default configuration
 */
export function initToastr() {
    if (window.toastr) {
        toastr.options = { ...defaultOptions };
    }
}

/**
 * Show a success toast
 *
 * @param {string} message - The message to display
 * @param {string} title - Optional title
 * @param {Object} options - Optional override options
 */
export function showSuccess(message, title = '', options = {}) {
    if (window.toastr) {
        toastr.success(message, title, { ...defaultOptions, ...options });
    } else {
        alert(message);
    }
}

/**
 * Show an error toast
 *
 * @param {string} message - The message to display
 * @param {string} title - Optional title
 * @param {Object} options - Optional override options
 */
export function showError(message, title = '', options = {}) {
    if (window.toastr) {
        toastr.error(message, title, {
            ...defaultOptions,
            timeOut: 0,  // Don't auto-hide errors
            extendedTimeOut: 0,
            ...options
        });
    } else {
        alert('Error: ' + message);
    }
}

/**
 * Show a warning toast
 *
 * @param {string} message - The message to display
 * @param {string} title - Optional title
 * @param {Object} options - Optional override options
 */
export function showWarning(message, title = '', options = {}) {
    if (window.toastr) {
        toastr.warning(message, title, {
            ...defaultOptions,
            timeOut: 7000,
            ...options
        });
    } else {
        alert('Warning: ' + message);
    }
}

/**
 * Show an info toast
 *
 * @param {string} message - The message to display
 * @param {string} title - Optional title
 * @param {Object} options - Optional override options
 */
export function showInfo(message, title = '', options = {}) {
    if (window.toastr) {
        toastr.info(message, title, { ...defaultOptions, ...options });
    } else {
        alert(message);
    }
}

/**
 * Show a loading toast (stays until cleared)
 *
 * @param {string} message - The message to display
 * @returns {Object} - The toast element for later removal
 */
export function showLoading(message = 'Processing...') {
    if (window.toastr) {
        return toastr.info(message, '', {
            ...defaultOptions,
            timeOut: 0,
            extendedTimeOut: 0,
            tapToDismiss: false,
            closeButton: false
        });
    }
    return null;
}

/**
 * Clear all toasts
 */
export function clearAll() {
    if (window.toastr) {
        toastr.clear();
    }
}

/**
 * Clear a specific toast
 *
 * @param {Object} toast - The toast element to clear
 */
export function clearToast(toast) {
    if (window.toastr && toast) {
        toastr.clear(toast);
    }
}

/**
 * Show toast based on response from server
 *
 * @param {Object} response - Server response with success/message fields
 */
export function showFromResponse(response) {
    if (!response) return;

    if (response.success === true) {
        showSuccess(response.message || 'Operation successful');
    } else if (response.success === false) {
        showError(response.message || 'Operation failed');
    } else if (response.message) {
        showInfo(response.message);
    }
}

/**
 * Show flash messages from session (call on page load)
 */
export function showFlashMessages() {
    // Check for messages in the DOM (rendered by Blade)
    const successMsg = document.querySelector('[data-flash-success]')?.dataset.flashSuccess;
    const errorMsg = document.querySelector('[data-flash-error]')?.dataset.flashError;
    const warningMsg = document.querySelector('[data-flash-warning]')?.dataset.flashWarning;
    const infoMsg = document.querySelector('[data-flash-info]')?.dataset.flashInfo;

    if (successMsg) showSuccess(successMsg);
    if (errorMsg) showError(errorMsg);
    if (warningMsg) showWarning(warningMsg);
    if (infoMsg) showInfo(infoMsg);
}

// Auto-initialize when module loads
if (typeof window !== 'undefined') {
    document.addEventListener('DOMContentLoaded', () => {
        initToastr();
        showFlashMessages();
    });
}

export default {
    initToastr,
    showSuccess,
    showError,
    showWarning,
    showInfo,
    showLoading,
    clearAll,
    clearToast,
    showFromResponse,
    showFlashMessages
};
