// =========================================================================
// KALASUTRA AI v3 — SIDE PANEL DASHBOARD
// Renders the payload background.js pushes to chrome.storage.local
// ('ks_latest_astro') / broadcasts via UPDATE_CHART message. Pure display —
// no calculations happen here.
// =========================================================================

const PLANET_ORDER_12 = ['Su', 'Mo', 'Ma', 'Me', 'Ju', 'Ve', 'Sa', 'Ra', 'Ke', 'Ur', 'Ne', 'Pl'];
const PLANET_FULL = { Su: "Sun", Mo: "Moon", Ma: "Mars", Me: "Mercury", Ju: "Jupiter", Ve: "Venus", Sa: "Saturn", Ra: "Rahu", Ke: "Ketu", Ur: "Uranus", Ne: "Neptune", Pl: "Pluto" };
const SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"];

function formatDeg(deg) {
    const d = Math.floor(deg % 30), m = Math.floor((deg % 1) * 60);
    return `${SIGNS[Math.floor(deg / 30)].slice(0, 3)} ${d}°${m.toString().padStart(2, '0')}'`;
}

// --- Collapsible sections ---
document.addEventListener('click', (e) => {
    if (e.target.matches('.ks-toggle-btn[data-toggle]')) {
        const targetId = e.target.getAttribute('data-toggle');
        const el = document.getElementById(targetId);
        const showing = el.style.display !== 'none';
        el.style.display = showing ? 'none' : 'block';
        e.target.innerText = showing ? 'Show' : 'Hide';
    }
});

function render(data) {
    if (!data || data.error) return;

    // --- Top ephemeris strip (kept from v2 layout) ---
    setText('astro-lagna', data.lagnaName);
    setText('astro-moonsign', data.planets?.Mo ? SIGNS[Math.floor(data.planets.Mo.long / 30)] : '--');
    setText('astro-nak', data.moonNakshatraName);
    setText('astro-sl', data.planets?.Mo?.sssl?.SL);
    setText('astro-ssl', data.planets?.Mo?.sssl?.SSL);
    const topVedha = data.sbc?.perPlanet?.Moon?.vedhaTargets?.length
        ? data.sbc.perPlanet.Moon.vedhaTargets.map(v => v.nakshatra).join(', ')
        : 'None';
    setText('astro-vedha', topVedha);

    renderPanchang(data.panchang);
    renderSBC(data.sbc);
    renderCusps(data.cusps);
    renderPlanets(data.planets);
    renderProfileDerived(data);
}

function setText(id, val) {
    const el = document.getElementById(id);
    if (el) el.innerText = (val === undefined || val === null || val === '') ? '--' : val;
}

function renderPanchang(p) {
    const el = document.getElementById('panchang-body');
    if (!el) return;
    if (!p) { el.innerHTML = `<div class="ks-empty-note">No panchang data yet.</div>`; return; }
    const rows = [
        ['Weekday', p.weekday], ['Tithi', p.tithi], ['Yoga', p.yoga], ['Karana', p.karana],
        ['Hora', p.hora], ['Sub-Hora', p.subHora], ['Choghadiya', p.choghadiya],
        ['Rahu Kalam', p.rahuKalam], ['Sunrise', p.sunrise], ['Sunset', p.sunset]
    ];
    el.innerHTML = rows.map(([label, val]) => `<div class="grid-row"><span class="grid-label">${label}</span><span class="grid-val">${val ?? '--'}</span></div>`).join('');
}

function renderSBC(sbc) {
    const el = document.getElementById('sbc-body');
    if (!el) return;
    if (!sbc || !sbc.perPlanet) { el.innerHTML = `<div class="ks-empty-note">No SBC data yet.</div>`; return; }

    let html = '';
    Object.entries(sbc.perPlanet).forEach(([planet, info]) => {
        const targets = info.vedhaTargets.length
            ? info.vedhaTargets.map(v => `<span class="ks-chip ks-chip-danger">${v.nakshatra} (${v.type})</span>`).join('')
            : `<span class="ks-chip ks-chip-good">No Vedha</span>`;
        html += `<div style="margin-bottom:6px; padding-bottom:6px; border-bottom:1px solid #1e293b1a;">
            <div class="grid-row"><span class="grid-label"><strong style="color:#ffd700;">${planet}</strong> — ${info.nakshatra} (Pada ${info.pada})</span><span class="grid-val" style="font-size:9.5px; color:#94a3b8;">${info.motion}</span></div>
            <div style="margin-top:2px;">${targets}</div>
            ${info.latta ? `<div style="margin-top:2px; font-size:10px; color:#f59e0b;">Latta ➔ ${info.latta}</div>` : ''}
        </div>`;
    });
    el.innerHTML = html;
}

function renderCusps(cusps) {
    const table = document.getElementById('cusps-table');
    if (!table || !cusps) return;
    let html = `<tr><th>Cusp</th><th>Sign</th><th>Pos</th><th>SgL</th><th>StL</th><th>SL</th><th>SSL</th></tr>`;
    for (let i = 1; i <= 12; i++) {
        const c = cusps[i];
        html += `<tr><td style="color:#ffd700;">${i}</td><td>${SIGNS[Math.floor(c.long / 30)].slice(0, 3)}</td><td>${formatDeg(c.long)}</td><td>${c.sssl.SgL}</td><td style="color:#34d399;">${c.sssl.StL}</td><td style="color:#f59e0b; font-weight:bold;">${c.sssl.SL}</td><td>${c.sssl.SSL}</td></tr>`;
    }
    table.innerHTML = html;
}

