// =========================================================================
// KALASUTRA ASTRO AI v3 — SITE OVERLAY (content.js)
// Open source. No license gate, no lock screen, no remote calls (other
// than the optional city-search geocoding done from the popup, not here).
// Tabs: Transit Data, My Data, Credits. Pure display — all math happens
// in background.js and is pushed here via chrome.storage / UPDATE_CHART.
// =========================================================================

console.log("Kalasutra Astro AI v3: Initializing overlay...");

let isHudHidden = true;

const KS_SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"];
const KS_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 KS_PLANET_ORDER_12 = ['Su', 'Mo', 'Ma', 'Me', 'Ju', 'Ve', 'Sa', 'Ra', 'Ke', 'Ur', 'Ne', 'Pl'];

function ksSignName(long) {
    return KS_SIGNS[Math.floor(((long % 360) + 360) % 360 / 30)];
}
function ksLbl(sym) { return KS_PLANET_FULL[sym] || sym; }

chrome.storage.local.get(['ks_latest_astro'], (res) => {
    if (res.ks_latest_astro) drawAstrologyOverlay(res.ks_latest_astro);
});

// -------------------------------------------------------------------------
// 1. STYLES
// -------------------------------------------------------------------------
const style = document.createElement('style');
style.textContent = `
    #kalasutra-ai-box {
        position: fixed; top: 70px; right: 60px; width: 460px;
        background: rgba(10, 14, 26, 0.96); backdrop-filter: blur(14px);
        border: 1px solid #FFD700; border-radius: 12px; padding: 14px;
        box-shadow: 0 12px 35px rgba(0, 0, 0, 0.9); z-index: 2147483000;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        color: #E0E6ED; display: none;
    }
    .ks-hud-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #2a3b5c; padding-bottom: 6px; margin-bottom: 8px; cursor: move; }
    .ks-hud-title { font-size: 13px; font-weight: 800; color: #FFD700; display: flex; align-items: center; gap: 6px; }
    .ks-hud-close { cursor: pointer; color: #7887A8; font-size: 16px; font-weight: bold; }
    .ks-hud-close:hover { color: #FF5733; }
    .ks-tab-bar { display: flex; gap: 4px; border-bottom: 1px solid #1e293b; margin-bottom: 8px; }
    .ks-tab-btn { flex: 1; padding: 7px 2px; font-size: 11px; font-weight: bold; background: #131b2e; color: #94a3b8; border: none; border-radius: 4px 4px 0 0; cursor: pointer; text-align: center; text-transform: uppercase; }
    .ks-tab-btn.active { background: #FFD700; color: #0b0f19; }
    .ks-tab-content { display: none; max-height: 600px; overflow-y: auto; padding-right: 2px; }
    .ks-tab-content.active { display: block; }
    .ks-data-card { background: #131b2e; padding: 8px; border-radius: 6px; margin-bottom: 8px; border: 1px solid #1e293b; font-size: 11px; }
    .ks-astro-row { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid rgba(42, 59, 92, 0.3); font-size: 11px; gap: 8px; }
    .ks-astro-row:last-child { border-bottom: none; }
    .ks-astro-label { color: #94a3b8; flex-shrink: 0; } .ks-astro-val { font-weight: bold; color: #fff; text-align: right; }
    .ks-section-title { color: #38bdf8; font-weight: bold; margin-bottom: 4px; font-size: 11px; }
    table.ks-kp-table { width: 100%; font-size: 10.5px; border-collapse: collapse; }
    table.ks-kp-table th { color: #FFD700; text-align: left; padding: 4px 3px; border-bottom: 1px solid #1e293b; position: sticky; top: 0; background: #131b2e; }
    table.ks-kp-table td { padding: 4px 3px; border-bottom: 1px solid rgba(42,59,92,0.3); color: #e2e8f0; }
    .ks-kp-scroll { max-height: 260px; overflow-y: auto; }
    .ks-empty-note { color: #64748b; font-size: 10px; text-align: center; padding: 6px; }
    .ks-chip-good { color: #34d399; font-weight: bold; }
    .ks-chip-bad { color: #f87171; font-weight: bold; }
    .ks-dasha-chain { font-size: 13px; font-weight: bold; color: #FFD700; text-align: center; padding: 8px 0; letter-spacing: 0.5px; }
    .ks-sig-chip { display: inline-block; background: rgba(56,189,248,0.15); color: #38bdf8; font-weight: bold; padding: 2px 7px; border-radius: 3px; font-size: 10.5px; margin: 2px 3px 0 0; }
    .ks-pair-chip { display: inline-block; background: rgba(255,215,0,0.12); color: #FFD700; font-weight: bold; padding: 2px 7px; border-radius: 3px; font-size: 10px; margin: 2px 3px 2px 0; }
    .ks-credits-line { padding: 5px 0; font-size: 11.5px; line-height: 1.5; }
    .ks-credits-line a { color: #FFD700; text-decoration: none; }
    .ks-credits-line a:hover { text-decoration: underline; }
    #ks-ai-trigger {
        position: fixed; top: 12px; right: 20px; z-index: 2147483000;
        background: #FFD700; color: #0b0f19; border: none; padding: 8px 16px;
        border-radius: 20px; font-weight: bold; font-size: 12px; cursor: pointer;
        box-shadow: 0 4px 12px rgba(0,0,0,0.5);
    }
    #ks-ai-trigger:hover { background: #E5C100; }
`;
document.head.appendChild(style);

