function applyLanguage() {
    const language = getCurrentLanguage();
    document.documentElement.lang = language;

    document.querySelectorAll('[data-i18n]').forEach((el) => {
        el.textContent = t(el.dataset.i18n);
    });

    document.querySelectorAll('[data-i18n-html]').forEach((el) => {
        el.innerHTML = t(el.dataset.i18nHtml);
    });

    document.querySelectorAll('[data-i18n-placeholder]').forEach((el) => {
        el.setAttribute('placeholder', t(el.dataset.i18nPlaceholder));
    });

    document.querySelectorAll('[data-i18n-title]').forEach((el) => {
        const translatedTitle = t(el.dataset.i18nTitle);
        el.setAttribute('title', translatedTitle);
        if (el.classList.contains('info-tooltip')) {
            el.dataset.tooltip = translatedTitle;
        }
    });

    const settingsLanguage = document.getElementById('settingsLanguage');
    if (settingsLanguage) settingsLanguage.value = language;

    if (state.activeDashboardDivId) {
        const activeDivision = state.divisions.find((div) => div.id === state.activeDashboardDivId);
        if (activeDivision) {
            document.getElementById('dashboardTitle').textContent = getDivisionCopy(activeDivision).name;
        }
    }

    applyRuntimeI18n();
    refreshLocalizedViews();
}

let tooltipEl = null;
let sharedIconPickerState = {
    selectedIcon: 'fa-box',
    title: 'Choose Icon',
    onPick: null
};

function ensureTooltipElement() {
    if (!tooltipEl) {
        tooltipEl = document.createElement('div');
        tooltipEl.className = 'app-tooltip';
        document.body.appendChild(tooltipEl);
    }
    return tooltipEl;
}

function positionTooltip(target) {
    if (!tooltipEl || !target) return;
    const rect = target.getBoundingClientRect();
    const tooltipRect = tooltipEl.getBoundingClientRect();
    const gutter = 10;

    let left = rect.left + (rect.width / 2) - (tooltipRect.width / 2);
    left = Math.max(gutter, Math.min(left, window.innerWidth - tooltipRect.width - gutter));

    let top = rect.bottom + 10;
    if (top + tooltipRect.height > window.innerHeight - gutter) {
        top = rect.top - tooltipRect.height - 10;
    }
    if (top < gutter) {
        top = Math.max(gutter, window.innerHeight - tooltipRect.height - gutter);
    }

    tooltipEl.style.left = `${left}px`;
    tooltipEl.style.top = `${top}px`;
}

function showTooltip(target) {
    const tooltipText = target?.dataset?.tooltip || target?.getAttribute('title');
    if (!tooltipText) return;
    const el = ensureTooltipElement();
    el.textContent = tooltipText;
    target.dataset.tooltip = tooltipText;
    target.removeAttribute('title');
    el.classList.add('visible');
    positionTooltip(target);
}

function hideTooltip() {
    if (tooltipEl) tooltipEl.classList.remove('visible');
}

function initTooltips() {
    document.querySelectorAll('.info-tooltip').forEach((el) => {
        if (el.dataset.tooltipBound === '1') return;
        el.dataset.tooltipBound = '1';
        el.dataset.tooltip = el.getAttribute('title') || el.dataset.tooltip || '';
        el.removeAttribute('title');
        el.addEventListener('mouseenter', () => showTooltip(el));
        el.addEventListener('mouseleave', hideTooltip);
        el.addEventListener('focus', () => showTooltip(el));
        el.addEventListener('blur', hideTooltip);
    });

    if (!tooltipsInitialized) {
        window.addEventListener('scroll', hideTooltip, true);
        window.addEventListener('resize', hideTooltip);
        tooltipsInitialized = true;
    }
}

function escapeHtml(value) {
    return String(value ?? '').replace(/[&<>"']/g, (char) => ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;'
    }[char]));
}

