(function () {
    'use strict';

    if (window.__MELON_LITE_ANNOUNCEMENTS_BOUND) return;
    window.__MELON_LITE_ANNOUNCEMENTS_BOUND = true;

    const todayString = function () {
        const now = new Date();
        return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
    };

    const storageKey = function (id) {
        return `melon_lite_announcement_${id}_hide_until`;
    };

    const closeKey = function (id) {
        return `melon_lite_announcement_${id}_closed`;
    };

    function safeGet(storage, key) {
        try {
            return storage.getItem(key);
        } catch (err) {
            return null;
        }
    }

    function safeSet(storage, key, value) {
        try {
            storage.setItem(key, value);
        } catch (err) {
        }
    }

    function hideBanner(banner) {
        if (!banner) return;
        banner.classList.add('is-hidden');
        window.setTimeout(function () {
            if (banner && banner.parentNode) banner.parentNode.removeChild(banner);
        }, 180);
    }

    function syncBannerVisibility() {
        const banner = document.getElementById('app-announcement-banner');
        if (!banner) return;
        const id = banner.dataset.announcementId || '';
        if (!id) return;
        const hideUntil = safeGet(window.localStorage, storageKey(id));
        const closed = safeGet(window.sessionStorage, closeKey(id));
        if (closed === '1' || (hideUntil && hideUntil >= todayString())) {
            hideBanner(banner);
        }
    }

    document.addEventListener('click', function (event) {
        const button = event.target.closest('[data-announcement-dismiss]');
        if (!button) return;
        const banner = button.closest('#app-announcement-banner');
        if (!banner) return;
        const id = banner.dataset.announcementId || '';
        if (!id) return;
        const mode = button.getAttribute('data-announcement-dismiss');
        if (mode === 'today') {
            safeSet(window.localStorage, storageKey(id), todayString());
        } else {
            safeSet(window.sessionStorage, closeKey(id), '1');
        }
        hideBanner(banner);
    });

    document.addEventListener('DOMContentLoaded', syncBannerVisibility);
    document.addEventListener('melonlite:pjax-complete', syncBannerVisibility);
    syncBannerVisibility();
})();
