<div id="system-notification-alert-container">
    <p class="text-center text-gray-500">Cargando Notificación Del Sistema...</p>
</div>

<script>
(function() {
    'use strict';

    const UI = {
        notificationContainer: document.getElementById('system-notification-alert-container'),
    };

    const sanitizeText = (str) => {
        if (!str) return '';
        const temp = document.createElement('div');
        temp.textContent = str;
        return temp.innerHTML;
    };

    function createNotificationElement(notificationData) {
        const { title, description, external_url, internal_url } = notificationData;

        const sanitizedTitle = sanitizeText(title) || 'Notificación Importante';
        const sanitizedDescription = sanitizeText(description) || 'Mantente informado sobre las últimas novedades.';

        const alertDiv = document.createElement('div');
        alertDiv.id = 'system-notification-alert';
        alertDiv.className = "mt-8 bg-gradient-to-r from-blue-50 to-yellow-50 p-6 rounded-xl shadow-md border-l-4 border-[var(--color-secondary)] flex items-start space-x-4 relative transition-opacity duration-300 ease-in-out";
        alertDiv.style.animation = "fadeIn 0.3s ease-out forwards";

        let linkHTML = '';
        if (external_url) {
            linkHTML = `
                <a href="${sanitizeText(external_url)}" target="_blank" rel="noopener noreferrer" class="inline-block mt-3 text-[var(--color-secondary)] font-bold hover:none text-sm">
                    VER DETALLES <i data-lucide="arrow-right" class="inline-block w-4 h-4 ml-1"></i>
                </a>`;
        } else if (internal_url) {
            linkHTML = `
                <a href="${sanitizeText(internal_url)}" class="inline-block mt-3 text-[var(--color-secondary)] font-black text-sm">
                    VER DETALLES <i data-lucide="arrow-right" class="inline-block w-4 h-4 ml-1"></i>
                </a>`;
        }

        alertDiv.innerHTML = `
            <div class="flex-shrink-0 p-3 bg-[var(--color-highlight)] rounded-full shadow-sm">
                <i data-lucide="megaphone" class="w-12 h-12 text-[var(--color-primary)]"></i>
            </div>
            <div class="flex-grow">
                <h4 class="text-xl font-extrabold text-[var(--color-primary)] ">${sanitizedTitle}</h4>
                <p class="text-gray-600 mt-1 ">${sanitizedDescription}</p>
                ${linkHTML}
            </div>
        `;

        const closeButton = document.createElement('button');
        closeButton.className = "absolute top-4 right-4 text-gray-400 hover:text-[var(--color-secondary)] transition-colors";
        closeButton.title = "Cerrar Notificación";
        closeButton.innerHTML = `<i data-lucide="x" class="w-5 h-5"></i>`;
        closeButton.addEventListener('click', () => {
            alertDiv.style.opacity = '0';
            setTimeout(() => alertDiv.remove(), 300);
        });

        alertDiv.appendChild(closeButton);
        return alertDiv;
    }

    function renderNotification(notification) {
        if (!UI.notificationContainer) return;
        UI.notificationContainer.innerHTML = ''; 

        if (notification) {
            const notificationElement = createNotificationElement(notification);
            UI.notificationContainer.appendChild(notificationElement);
            if (typeof lucide !== 'undefined') {
                lucide.createIcons();
            }
        }
    }
    
    function renderError() {
          if (UI.notificationContainer) {
            UI.notificationContainer.innerHTML = `
                <div class="mt-8 bg-red-50 border-l-4 border-red-400 text-red-700 p-4 rounded-md flex items-center space-x-3" style="animation: fadeIn 0.3s ease-out forwards;">
                    <i data-lucide="alert-triangle" class="w-5 h-5"></i>
                    <p>No Se Pudo Cargar La Notificación. Intente Más Tarde</p>
                </div>
            `;
            if (typeof lucide !== 'undefined') {
                lucide.createIcons();
            }
        }
    }

    async function fetchNotification() {
        try {
            const response = await fetch('admin/admin_notifications.php');
            if (!response.ok) {
                console.error(`Error del servidor: ${response.status}`, await response.text());
                throw new Error('Respuesta de red no fue exitosa.');
            }
            return await response.json();
        } catch (error) {
            console.error('Error al obtener la notificación del sistema:', error);
            throw error; 
        }
    }

    async function init() {
        if (!UI.notificationContainer) {
            console.warn('Contenedor de notificaciones no encontrado.');
            return;
        }

        UI.notificationContainer.innerHTML = `
            <div class="mt-8 bg-gray-200 p-6 rounded-xl shadow-md flex items-start space-x-4 animate-pulse">
                <div class="flex-shrink-0 bg-gray-300 w-14 h-14 rounded-full"></div>
                <div class="flex-grow pt-2">
                    <div class="h-5 bg-gray-300 rounded w-3/4"></div>
                    <div class="h-4 bg-gray-300 rounded w-full mt-3"></div>
                </div>
            </div>
        `;

        try {
            const notification = await fetchNotification();
            renderNotification(notification);
        } catch {
            renderError();
        }
    }

    init();

})();
</script>