// -------------------------------------------------------------------------
// 2. TRIGGER BUTTON — fixed to the viewport so it's always visible and
// findable, on any site (not tied to any one page's own toolbar layout).
// -------------------------------------------------------------------------
function openOverlayBox() {
    isHudHidden = false;
    const box = document.getElementById("kalasutra-ai-box");
    if (box) box.style.display = "block";
    // Render whatever's already cached RIGHT NOW — don't wait on a fresh
    // broadcast, which might not arrive for up to 30s (or at all, if this
    // tab's content script just loaded and missed the last tick).
    chrome.storage.local.get(['ks_latest_astro'], (res) => {
        if (res.ks_latest_astro) drawAstrologyOverlay(res.ks_latest_astro);
    });
    // Then also ask for a fresh computation to update it shortly after.
    chrome.runtime.sendMessage({ action: "REQUEST_ASTRO_UPDATE" });
}

function injectAIButton() {
    if (document.getElementById('ks-ai-trigger')) return;
    const btn = document.createElement('button');
    btn.id = 'ks-ai-trigger';
    btn.innerHTML = "🔮 Ask Kalasutra Astro AI";
    btn.addEventListener('click', openOverlayBox);
    document.body.appendChild(btn);
}
setInterval(injectAIButton, 1500);
injectAIButton();

function makeElementDraggable(elmnt, handle) {
    let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    handle.style.cursor = "move";
    handle.onmousedown = (e) => {
        e.preventDefault();
        pos3 = e.clientX; pos4 = e.clientY;
        document.onmouseup = () => { document.onmouseup = null; document.onmousemove = null; };
        document.onmousemove = (e) => {
            e.preventDefault();
            pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY;
            pos3 = e.clientX; pos4 = e.clientY;
            elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
            elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
        };
    };
}

