document.addEventListener("DOMContentLoaded", function () {
    const bar = document.getElementById("mm-announcement");
    if (!bar) return;

    // --- 1. Positionierung ---
    const position = bar.dataset.position || 'below-header';

    if (position === "top") {
        document.body.insertAdjacentElement('afterbegin', bar);
    } else if (position === "below-slider") {
        const anchor = document.getElementById("mm-announcement-anchor");
        if (anchor) {
            anchor.replaceWith(bar);
        } else {
            const header = document.getElementById("masthead");
            if (header) header.insertAdjacentElement('afterend', bar);
        }
    } else {
        // "below-header" und alle anderen Positionen
        const header = document.getElementById("masthead");
        if (header) header.insertAdjacentElement('afterend', bar);
    }

    // --- 2. Schließen-Button ---
    const closeBtn = bar.querySelector(".mm-announcement-close");
    if (closeBtn) {
        closeBtn.addEventListener("click", function () {
            bar.style.transition = 'opacity 0.3s ease';
            bar.style.opacity = '0';
            setTimeout(function() { bar.style.display = "none"; }, 300);
        });
    }

    // --- 3. Countdown Timer ---
    const timerElement = document.querySelector('.mm-countdown-timer');

    if (timerElement) {
        const targetDateString = timerElement.getAttribute('data-date');
        const expiredMessage   = timerElement.getAttribute('data-expired') || 'Abgelaufen';

        if (!targetDateString) {
            timerElement.style.display = 'none';
            return;
        }

        const countDownDate = new Date(targetDateString).getTime();

        // FIX: Tick-Funktion auslagern und SOFORT aufrufen – kein 1s-Flackern beim Laden
        function tick() {
            const now      = new Date().getTime();
            const distance = countDownDate - now;

            if (distance < 0) {
                clearInterval(timerInterval);
                timerElement.innerHTML    = expiredMessage;
                timerElement.style.color  = '#ff3333';
                return;
            }

            const days    = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours   = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);

            const fDays    = days > 0 ? days + 'd ' : '';
            const fHours   = String(hours).padStart(2, '0');
            const fMinutes = String(minutes).padStart(2, '0');
            const fSeconds = String(seconds).padStart(2, '0');

            timerElement.innerHTML = fDays + fHours + ':' + fMinutes + ':' + fSeconds;
        }

        tick(); // Sofort ausführen
        const timerInterval = setInterval(tick, 1000);
    }
});