(function(){

let notifSound = new Audio('/core/assets/sounds/notification.mp3');
let lastUnread = 0;

/* =============================
   PREVENT DUPLICATE LOAD
============================= */
if (document.getElementById('activity-panel')) return;

/* =============================
   GET ELEMENTS
============================= */
const bell = document.getElementById('notification-bell');
const badge = document.getElementById('notif-count');

/* =============================
   CREATE PANEL
============================= */
const panel = document.createElement('div');
panel.id = 'activity-panel';

/* =============================
   PANEL STYLE (LOCKED)
============================= */
panel.style.position = 'fixed';

panel.style.top = '80px'; // keep this (important for your working logic)
panel.style.bottom = 'auto';

panel.style.right = '10px';

panel.style.width = '300px';
panel.style.maxWidth = '90%';

panel.style.maxWidth = '320px';
panel.style.left = 'auto';
panel.style.boxSizing = 'border-box';            // ✅ ALWAYS FIXED WIDTH
panel.style.maxHeight = '70vh';
panel.style.background = '#fff';
panel.style.borderRadius = '12px';
panel.style.boxShadow = '0 8px 25px rgba(0,0,0,0.15)';
panel.style.border = '1px solid #eee';
panel.style.overflow = 'hidden';

panel.style.zIndex = '99999';

panel.style.fontSize = '13px';
panel.style.transition = 'all 0.3s ease';

/* =============================
   PANEL CONTENT
============================= */
panel.innerHTML = `
    <div id="activity-header" style="
        background:#f2531e;
        color:#fff;
        padding:12px;
        font-weight:bold;
        cursor:pointer;
        border-top-left-radius:12px;
        border-top-right-radius:12px;
    ">
        🔔 Recent Activity
    </div>

    <div id="activity-content"></div>
`;

document.body.appendChild(panel);

/* START HIDDEN */
panel.style.display = 'none';

/* =============================
   CONTENT CONFIG
============================= */
const content = panel.querySelector('#activity-content');
content.style.overflowY = 'auto';
content.style.maxHeight = '300px';

/* =============================
   PREVENT CLICK CONFLICT
============================= */
panel.addEventListener('click', function(e){
    e.stopPropagation();
});

/* =============================
   COLLAPSE
============================= */
let open = true;

document.addEventListener("click", function(e){

    if(e.target.id === "activity-header"){

        e.stopPropagation();

        open = !open;

        content.style.display = open ? "block" : "none";
    }

});

/* =============================
   BELL CLICK
============================= */
if(bell){
    bell.addEventListener('click', function(e){

        e.stopPropagation();

        const isHidden = panel.style.display === 'none';

        panel.style.display = isHidden ? 'block' : 'none';

        if(isHidden && badge){
            badge.style.display = 'none';
        }

    });
}

/* =============================
   CLOSE ON OUTSIDE CLICK
============================= */

document.addEventListener('click', function(){
    notifSound.play().then(() => {
        notifSound.pause();
        notifSound.currentTime = 0;
    }).catch(() => {});
}, { once: true });

document.addEventListener('click', function(){

    if(panel.style.display === 'block'){
        panel.style.display = 'none';
    }

});

/* =============================
   LOAD ACTIVITY
============================= */
function loadActivity(){

    fetch('/api/notifications.php')
    .then(res => res.json())
    .then(data => {

        let html = '';
        let unread = data.filter(item => item.is_read == 0).length;

if (unread > lastUnread) {
    notifSound.currentTime = 0;
notifSound.play();
}
lastUnread = unread;

        if (!data.length) {

            html = '<div style="padding:12px;color:#6b7280;">No recent activity</div>';

        } else {

            data.forEach(item => {

    const isUnread = item.is_read == 0;

    html += `
        <div 
            onclick="markAsRead(${item.id}, '${item.link}')"
            style="
                padding:12px;
                border-bottom:1px solid #eee;
                cursor:pointer;
                background:${isUnread ? '#fff7ed' : '#fff'};
                font-weight:${isUnread ? '600' : '400'};
                transition:all 0.2s;
            "
            onmouseover="this.style.background='#f9fafb'"
            onmouseout="this.style.background='${isUnread ? '#fff7ed' : '#fff'}'"
        >

            <strong>${item.title}</strong><br>

            <small style="color:#6b7280;">
                ${item.message}
            </small>

        </div>
    `;
});

        }

        content.innerHTML = html;

        /* BADGE */
        if(badge){
            if(unread > 0){
                badge.style.display = 'block';
                badge.innerText = unread;
            } else {
                badge.style.display = 'none';
            }
        }

        /* CLICK */
        document.querySelectorAll('.activity-item').forEach(el => {
            el.addEventListener('click', function(){
                const id = this.getAttribute('data-id');
                window.location = '/core/public/operations/tickets/view.php?id=' + id;
            });
        });

    })
    .catch(() => {
        content.innerHTML = '<div style="padding:12px;color:red;">Error loading</div>';
    });
}

/* =============================
   AUTO REFRESH
============================= */
loadActivity();
setInterval(loadActivity, 15000);

})();
function markAsRead(id, link){

    fetch('/api/mark_read.php?id=' + id)
    .then(() => {
        window.location = link;
    });

}