// -------------------------------------------------------------------------
// 3. UI RENDERER & EVENT BINDING
// -------------------------------------------------------------------------
function renderOverlay() {
    if (document.getElementById("kalasutra-ai-box")) return;

    const box = document.createElement("div");
    box.id = "kalasutra-ai-box";

    box.innerHTML = `
        <div class="ks-hud-header" id="kalasutra-drag-header">
            <span class="ks-hud-title">🔮 Kalasutra Astro AI v3</span>
            <span id="close-kalasutra-box" class="ks-hud-close">✕</span>
        </div>

        <div class="ks-tab-bar">
            <button class="ks-tab-btn active" id="btn-transit">Transit Data</button>
            <button class="ks-tab-btn" id="btn-mydata">My Data</button>
            <button class="ks-tab-btn" id="btn-credits">Credits</button>
        </div>

        <div id="tab-transit" class="ks-tab-content active">
            <div class="ks-data-card">
                <div class="ks-astro-row"><span class="ks-astro-label">Date:</span><span class="ks-astro-val" id="td-date">--</span></div>
                <div class="ks-astro-row"><span class="ks-astro-label">Time:</span><span class="ks-astro-val" id="td-time">--</span></div>
                <div class="ks-astro-row"><span class="ks-astro-label">Weekday:</span><span class="ks-astro-val" id="td-weekday">--</span></div>
                <div class="ks-astro-row"><span class="ks-astro-label">Tithi:</span><span class="ks-astro-val" id="td-tithi">--</span></div>
                <div class="ks-astro-row"><span class="ks-astro-label">Moon Sign:</span><span class="ks-astro-val" id="td-moonsign">--</span></div>
                <div class="ks-astro-row"><span class="ks-astro-label">Moon Star:</span><span class="ks-astro-val" id="td-moonstar">--</span></div>
                <div class="ks-astro-row"><span class="ks-astro-label">Active Hora:</span><span class="ks-astro-val" id="td-hora">--</span></div>
                <div class="ks-astro-row"><span class="ks-astro-label">Rahu Kalam:</span><span class="ks-astro-val" id="td-rahukalam">--</span></div>
                <div class="ks-astro-row"><span class="ks-astro-label">Choghadiya:</span><span class="ks-astro-val" id="td-choghadiya">--</span></div>
                <div class="ks-astro-row"><span class="ks-astro-label">Karana:</span><span class="ks-astro-val" id="td-karana">--</span></div>
                <div class="ks-astro-row"><span class="ks-astro-label">Yoga:</span><span class="ks-astro-val" id="td-yoga">--</span></div>
            </div>

            <div class="ks-data-card">
                <div class="ks-section-title">⭐ Tara Bala (vs Your Moon Sign)</div>
                <div id="td-tarabala-body"><div class="ks-empty-note">Add your birth details in the extension popup's Profile tab to unlock this.</div></div>
            </div>

            <div class="ks-data-card">
                <div class="ks-section-title">🔢 Ashtakavarga (Transit Moon)</div>
                <div id="td-ashtakavarga-body"><div class="ks-empty-note">Add your birth details in the extension popup's Profile tab to unlock this.</div></div>
            </div>

            <div class="ks-data-card">
                <div class="ks-section-title">🧭 Lagna (Ascendant)</div>
                <div id="td-lagna-body"></div>
            </div>

            <div class="ks-data-card">
                <div class="ks-section-title">🌙 Moon Details</div>
                <div id="td-moondetail-body"></div>
            </div>

            <div class="ks-data-card">
                <div class="ks-section-title">🔗 Conjunctions</div>
                <div id="td-conjunctions-body"><div class="ks-empty-note">None right now.</div></div>
            </div>

            <div class="ks-data-card">
                <div class="ks-section-title">👁️ Aspects (Graha Drishti)</div>
                <div id="td-aspects-body"><div class="ks-empty-note">None right now.</div></div>
            </div>

            <div class="ks-data-card">
                <div class="ks-section-title">🕸️ SBC Vedha &amp; Latta</div>
                <div id="td-sbc-body"><div class="ks-empty-note">Waiting for data...</div></div>
            </div>
        </div>

        <div id="tab-mydata" class="ks-tab-content">
            <div class="ks-data-card">
                <div class="ks-section-title">🏠 KP Cusps — Transit (Live Sky)</div>
                <div class="ks-kp-scroll"><table class="ks-kp-table" id="kp-cusps-table"></table></div>
            </div>
            <div class="ks-data-card">
                <div class="ks-section-title">🪐 KP Planets — Transit (Live Sky)</div>
                <div class="ks-kp-scroll"><table class="ks-kp-table" id="kp-planets-table"></table></div>
            </div>
            <div class="ks-data-card">
                <div class="ks-section-title">🏠 KP Cusps — Natal (Birth Chart)</div>
                <div class="ks-kp-scroll"><table class="ks-kp-table" id="kp-cusps-table-natal"></table></div>
            </div>
            <div class="ks-data-card">
                <div class="ks-section-title">🪐 KP Planets — Natal (Birth Chart)</div>
                <div class="ks-kp-scroll"><table class="ks-kp-table" id="kp-planets-table-natal"></table></div>
            </div>
            <div class="ks-data-card">
                <div class="ks-section-title">🌓 Running Dasha (Maha &rarr; ... &rarr; Prana)</div>
                <div id="md-dasha-chain"><div class="ks-empty-note">Add your birth details in the extension popup's Profile tab to unlock this.</div></div>
            </div>
            <div class="ks-data-card">
                <div class="ks-section-title">🎯 Active Significations</div>
                <div id="md-active-sigs"><div class="ks-empty-note">Add your birth details in the extension popup's Profile tab to unlock this.</div></div>
            </div>
        </div>

        <div id="tab-credits" class="ks-tab-content">
            <div class="ks-data-card">
                <div class="ks-credits-line">🔓 <strong>Kalasutra Astro AI</strong> is an open source project.</div>
                <div class="ks-credits-line">🌐 Astronomical calculations powered by the <a href="https://www.astro.com/swisseph/" target="_blank" rel="noopener">Swiss Ephemeris</a>, used here under its open source license.</div>
                <div class="ks-credits-line">👤 Extension by: <strong>Surya Sunil Pasupuleti</strong></div>
                <div class="ks-credits-line">🔗 Website: <a href="https://makaratv.in" target="_blank" rel="noopener">makaratv.in</a></div>
            </div>
        </div>
    `;

    document.body.appendChild(box);
    makeElementDraggable(box, document.getElementById("kalasutra-drag-header"));
    bindUIEvents();
}