function escapeAttr(value) {
    return escapeHtml(value).replace(/`/g, '&#96;');
}

function getCurrencySymbol(currency) {
    const code = String(currency || 'EUR').toUpperCase();
    return {
        EUR: '€',
        GBP: '£',
        USD: '$',
        CAD: 'C$'
    }[code] || '€';
}

function formatServicePrice(service) {
    const currency = String(service?.currency || 'EUR').toUpperCase();
    const price = String(service?.price || '').trim();
    return `${getCurrencySymbol(currency)}${price}`;
}

function sanitizeAdvisorHtml(text) {
    const template = document.createElement('template');
    template.innerHTML = String(text ?? '');
    const allowedTags = new Set(['B', 'STRONG', 'I', 'EM', 'BR', 'P', 'UL', 'OL', 'LI', 'H3', 'H4']);

    const walk = (node) => {
        [...node.childNodes].forEach((child) => {
            if (child.nodeType === Node.ELEMENT_NODE) {
                if (!allowedTags.has(child.tagName)) {
                    const fragment = document.createDocumentFragment();
                    while (child.firstChild) fragment.appendChild(child.firstChild);
                    child.replaceWith(fragment);
                    walk(node);
                    return;
                }
                [...child.attributes].forEach((attr) => child.removeAttribute(attr.name));
                walk(child);
            }
        });
    };

    walk(template.content);
    return template.innerHTML;
}

function formatAiReply(text) {
    const raw = String(text ?? '').replace(/\r\n/g, '\n');
    if (/<\/?(b|strong|i|em|br|p|ul|ol|li|h3|h4)\b/i.test(raw)) {
        return sanitizeAdvisorHtml(decodeHtmlEntities(raw));
    }
    return escapeHtml(raw)
        .replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
        .replace(/\n/g, '<br/>');
}

function decodeHtmlEntities(text) {
    const textarea = document.createElement('textarea');
    textarea.innerHTML = text;
    return textarea.value;
}

function getTrainingTitleDisplay(module) {
    const original = normalizeTranslatableText(module?.title);
    const translated = getCachedTranslation(original);
    if (!translated) return original;
    if (translated.includes('<') || translated.length > 140) return original;
    return translated;
}

function getTrainingContentDisplay(module) {
    const original = normalizeTranslatableText(module?.content);
    let translated = getCachedTranslation(original) || original;
    translated = translated.replace(/^.*?(<h[1-6][\s>])/is, '$1');
    translated = decodeHtmlEntities(translated);
    return translated;
}

function setSharedIconPickerCurrent(icon) {
    const iconEl = document.getElementById('sharedIconPickerCurrentIcon');
    const labelEl = document.getElementById('sharedIconPickerCurrentLabel');
    if (iconEl) iconEl.className = `fas ${icon || 'fa-box'} text-lg text-indigo-300`;
    if (labelEl) labelEl.textContent = icon || 'fa-box';
    sharedIconPickerState.selectedIcon = icon || 'fa-box';
}

function renderSharedIconPicker() {
    const grid = document.getElementById('sharedIconPickerGrid');
    const searchInput = document.getElementById('sharedIconPickerSearch');
    if (!grid || !searchInput) return;

    const query = searchInput.value.trim().toLowerCase();
    const filtered = SKILL_ICON_PRESETS.filter((entry) => {
        if (!query) return true;
        const haystack = `${entry.label} ${entry.icon} ${entry.keywords.join(' ')}`.toLowerCase();
        return haystack.includes(query);
    });

    grid.innerHTML = filtered.map((entry) => {
        const active = entry.icon === sharedIconPickerState.selectedIcon;
        return `
            <button class="skill-icon-option ${active ? 'border-indigo-400 bg-indigo-500/10 text-white' : ''}" type="button" data-icon="${entry.icon}" title="${escapeAttr(entry.label)}">
                <i class="fas ${entry.icon}"></i>
                <span>${escapeHtml(entry.label)}</span>
            </button>
        `;
    }).join('');

    grid.querySelectorAll('[data-icon]').forEach((button) => {
        button.addEventListener('click', () => {
            const icon = button.dataset.icon || 'fa-box';
            setSharedIconPickerCurrent(icon);
            sharedIconPickerState.onPick?.(icon);
            closeSharedIconPicker();
        });
    });
}

function closeSharedIconPicker() {
    const modal = document.getElementById('sharedIconPickerModal');
    if (!modal) return;
    modal.classList.add('opacity-0');
    modal.querySelector('.glass-panel')?.classList.add('scale-95');
    setTimeout(() => modal.classList.add('hidden'), 250);
}

function bindSharedIconPicker() {
    const modal = document.getElementById('sharedIconPickerModal');
    const closeBtn = document.getElementById('closeSharedIconPickerBtn');
    const cancelBtn = document.getElementById('cancelSharedIconPickerBtn');
    const searchInput = document.getElementById('sharedIconPickerSearch');
    if (!modal || modal.dataset.bound === '1') return;

    modal.dataset.bound = '1';
    closeBtn?.addEventListener('click', closeSharedIconPicker);
    cancelBtn?.addEventListener('click', closeSharedIconPicker);
    searchInput?.addEventListener('input', renderSharedIconPicker);
    modal.addEventListener('click', (event) => {
        if (event.target === modal) closeSharedIconPicker();
    });
}

function openSharedIconPicker(options = {}) {
    bindSharedIconPicker();
    sharedIconPickerState.title = options.title || 'Choose Icon';
    sharedIconPickerState.onPick = typeof options.onPick === 'function' ? options.onPick : null;

    const modal = document.getElementById('sharedIconPickerModal');
    const title = document.getElementById('sharedIconPickerTitle');
    const searchInput = document.getElementById('sharedIconPickerSearch');
    if (!modal || !title || !searchInput) return;

    title.textContent = sharedIconPickerState.title;
    searchInput.value = '';
    setSharedIconPickerCurrent(options.selectedIcon || 'fa-box');
    renderSharedIconPicker();

    modal.classList.remove('hidden');
    requestAnimationFrame(() => {
        modal.classList.remove('opacity-0');
        modal.querySelector('.glass-panel')?.classList.remove('scale-95');
        searchInput.focus();
    });
}

// ====== TOAST NOTIFICATION SYSTEM ======
function showToast(message, type = 'error') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    const icons = { error: 'fa-exclamation-circle', success: 'fa-check-circle', warning: 'fa-exclamation-triangle', info: 'fa-info-circle' };
    const colors = { error: 'from-red-600 to-red-800 border-red-500/40', success: 'from-green-600 to-green-800 border-green-500/40', warning: 'from-amber-600 to-amber-800 border-amber-500/40', info: 'from-blue-600 to-blue-800 border-blue-500/40' };
    toast.className = `pointer-events-auto bg-gradient-to-r ${colors[type]} border backdrop-blur-xl text-white px-5 py-3.5 rounded-xl shadow-2xl flex items-center gap-3 text-sm font-medium transform translate-x-[120%] transition-transform duration-300 max-w-sm`;
    toast.innerHTML = `<i class="fas ${icons[type]} text-lg shrink-0"></i><span>${message}</span>`;
    container.appendChild(toast);
    requestAnimationFrame(() => { toast.style.transform = 'translateX(0)'; });
    setTimeout(() => {
        toast.style.transform = 'translateX(120%)';
        setTimeout(() => toast.remove(), 300);
    }, 4000);
}
