/**
 * Blog Over - Announcement Bar Scripts (Free Version)
 */

(function ($) {
    'use strict';

    var ANNOUNCEMENT_DISMISS_PREFIX = 'blog_over_announce_dismissed_';

    function initAnnouncementBars() {
        var $wrapper = $('.blog-over-announcement-wrapper');
        if (!$wrapper.length) return;

        // The Pro plugin handles its own initialization. 
        // If the wrapper has data-total-bars (which Pro adds), let Pro handle it.
        if ($wrapper.attr('data-total-bars')) {
            return;
        }

        var behavior = $wrapper.data('dismiss-behavior') || 'session';
        var isDismissible = $wrapper.data('dismissible') === 1 || $wrapper.data('dismissible') === '1';
        
        var $bar = $wrapper.find('.blog-over-announcement-bar');
        var idx = $bar.data('index') || 0;
        var isDismissed = false;

        // Check storage only if dismissible
        if (isDismissible) {
            if (behavior === 'permanent') {
                try { isDismissed = localStorage.getItem(ANNOUNCEMENT_DISMISS_PREFIX + idx) === '1'; } catch (e) {}
            } else if (behavior === 'session') {
                try { isDismissed = sessionStorage.getItem(ANNOUNCEMENT_DISMISS_PREFIX + idx) === '1'; } catch (e) {}
            }

            if (isDismissed) {
                $wrapper.css('display', 'none');
                return;
            }
        }

        // Bind dismiss click (use namespace to prevent conflicts)
        $wrapper.off('click.boAnnounce').on('click.boAnnounce', '.blog-over-announcement-close', function (e) {
            e.preventDefault();
            
            $wrapper.fadeOut(300, function() {
                $(this).css('display', 'none');
            });

            if (behavior === 'permanent') {
                try { localStorage.setItem(ANNOUNCEMENT_DISMISS_PREFIX + idx, '1'); } catch (err) {}
            } else if (behavior === 'session') {
                try { sessionStorage.setItem(ANNOUNCEMENT_DISMISS_PREFIX + idx, '1'); } catch (err) {}
            }
        });
    }

    $(document).ready(function () {
        initAnnouncementBars();
    });

    // Re-init after Customizer selective refresh
    if (typeof wp !== 'undefined' && wp.customize && wp.customize.selectiveRefresh) {
        wp.customize.selectiveRefresh.bind('partial-content-rendered', function (placement) {
            if (placement.partial.id.indexOf('announcement') !== -1) {
                setTimeout(initAnnouncementBars, 200);
            }
        });
    }

})(jQuery);
