// RFC1123Z → "MM/DD HH:MM" 형식으로 변환
function formatNewsDate(s) {
    if (!s) return '';
    const d = new Date(s);
    if (isNaN(d)) return s;
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const dd = String(d.getDate()).padStart(2, '0');
    const hh = String(d.getHours()).padStart(2, '0');
    const min = String(d.getMinutes()).padStart(2, '0');
    return `${mm}/${dd} ${hh}:${min}`;
}

async function loadNews() {
    try {
        const resp = await fetch(`/api/news?name=${encodeURIComponent(STOCK_NAME)}`);
        if (!resp.ok) throw new Error();
        const list = await resp.json();

        document.getElementById('newsLoading').classList.add('hidden');

        if (!list || list.length === 0) {
            document.getElementById('newsEmpty').classList.remove('hidden');
            return;
        }

        const ul = document.getElementById('newsList');
        list.forEach(item => {
            const li = document.createElement('li');
            li.className = 'py-3';
            li.innerHTML = `<a href="${item.url}" target="_blank" rel="noopener noreferrer"
                class="flex items-start gap-3 hover:bg-gray-50 px-1 rounded transition-colors">
                <div class="flex-1 min-w-0">
                    <p class="text-sm text-gray-800 truncate">${item.title}</p>
                    <p class="text-xs text-gray-400 mt-0.5">${item.source}</p>
                </div>
                <span class="text-xs text-gray-400 shrink-0 mt-0.5">${formatNewsDate(item.publishedAt)}</span>
            </a>`;
            ul.appendChild(li);
        });
        ul.classList.remove('hidden');
    } catch {
        document.getElementById('newsLoading').classList.add('hidden');
        document.getElementById('newsError').classList.remove('hidden');
    }
}

document.addEventListener('DOMContentLoaded', () => {
    if (typeof STOCK_NAME !== 'undefined') loadNews();
});