function renderPlanets(planets) {
    const table = document.getElementById('planets-table');
    if (!table || !planets) return;
    let html = `<tr><th>Planet</th><th>Deg</th><th>Star(Pd)</th><th>SgL</th><th>StL</th><th>SL</th><th>SSL</th><th>Hse</th><th>Sig</th></tr>`;
    PLANET_ORDER_12.forEach(sym => {
        const p = planets[sym];
        if (!p) return;
        const retro = p.isRetro ? ' <span style="color:#f87171;">(R)</span>' : '';
        html += `<tr>
            <td style="color:#ffd700;">${PLANET_FULL[sym]}${retro}</td>
            <td>${formatDeg(p.long)}</td>
            <td>${p.sssl.NakName} (${p.sssl.Pada})</td>
            <td>${p.sssl.SgL}</td>
            <td style="color:#34d399;">${p.sssl.StL}</td>
            <td style="color:#f59e0b; font-weight:bold;">${p.sssl.SL}</td>
            <td>${p.sssl.SSL}</td>
            <td>${p.kp_house}</td>
            <td style="color:#34d399; font-size:9.5px;">${p.houseSigStr || '-'}</td>
        </tr>`;
    });
    table.innerHTML = html;
}

function renderProfileDerived(data) {
    const missingNote = document.getElementById('profile-missing-note');
    const content = document.getElementById('profile-derived-content');
    if (!data.natal) { missingNote.style.display = 'block'; content.style.display = 'none'; return; }
    missingNote.style.display = 'none';
    content.style.display = 'block';

    setText('pd-name', data.natal.name || '(unnamed)');
    setText('pd-star', data.natal.birthStar);
    setText('pd-lagna', data.natal.lagna);

    const dashaBody = document.getElementById('dasha-active-body');
    if (data.dasha && data.dasha.active) {
        dashaBody.innerHTML = data.dasha.active.map(lvl =>
            `<div class="dasha-level"><span class="lvl-tag">${lvl.level}</span><span class="lvl-lord">${PLANET_FULL[lvl.lord] || lvl.lord}</span></div>`
        ).join('');
    } else {
        dashaBody.innerHTML = `<div class="ks-empty-note">--</div>`;
    }

    const taraEl = document.getElementById('tarabala-body');
    if (data.taraBala) {
        const t = data.taraBala;
        const chipClass = t.favorable ? 'ks-chip-good' : 'ks-chip-danger';
        taraEl.innerHTML = `
            <div class="grid-row"><span class="grid-label">Birth Star</span><span class="grid-val">${t.birthNakshatra}</span></div>
            <div class="grid-row"><span class="grid-label">Transit Moon Star</span><span class="grid-val">${t.transitNakshatra} (${t.transitPada})</span></div>
            <div class="grid-row"><span class="grid-label">Tara</span><span class="ks-chip ${chipClass}">${t.tara}</span></div>`;
    }

    const avEl = document.getElementById('ashtakavarga-body');
    if (data.ashtakavarga) {
        const a = data.ashtakavarga;
        avEl.innerHTML = `
            <div class="grid-row"><span class="grid-label">Transit Moon Sign</span><span class="grid-val">${a.sign}</span></div>
            <div class="grid-row"><span class="grid-label">Bindus (Points)</span><span class="grid-val" style="color:${a.points >= 4 ? '#34d399' : '#f87171'};">${a.points} / ${a.maxPoints}</span></div>`;
    }
}

document.getElementById('btn-load-dasha-tree')?.addEventListener('click', (e) => {
    const treeBody = document.getElementById('dasha-tree-body');
    if (treeBody.style.display !== 'none') { treeBody.style.display = 'none'; e.target.innerText = "Show Full 120-Year Tree"; return; }
    e.target.innerText = "Loading...";
    chrome.runtime.sendMessage({ action: "REQUEST_DASHA_TREE" }, (res) => {
        e.target.innerText = "Hide Full 120-Year Tree";
        treeBody.style.display = 'block';
        if (!res || res.error) { treeBody.innerHTML = `<div class="ks-empty-note">${res?.error || 'Could not load tree.'}</div>`; return; }
        treeBody.innerHTML = res.tree.map(renderMdNode).join('');
    });
});

function renderMdNode(md) {
    return `<details class="ks-tree"><summary>${PLANET_FULL[md.lord]} MD <span style="color:#94a3b8; font-size:10px;">${md.start} → ${md.end}</span> <span class="sig">${md.sig}</span></summary>
        ${md.children.map(ad => `<details class="ks-tree"><summary>${PLANET_FULL[ad.lord]} AD <span style="color:#94a3b8; font-size:10px;">${ad.start} → ${ad.end}</span> <span class="sig">${ad.sig}</span></summary>
            ${ad.children.map(pd => `<details class="ks-tree"><summary>${PLANET_FULL[pd.lord]} PD <span style="color:#94a3b8; font-size:10px;">${pd.start} → ${pd.end}</span> <span class="sig">${pd.sig}</span></summary>
                ${pd.children.map(sd => `<div style="margin-left:10px; font-size:10px; color:#e2e8f0;">${PLANET_FULL[sd.lord]} SD: ${sd.start} → ${sd.end} <span class="sig">${sd.sig}</span></div>`).join('')}
            </details>`).join('')}
        </details>`).join('')}
    </details>`;
}

// --- Live updates ---
chrome.runtime.onMessage.addListener((message) => {
    if (message.action === "UPDATE_CHART") render(message.data);
});

chrome.storage.local.get('ks_latest_astro', (data) => {
    if (data.ks_latest_astro) render(data.ks_latest_astro);
});

document.getElementById('btn-side-analyze')?.addEventListener('click', () => {
    chrome.runtime.sendMessage({ action: "REQUEST_ASTRO_UPDATE" });
});
