// YYYYMMDD → YYYY.MM.DD
function formatDate(d) {
    return d ? `${d.slice(0, 4)}.${d.slice(4, 6)}.${d.slice(6, 8)}` : '-';
}

// 태그별 색상 매핑
const TAG_COLORS = {
    '실적':  'bg-blue-100 text-blue-700',
    '유증':  'bg-red-100 text-red-700',
    '무증':  'bg-orange-100 text-orange-700',
    '수주':  'bg-green-100 text-green-700',
    '소송':  'bg-red-100 text-red-700',
    'M&A':   'bg-purple-100 text-purple-700',
    '지분':  'bg-indigo-100 text-indigo-700',
    '자사주':'bg-teal-100 text-teal-700',
    '경영':  'bg-gray-100 text-gray-600',
    'CB/BW': 'bg-yellow-100 text-yellow-700',
    '공시':  'bg-gray-100 text-gray-500',
};

function tagBadge(tag) {
    const cls = TAG_COLORS[tag] || TAG_COLORS['공시'];
    return `<span class="text-xs font-medium px-2 py-0.5 rounded-full ${cls} shrink-0">${tag}</span>`;
}

async function loadDisclosures() {
    try {
        const resp = await fetch(`/api/disclosure?code=${STOCK_CODE}`);
        if (!resp.ok) throw new Error();
        const list = await resp.json();

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

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

        const ul = document.getElementById('disclosureList');
        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-center gap-2 hover:bg-gray-50 px-1 rounded transition-colors">
                ${tagBadge(item.tag)}
                <span class="text-sm text-gray-800 flex-1 min-w-0 truncate">${item.reportNm}</span>
                <span class="text-xs text-gray-400 shrink-0">${formatDate(item.rceptDt)}</span>
            </a>`;
            ul.appendChild(li);
        });
        ul.classList.remove('hidden');
    } catch {
        document.getElementById('disclosureLoading').classList.add('hidden');
        document.getElementById('disclosureError').classList.remove('hidden');
    }
}

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