/**
 * Flash message utility
 * Provides a simple interface for showing flash messages with translations
 */

// @ts-ignore
import { FlashMessage } from '../flash.js';

declare global {
    interface Window {
        flash?: FlashMessage;
        translations?: {
            [key: string]: string;
        };
    }
}

/**
 * Initialize flash message system
 */
export function initFlash(): void {
    if (typeof window === 'undefined') {
        return;
    }

    // Инициализируем flash, если еще не инициализирован
    if (!window.flash) {
        // @ts-ignore
        window.flash = new FlashMessage();
    }
}

/**
 * Get translation by key
 * @param key - Translation key
 * @param fallback - Fallback text if translation not found
 * @returns Translated text
 */
function getTranslation(key: string, fallback?: string): string {
    if (window.translations && window.translations[key]) {
        return window.translations[key];
    }
    return fallback || key;
}

/**
 * Show a flash message with translation support
 * @param messageKey - Translation key for the message
 * @param variant - Message variant (success|error|warning|info|primary|default)
 * @param titleKey - Optional translation key for the title
 * @param closable - Whether message can be closed
 * @param duration - Auto-close duration in ms (0 = no auto-close)
 * @param messageFallback - Fallback text if translation not found
 * @param titleFallback - Fallback title if translation not found
 */
export function showFlash(
    messageKey: string,
    variant: 'success' | 'error' | 'warning' | 'info' | 'primary' | 'default' = 'default',
    titleKey: string | null = null,
    closable: boolean = true,
    duration: number = 5000,
    messageFallback?: string,
    titleFallback?: string
): void {
    initFlash();

    if (!window.flash) {
        console.error('Flash не инициализирован');
        return;
    }

    const message = getTranslation(messageKey, messageFallback);
    const title = titleKey ? getTranslation(titleKey, titleFallback) : null;

    window.flash.show(message, variant, title, closable, duration);
}

/**
 * Show success flash message
 */
export function showSuccess(messageKey: string, messageFallback?: string, duration: number = 5000): void {
    showFlash(messageKey, 'success', null, true, duration, messageFallback);
}

/**
 * Show error flash message
 */
export function showError(messageKey: string, messageFallback?: string, duration: number = 5000): void {
    showFlash(messageKey, 'error', null, true, duration, messageFallback);
}

/**
 * Show warning flash message
 */
export function showWarning(messageKey: string, messageFallback?: string, duration: number = 5000): void {
    showFlash(messageKey, 'warning', null, true, duration, messageFallback);
}

/**
 * Show info flash message
 */
export function showInfo(messageKey: string, messageFallback?: string, duration: number = 5000): void {
    showFlash(messageKey, 'info', null, true, duration, messageFallback);
}

