/**
 * Cincinnati Fire Department Portal — News Ticker
 * Polls api/news.php every 15 minutes.
 */
(function() {
    'use strict';

    const P = window.CFD_PORTAL || {};
    const track = document.getElementById('tickerTrack');
    if (!track) return;

    async function loadNews() {
        const data = await window.portalAPI('news.php');
        if (!data || !data.articles || data.articles.length === 0) {
            track.innerHTML = '<span class="ticker-placeholder">No headlines available</span>';
            return;
        }

        // Deduplicate by title
        const seen = new Set();
        const unique = [];
        for (const a of data.articles) {
            const key = a.title.trim().toLowerCase();
            if (!seen.has(key)) {
                seen.add(key);
                unique.push(a);
            }
        }

        const items = unique.slice(0, 15);
        let html = '';

        for (let pass = 0; pass < 2; pass++) {
            items.forEach((article, i) => {
                html += `<span class="ticker-item">
                    <span class="ticker-headline">${escapeHtml(article.title)}</span>
                    <span class="ticker-source">${escapeHtml(article.source)}</span>
                </span>`;
                if (i < items.length - 1 || pass === 0) {
                    html += '<span class="ticker-separator"></span>';
                }
            });
        }

        track.innerHTML = html;

        const contentWidth = track.scrollWidth / 2;
        const duration = contentWidth / 50;
        track.style.setProperty('--ticker-duration', duration + 's');
        track.parentElement.style.setProperty('--ticker-duration', duration + 's');
    }

    function escapeHtml(str) {
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

    loadNews();
    setInterval(loadNews, P.newsRefresh || 900000);
})();