function bindUIEvents() {
    document.getElementById("close-kalasutra-box").addEventListener("click", () => {
        isHudHidden = true;
        document.getElementById("kalasutra-ai-box").style.display = "none";
    });

    const tabs = ['transit', 'mydata', 'credits'];
    tabs.forEach(tab => {
        const btn = document.getElementById(`btn-${tab}`);
        if (btn) {
            btn.addEventListener('click', () => {
                tabs.forEach(t => {
                    document.getElementById(`btn-${t}`).classList.remove('active');
                    document.getElementById(`tab-${t}`).classList.remove('active');
                });
                document.getElementById(`btn-${tab}`).classList.add('active');
                document.getElementById(`tab-${tab}`).classList.add('active');
                if (tab === 'mydata') loadNatalKPTables();
            });
        }
    });
}

// -------------------------------------------------------------------------
// MESSAGING WITH RETRY — mirrors the same fix used in popup.js: an MV3
// service worker that just woke up can miss a message sent the instant it
// wakes. Retry once before giving up.
// -------------------------------------------------------------------------
function ksSendMessage(msg, callback, attemptsLeft = 2) {
    chrome.runtime.sendMessage(msg, (res) => {
        if (chrome.runtime.lastError && attemptsLeft > 0) {
            setTimeout(() => ksSendMessage(msg, callback, attemptsLeft - 1), 350);
            return;
        }
        callback(res, chrome.runtime.lastError);
    });
}

function loadNatalKPTables() {
    const cuspsTable = document.getElementById("kp-cusps-table-natal");
    const planetsTable = document.getElementById("kp-planets-table-natal");
    if (!cuspsTable || !planetsTable) return;
    cuspsTable.innerHTML = `<tr><td class="ks-empty-note">Loading...</td></tr>`;
    planetsTable.innerHTML = '';
    let settled = false;
    const failSafe = setTimeout(() => {
        if (settled) return;
        settled = true;
        cuspsTable.innerHTML = `<tr><td class="ks-empty-note">Taking unusually long — switch tabs and try again in a moment.</td></tr>`;
    }, 13000);
    ksSendMessage({ action: "REQUEST_NATAL_KP_CHART" }, (res, err) => {
        if (settled) return;
        settled = true;
        clearTimeout(failSafe);
        if (err) { cuspsTable.innerHTML = `<tr><td class="ks-empty-note">Background engine not responding — try again in a moment.</td></tr>`; return; }
        if (!res || res.error) { cuspsTable.innerHTML = `<tr><td class="ks-empty-note">${res?.error || "Save your birth Profile first."}</td></tr>`; return; }
        renderKPCusps(res.cusps, "kp-cusps-table-natal");
        renderKPPlanets(res.planets, "kp-planets-table-natal");
    });
}
renderOverlay();

// -------------------------------------------------------------------------
// 4. LIVE CLOCK
// -------------------------------------------------------------------------
setInterval(() => {
    if (isHudHidden || !document.getElementById("kalasutra-ai-box")) return;
    const nowD = new Date();
    const dateEl = document.getElementById('td-date');
    const timeEl = document.getElementById('td-time');
    if (dateEl) dateEl.innerText = nowD.toLocaleDateString();
    if (timeEl) timeEl.innerText = nowD.toLocaleTimeString();
}, 1000);

// -------------------------------------------------------------------------
// 5. ASTRO DATA RENDERING — driven entirely by background.js's payload.
// -------------------------------------------------------------------------
function drawAstrologyOverlay(transitData) {
    if (isHudHidden || !document.getElementById("kalasutra-ai-box")) return;
    if (!transitData || transitData.error) return;

    const p = transitData.panchang || {};
    setText('td-weekday', p.weekday);
    setText('td-tithi', p.tithi || transitData.tithi);
    setText('td-hora', p.hora || transitData.hora);
    setText('td-rahukalam', p.rahuKalam);
    setText('td-choghadiya', p.choghadiya || transitData.choghadiya);
    setText('td-karana', p.karana);
    setText('td-yoga', p.yoga);

    if (transitData.planets && transitData.planets['Mo']) {
        setText('td-moonsign', ksSignName(transitData.planets['Mo'].long));
        setText('td-moonstar', transitData.moonNakshatraName);
    }

    renderTaraBala(transitData.taraBala);
    renderAshtakavarga(transitData.ashtakavarga);
    renderLagnaDetail(transitData);
    renderMoonDetail(transitData);
    renderConjunctions(transitData.conjunctions);
    renderAspects(transitData.aspects);
    renderSBC(transitData.sbc);

    renderKPCusps(transitData.cusps);
    renderKPPlanets(transitData.planets);
    renderDashaChain(transitData.dasha);
    renderActiveSigs(transitData.dasha);
}

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

function renderTaraBala(taraBala) {
    const el = document.getElementById("td-tarabala-body");
    if (!el) return;
    if (!taraBala) {
        el.innerHTML = `<div class="ks-empty-note">Add your birth details in the extension popup's Profile tab to unlock this.</div>`;
        return;
    }
    const chipClass = taraBala.favorable ? 'ks-chip-good' : 'ks-chip-bad';
    el.innerHTML = `
        <div class="ks-astro-row"><span class="ks-astro-label">Your Moon Sign / Star:</span><span class="ks-astro-val">${taraBala.birthNakshatra}</span></div>
        <div class="ks-astro-row"><span class="ks-astro-label">Transit Moon Star:</span><span class="ks-astro-val">${taraBala.transitNakshatra} (Pada ${taraBala.transitPada})</span></div>
        <div class="ks-astro-row"><span class="ks-astro-label">Tara:</span><span class="ks-astro-val ${chipClass}">${taraBala.tara}</span></div>`;
}

function renderAshtakavarga(av) {
    const el = document.getElementById("td-ashtakavarga-body");
    if (!el) return;
    if (!av) {
        el.innerHTML = `<div class="ks-empty-note">Add your birth details in the extension popup's Profile tab to unlock this.</div>`;
        return;
    }
    const chipClass = av.points >= 4 ? 'ks-chip-good' : 'ks-chip-bad';
    el.innerHTML = `
        <div class="ks-astro-row"><span class="ks-astro-label">Transit Moon Sign:</span><span class="ks-astro-val">${av.sign}</span></div>
        <div class="ks-astro-row"><span class="ks-astro-label">Bindus (Points):</span><span class="ks-astro-val ${chipClass}">${av.points} / ${av.maxPoints}</span></div>`;
}

function renderLagnaDetail(data) {
    const el = document.getElementById("td-lagna-body");
    if (!el || !data.cusps || !data.cusps[1]) return;
    const c1 = data.cusps[1];
    el.innerHTML = `
        <div class="ks-astro-row"><span class="ks-astro-label">Lagna:</span><span class="ks-astro-val">${data.lagnaName || ksSignName(c1.long)}</span></div>
        <div class="ks-astro-row"><span class="ks-astro-label">Lagna Lord:</span><span class="ks-astro-val">${ksLbl(c1.sssl.SgL)}</span></div>
        <div class="ks-astro-row"><span class="ks-astro-label">Lagna Star:</span><span class="ks-astro-val">${c1.sssl.NakName}</span></div>
        <div class="ks-astro-row"><span class="ks-astro-label">Lagna Sub Lord:</span><span class="ks-astro-val">${ksLbl(data.lagnaSSL || c1.sssl.SSL)}</span></div>
        <div class="ks-astro-row"><span class="ks-astro-label">Sub Lord Significations:</span><span class="ks-astro-val" style="font-size:9.5px;">${data.lagnaABCD || '-'}</span></div>`;
}

function renderMoonDetail(data) {
    const el = document.getElementById("td-moondetail-body");
    const mo = data.planets && data.planets['Mo'];
    if (!el || !mo) return;
    el.innerHTML = `
        <div class="ks-astro-row"><span class="ks-astro-label">Moon Sign:</span><span class="ks-astro-val">${ksSignName(mo.long)}</span></div>
        <div class="ks-astro-row"><span class="ks-astro-label">Moon Star:</span><span class="ks-astro-val">${data.moonNakshatraName || mo.sssl.NakName}</span></div>
        <div class="ks-astro-row"><span class="ks-astro-label">Moon Sub Lord:</span><span class="ks-astro-val">${ksLbl(mo.sssl.SL)}</span></div>
        <div class="ks-astro-row"><span class="ks-astro-label">Sub Lord Significations:</span><span class="ks-astro-val" style="font-size:9.5px;">${mo.abcd || '-'}</span></div>
        <div class="ks-astro-row"><span class="ks-astro-label">Moon Significations:</span><span class="ks-astro-val">${mo.houseSigStr || '-'}</span></div>`;
}

function renderConjunctions(conjunctions) {
    const el = document.getElementById("td-conjunctions-body");
    if (!el) return;
    if (!conjunctions || !conjunctions.length) { el.innerHTML = `<div class="ks-empty-note">No planets are conjunct right now.</div>`; return; }
    el.innerHTML = conjunctions.map(c => `<span class="ks-pair-chip">${ksLbl(c.a)} + ${ksLbl(c.b)} (${c.sign})</span>`).join('');
}

function renderAspects(aspects) {
    const el = document.getElementById("td-aspects-body");
    if (!el) return;
    if (!aspects || !aspects.length) { el.innerHTML = `<div class="ks-empty-note">No notable aspects right now.</div>`; return; }
    el.innerHTML = aspects.map(a => `<span class="ks-pair-chip">${ksLbl(a.from)} &rarr; ${ksLbl(a.to)} (${a.house}th)</span>`).join('');
}

function renderSBC(sbc) {
    const el = document.getElementById("td-sbc-body");
    if (!el) return;
    if (!sbc || !sbc.perPlanet) { el.innerHTML = `<div class="ks-empty-note">Waiting for data...</div>`; return; }
    let html = '';
    Object.entries(sbc.perPlanet).forEach(([planet, info]) => {
        const targets = info.vedhaTargets.length
            ? info.vedhaTargets.map(v => `<span class="ks-pair-chip" style="background:rgba(239,68,68,0.15); color:#f87171;">${v.nakshatra} (${v.type})</span>`).join('')
            : `<span class="ks-sig-chip">No Vedha</span>`;
        html += `<div style="margin-bottom:6px; padding-bottom:6px; border-bottom:1px solid rgba(42,59,92,0.3);">
            <div class="ks-astro-row"><span class="ks-astro-label"><strong style="color:#FFD700;">${planet}</strong> — ${info.nakshatra} (Pada ${info.pada})</span><span class="ks-astro-val" style="font-size:9px; color:#94a3b8;">${info.motion}</span></div>
            <div style="margin-top:3px;">${targets}</div>
            ${info.latta ? `<div style="margin-top:3px; font-size:10px; color:#f59e0b;">Latta &rarr; ${info.latta}</div>` : ''}
        </div>`;
    });
    el.innerHTML = html;
}

function renderKPCusps(cusps, tableId = "kp-cusps-table") {
    const table = document.getElementById(tableId);
    if (!table || !cusps) return;
    let html = `<tr><th>House</th><th>Star</th><th>Sign</th><th>CSL</th><th>SSL</th></tr>`;
    for (let i = 1; i <= 12; i++) {
        const c = cusps[i];
        if (!c) continue;
        html += `<tr>
            <td style="color:#FFD700;">${i}</td>
            <td style="color:#34d399;">${c.sssl.NakName}</td>
            <td>${ksSignName(c.long)}</td>
            <td style="color:#f59e0b; font-weight:bold;">${c.sssl.SL}</td>
            <td>${c.sssl.SSL}</td>
        </tr>`;
    }
    table.innerHTML = html;
}

function renderKPPlanets(planets, tableId = "kp-planets-table") {
    const table = document.getElementById(tableId);
    if (!table || !planets) return;
    let html = `<tr><th>Planet</th><th>Star</th><th>Sign</th><th>SL</th><th>SSL</th><th>ABCD</th></tr>`;
    KS_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;">${ksLbl(sym)}${retro}</td>
            <td style="color:#34d399;">${p.sssl.NakName}</td>
            <td>${ksSignName(p.long)}</td>
            <td style="color:#f59e0b; font-weight:bold;">${p.sssl.SL}</td>
            <td>${p.sssl.SSL}</td>
            <td style="font-size:8.5px;">${p.abcd || '-'}</td>
        </tr>`;
    });
    table.innerHTML = html;
}

function renderDashaChain(dasha) {
    const el = document.getElementById("md-dasha-chain");
    if (!el) return;
    if (!dasha || !dasha.active || !dasha.active.length) {
        el.innerHTML = `<div class="ks-empty-note">Add your birth details in the extension popup's Profile tab to unlock this.</div>`;
        return;
    }
    el.innerHTML = `<div class="ks-dasha-chain">${dasha.active.map(l => ksLbl(l.lord)).join(' - ')}</div>`;
}

function renderActiveSigs(dasha) {
    const el = document.getElementById("md-active-sigs");
    if (!el) return;
    if (!dasha || !dasha.activeSignifications || !dasha.activeSignifications.length) {
        el.innerHTML = `<div class="ks-empty-note">Add your birth details in the extension popup's Profile tab to unlock this.</div>`;
        return;
    }
    el.innerHTML = dasha.activeSignifications.map(h => `<span class="ks-sig-chip">${h}</span>`).join('');
}

// -------------------------------------------------------------------------
// 6. LIVE UPDATES + POPUP-TRIGGERED OPEN
// background.js pushes a new payload roughly every 30s. SHOW_OVERLAY is
// sent by the popup's "Open Overlay Here" button, for pages where the
// on-page trigger button is hard to find (or on a fresh page load where
// the content script only just injected).
// -------------------------------------------------------------------------
chrome.runtime.onMessage.addListener((message) => {
    if (message.action === "UPDATE_CHART") drawAstrologyOverlay(message.data);
    if (message.action === "SHOW_OVERLAY") openOverlayBox();
});
