// =========================================================================
// KALASUTRA ASTRO AI v3 — POPUP CONTROLLER
// =========================================================================

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

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')}'`;
}
function signName(long) { return SIGNS[Math.floor(((long % 360) + 360) % 360 / 30)]; }

// -------------------------------------------------------------------------
// MESSAGING WITH RETRY — MV3 service workers go idle and take a brief
// moment to wake back up when the popup sends its first message. Sending
// immediately after popup-open can race that wake-up and fail with
// "Could not establish connection" even though the background script is
// perfectly fine a few hundred ms later. This retries once before giving
// up, which is what was causing "Natal" KP data (message-based) to
// intermittently fail while "Transit" KP data (a direct storage read,
// no message needed) kept working.
// -------------------------------------------------------------------------
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);
    });
}
// Wake the service worker as soon as the popup opens, so it's already
// warm by the time the person clicks anything.
chrome.runtime.sendMessage({ action: "REQUEST_ASTRO_UPDATE" }, () => void chrome.runtime.lastError);

// -------------------------------------------------------------------------
// CITY SEARCH / GEOCODING
// Uses Open-Meteo's free geocoding API (no key required). Returns lat/lng
// plus an IANA timezone name, which we then resolve to a numeric UTC-offset
// via the browser's own Intl API (accounting for DST at the relevant date).
// -------------------------------------------------------------------------
async function ksGeocodeCity(query) {
    try {
        const res = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(query)}&count=6&language=en&format=json`);
        if (res.ok) {
            const data = await res.json();
            if (data.results && data.results.length) return data.results;
        }
    } catch (e) { /* fall through to Nominatim */ }

    // Fallback: OpenStreetMap Nominatim. It doesn't return an IANA timezone
    // name like Open-Meteo does, so we resolve the offset from lat/lng
    // instead — close enough for a rough UTC estimate (15° per hour),
    // the person can still fine-tune the Timezone field by hand.
    try {
        const res2 = await fetch(`https://nominatim.openstreetmap.org/search?format=json&limit=6&q=${encodeURIComponent(query)}`);
        if (!res2.ok) return [];
        const raw = await res2.json();
        return raw.map(r => ({
            name: r.display_name.split(',')[0],
            admin1: '', country: r.display_name.split(',').slice(-1)[0].trim(),
            latitude: parseFloat(r.lat), longitude: parseFloat(r.lon),
            timezone: null // resolved by longitude estimate in wireCitySearch
        }));
    } catch (e) {
        return [];
    }
}

function ksResolveUtcOffsetHours(tzName, dateObj) {
    try {
        const dtf = new Intl.DateTimeFormat('en-US', { timeZone: tzName, timeZoneName: 'shortOffset' });
        const part = dtf.formatToParts(dateObj).find(p => p.type === 'timeZoneName')?.value || '';
        const m = part.match(/GMT([+-])(\d+)(?::(\d+))?/);
        if (!m) return 5.5;
        const sign = m[1] === '-' ? -1 : 1;
        const hh = parseInt(m[2], 10);
        const mm = m[3] ? parseInt(m[3], 10) : 0;
        return sign * (hh + mm / 60);
    } catch (e) {
        return 5.5;
    }
}

/**
 * Wires a "Search City" input+button+results-list to a set of target
 * fields. On selecting a result: fills lat/lng, and (if a timezone field
 * id is given) resolves & fills the UTC offset for that city at refDateFn().
 */
function wireCitySearch({ inputId, btnId, resultsId, latId, lngId, tzId, refDateFn }) {
    const btn = document.getElementById(btnId);
    const input = document.getElementById(inputId);
    const resultsEl = document.getElementById(resultsId);
    if (!btn || !input || !resultsEl) return;

    const runSearch = async () => {
        const q = input.value.trim();
        if (!q) return;
        resultsEl.innerHTML = `<div class="city-note">Searching...</div>`;
        try {
            const results = await ksGeocodeCity(q);
            if (!results.length) { resultsEl.innerHTML = `<div class="city-note">No matches found.</div>`; return; }
            resultsEl.innerHTML = results.map((r, i) =>
                `<div class="city-result-item" data-idx="${i}">${r.name}${r.admin1 ? ', ' + r.admin1 : ''}, ${r.country} <span style="color:#7887A8;">(${r.latitude.toFixed(2)}, ${r.longitude.toFixed(2)})</span></div>`
            ).join('');
            resultsEl.querySelectorAll('.city-result-item').forEach(el => {
                el.addEventListener('click', () => {
                    const r = results[parseInt(el.dataset.idx, 10)];
                    document.getElementById(latId).value = r.latitude.toFixed(4);
                    document.getElementById(lngId).value = r.longitude.toFixed(4);
                    document.getElementById(latId).disabled = false;
                    document.getElementById(lngId).disabled = false;
                    if (tzId) {
                        const refDate = refDateFn ? refDateFn() : new Date();
                        if (r.timezone) {
                            document.getElementById(tzId).value = ksResolveUtcOffsetHours(r.timezone, refDate);
                        } else {
                            // Nominatim result: no IANA tz name, estimate from longitude (15°/hour).
                            document.getElementById(tzId).value = Math.round((r.longitude / 15) * 4) / 4;
                        }
                    }
                    resultsEl.innerHTML = `<div class="city-note ok">Selected: ${r.name}, ${r.country}</div>`;
                });
            });
        } catch (e) {
            resultsEl.innerHTML = `<div class="city-note err">Search failed — check your internet connection.</div>`;
        }
    };

    btn.addEventListener('click', runSearch);
    input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); runSearch(); } });
}

// --- TAB SWITCHING LOGIC ---
document.querySelectorAll('.tab-btn').forEach(button => {
    button.addEventListener('click', () => {
        document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
        button.classList.add('active');
        const targetId = button.getAttribute('data-target');
        document.getElementById(targetId).classList.add('active');
        if (targetId === 'tab-kp') loadKPData();
    });
});

// Default every date/time input to the current system date/time.
const now = new Date();
const todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
const timeStr = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
['tr-date', 'pc-date'].forEach(id => { const el = document.getElementById(id); if (el) el.value = todayStr; });
['tr-time', 'pc-time'].forEach(id => { const el = document.getElementById(id); if (el) el.value = timeStr; });

// --- ENGINE CONTROL (Tab: Engine) ---
const presetSelect = document.getElementById('location-preset');
const latInput = document.getElementById('lat-input');
const lngInput = document.getElementById('lng-input');

presetSelect.addEventListener('change', () => {
    if (presetSelect.value === 'mumbai') {
        latInput.value = '19.0600';
        lngInput.value = '72.8600';
        document.getElementById('eng-timezone').value = '5.5';
        latInput.disabled = true;
        lngInput.disabled = true;
    } else {
        latInput.disabled = false;
        lngInput.disabled = false;
    }
});
latInput.disabled = true;
lngInput.disabled = true;

wireCitySearch({
    inputId: 'eng-city-input', btnId: 'eng-city-btn', resultsId: 'eng-city-results',
    latId: 'lat-input', lngId: 'lng-input', tzId: 'eng-timezone',
    refDateFn: () => new Date()
});
// Selecting a city always means "custom", not the Mumbai preset.
document.getElementById('eng-city-results').addEventListener('click', () => { presetSelect.value = 'custom'; });

document.getElementById('update-btn').addEventListener('click', () => {
    const settings = {
        lat: parseFloat(latInput.value),
        lng: parseFloat(lngInput.value),
        timezone: parseFloat(document.getElementById('eng-timezone').value) || 5.5,
        ayanamsa: document.getElementById('ayanamsa-select').value,
        nodes: document.getElementById('nodes-select').value
    };
    chrome.storage.local.set({ settings: settings }, () => {
        const btn = document.getElementById('update-btn');
        btn.innerText = "Engine Running";
        btn.style.backgroundColor = "#161f33";
        btn.style.color = "#A0AABF";
        document.getElementById('status-msg').style.display = "block";
        ksSendMessage({ action: "START_INTRADAY_LOOP" }, () => {});
    });
});

chrome.storage.local.get('settings', (data) => {
    if (data.settings) {
        const s = data.settings;
        if (s.ayanamsa) document.getElementById('ayanamsa-select').value = s.ayanamsa;
        if (s.nodes) document.getElementById('nodes-select').value = s.nodes;
        if (s.timezone !== undefined) document.getElementById('eng-timezone').value = s.timezone;
        if (s.lat !== undefined && s.lng !== undefined) {
            const isMumbai = Math.abs(s.lat - 19.06) < 0.001 && Math.abs(s.lng - 72.86) < 0.001;
            presetSelect.value = isMumbai ? 'mumbai' : 'custom';
            latInput.value = s.lat;
            lngInput.value = s.lng;
            latInput.disabled = isMumbai;
            lngInput.disabled = isMumbai;
        }
    }
});

// --- USER PROFILE (Tab: Profile) ---
wireCitySearch({
    inputId: 'pf-city-input', btnId: 'pf-city-btn', resultsId: 'pf-city-results',
    latId: 'pf-birth-lat', lngId: 'pf-birth-lng', tzId: 'pf-timezone',
    refDateFn: () => {
        const bd = document.getElementById('pf-birth-date').value;
        const bt = document.getElementById('pf-birth-time').value;
        if (bd && bt) {
            const [y, m, d] = bd.split('-').map(Number);
            const [hh, mm] = bt.split(':').map(Number);
            return new Date(y, m - 1, d, hh, mm);
        }
        return new Date();
    }
});

document.getElementById('save-profile-btn').addEventListener('click', () => {
    const profile = {
        name: document.getElementById('pf-name').value.trim(),
        age: document.getElementById('pf-age').value,
        birthDate: document.getElementById('pf-birth-date').value,
        birthTime: document.getElementById('pf-birth-time').value,
        birthLat: document.getElementById('pf-birth-lat').value,
        birthLng: document.getElementById('pf-birth-lng').value,
        timezone: parseFloat(document.getElementById('pf-timezone').value) || 5.5
    };
    if (!profile.birthDate || !profile.birthTime) {
        alert("Please enter both Birth Date and Birth Time — required for Dasha, Tara Bala, Ashtakavarga, and Natal KP data.");
        return;
    }
    ksSendMessage({ action: "SAVE_PROFILE", profile: profile }, () => {
        const status = document.getElementById('profile-status');
        status.style.display = "block";
        setTimeout(() => status.style.display = "none", 2500);
        refreshProfileSummary();
    });
});

function refreshProfileSummary() {
    chrome.storage.local.get('ks_natal_summary', (data) => {
        if (data.ks_natal_summary) {
            document.getElementById('pf-summary-star').innerText = data.ks_natal_summary.birthStarName;
            document.getElementById('pf-summary-lagna').innerText = data.ks_natal_summary.lagna;
            document.getElementById('profile-summary').style.display = "block";
        }
    });
}

chrome.storage.local.get('ks_profile', (data) => {
    if (data.ks_profile) {
        const p = data.ks_profile;
        if (p.name) document.getElementById('pf-name').value = p.name;
        if (p.age) document.getElementById('pf-age').value = p.age;
        if (p.birthDate) document.getElementById('pf-birth-date').value = p.birthDate;
        if (p.birthTime) document.getElementById('pf-birth-time').value = p.birthTime;
        if (p.birthLat) document.getElementById('pf-birth-lat').value = p.birthLat;
        if (p.birthLng) document.getElementById('pf-birth-lng').value = p.birthLng;
        if (p.timezone !== undefined) document.getElementById('pf-timezone').value = p.timezone;
        refreshProfileSummary();
    }
});

// --- DASHA TAB (5-level: MD -> AD -> PD -> SD -> PRD, PRD lazy-loaded) ---
document.getElementById('btn-run-dasha')?.addEventListener('click', () => {
    const btn = document.getElementById('btn-run-dasha');
    const original = btn.innerText;
    btn.innerText = "Generating...";
    ksSendMessage({ action: "REQUEST_DASHA_TREE" }, (res, err) => {
        btn.innerText = original;
        if (err) { alert("Background engine not responding: " + err.message); return; }
        if (!res || res.error) { alert(res?.error || "Could not generate the dasha tree. Save your birth Profile first."); return; }
        document.getElementById('ks-dasha-module').style.display = "block";
        document.getElementById('ks-dasha-tree').innerHTML = res.tree.map(renderMdNode).join('');
    });
});

function lbl(lord) { return PLANET_FULL[lord] || lord; }

function renderMdNode(md) {
    return `<details><summary>${lbl(md.lord)} MD <span class="dasha-date">${md.start} &rarr; ${md.end}</span> <span class="dasha-sigs">${md.sig}</span></summary>
        ${md.children.map(ad => `<details><summary>${lbl(ad.lord)} AD <span class="dasha-date">${ad.start} &rarr; ${ad.end}</span> <span class="dasha-sigs">${ad.sig}</span></summary>
            ${ad.children.map(pd => `<details><summary>${lbl(pd.lord)} PD <span class="dasha-date">${pd.start} &rarr; ${pd.end}</span> <span class="dasha-sigs">${pd.sig}</span></summary>
                ${pd.children.map(sd => `<details class="ks-sd-node" data-start="${sd._startJd}" data-dur="${sd._durDays}" data-idx="${sd._idx}"><summary>${lbl(sd.lord)} SD <span class="dasha-date">${sd.start} &rarr; ${sd.end}</span> <span class="dasha-sigs">${sd.sig}</span></summary><div class="ks-prd-body"><div class="prd-loading">Expand to load Prana Dasha...</div></div></details>`).join('')}
            </details>`).join('')}
        </details>`).join('')}
    </details>`;
}

// SD nodes are collapsed by default and only carry the raw data needed to
// compute their 5th-level (Prana Dasha) children. We load those lazily,
// the first time a given SD node is actually expanded — avoids building
// (and shipping across the message channel) all 9^5 leaves up front.
document.getElementById('ks-dasha-tree').addEventListener('toggle', (e) => {
    const node = e.target;
    if (!node.matches('.ks-sd-node') || !node.open) return;
    const body = node.querySelector('.ks-prd-body');
    if (body.dataset.loaded) return;
    body.dataset.loaded = '1';
    const startJd = parseFloat(node.dataset.start);
    const durDays = parseFloat(node.dataset.dur);
    const idx = parseInt(node.dataset.idx, 10);
    ksSendMessage({ action: "REQUEST_PRD_CHILDREN", startJd, durDays, idx }, (res, err) => {
        if (err) { body.innerHTML = `<div class="prd-loading">Could not load — try again.</div>`; return; }
        if (!res || res.error) { body.innerHTML = `<div class="prd-loading">${res?.error || 'Could not load.'}</div>`; return; }
        body.innerHTML = res.children.map(prd => `<div class="sd-node">${lbl(prd.lord)} PRD: ${prd.start} &rarr; ${prd.end} <span class="dasha-sigs">${prd.sig}</span></div>`).join('');
    });
}, true); // capture: <details> "toggle" events don't bubble, so we intercept on the way down

// --- TRANSIT TAB (with optional location override + city search) ---
wireCitySearch({
    inputId: 'tr-city-input', btnId: 'tr-city-btn', resultsId: 'tr-city-results',
    latId: 'tr-lat', lngId: 'tr-lng', tzId: 'tr-timezone',
    refDateFn: () => {
        const d = document.getElementById('tr-date').value;
        const t = document.getElementById('tr-time').value;
        if (d && t) {
            const [y, m, dd] = d.split('-').map(Number);
            const [hh, mm] = t.split(':').map(Number);
            return new Date(y, m - 1, dd, hh, mm);
        }
        return new Date();
    }
});

document.getElementById('btn-run-transit')?.addEventListener('click', () => {
    const date = document.getElementById('tr-date').value;
    const time = document.getElementById('tr-time').value;
    if (!date || !time) { alert("Pick a transit date and time."); return; }

    const msg = { action: "REQUEST_CHART_FOR_DATETIME", date, time };
    const trLat = document.getElementById('tr-lat').value;
    const trLng = document.getElementById('tr-lng').value;
    const trTz = document.getElementById('tr-timezone').value;
    if (trLat !== '' && trLng !== '') {
        msg.lat = trLat; msg.lng = trLng;
        if (trTz !== '') msg.timezone = trTz;
    }

    ksSendMessage(msg, (res, err) => {
        if (err) { alert("Background engine not responding: " + err.message); return; }
        if (!res || res.error) { alert(res?.error || "Engine not ready yet — give it a few seconds after install and try again."); return; }
        renderTransitTable(res.data);
    });
});

function renderTransitTable(data) {
    document.getElementById('ks-transit-data-module').style.display = "block";
    const table = document.getElementById('ks-tdata-table-body');
    let html = `<tr><th>Planet</th><th>Sign</th><th>Deg</th><th>StL</th><th>SL</th><th>SSL</th><th>Hse</th></tr>`;
    PLANET_ORDER_12.forEach(sym => {
        const p = data.planets[sym];
        if (!p) return;
        html += `<tr>
            <td>${PLANET_FULL[sym]}${p.isRetro ? ' (R)' : ''}</td>
            <td>${signName(p.long)}</td>
            <td>${formatDeg(p.long)}</td>
            <td>${p.sssl.StL}</td>
            <td>${p.sssl.SL}</td>
            <td>${p.sssl.SSL}</td>
            <td>${p.kp_house}</td>
        </tr>`;
    });
    table.innerHTML = html;
}

// --- PANCHANG TAB ---
document.getElementById('btn-run-panchang')?.addEventListener('click', () => {
    const date = document.getElementById('pc-date').value;
    const time = document.getElementById('pc-time').value;
    if (!date || !time) { alert("Pick a panchang date and time."); return; }
    ksSendMessage({ action: "REQUEST_CHART_FOR_DATETIME", date, time }, (res, err) => {
        if (err) { alert("Background engine not responding: " + err.message); return; }
        if (!res || res.error) { alert(res?.error || "Engine not ready yet — give it a few seconds after install and try again."); return; }
        renderPanchangTable(res.data.panchang);
    });
});

function renderPanchangTable(p) {
    const el = document.getElementById('ks-panchang-module');
    el.style.display = "block";
    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 = `<table style="width:100%; border-collapse:collapse;">` +
        rows.map(([l, v]) => `<tr><td style="color:#A0AABF; padding:5px 4px; border-bottom:1px solid #1f2b47;">${l}</td><td style="color:#FFD700; font-weight:bold; padding:5px 4px; border-bottom:1px solid #1f2b47;">${v ?? '--'}</td></tr>`).join('') +
        `</table>`;
}

// --- KP DATA TAB (Natal + Transit) ---
function renderKPCusps(cusps) {
    const table = document.getElementById('kp-cusps-table');
    if (!table || !cusps) { if (table) table.innerHTML = ''; 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>${signName(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) {
    const table = document.getElementById('kp-planets-table');
    if (!table || !planets) { if (table) table.innerHTML = ''; return; }
    let html = `<tr><th>Planet</th><th>Star</th><th>Sign</th><th>SL</th><th>SSL</th><th>ABCD</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 style="color:#34d399;">${p.sssl.NakName}</td>
            <td>${signName(p.long)}</td>
            <td style="color:#f59e0b; font-weight:bold;">${p.sssl.SL}</td>
            <td>${p.sssl.SSL}</td>
            <td style="font-size:9.5px;">${p.abcd || '-'}</td>
        </tr>`;
    });
    table.innerHTML = html;
}

function showKPEmpty(msg) {
    document.getElementById('kp-cusps-table').innerHTML = `<tr><td style="color:#7887A8;">${msg}</td></tr>`;
    document.getElementById('kp-planets-table').innerHTML = '';
}

function loadKPData() {
    const view = document.getElementById('kp-view-select').value;
    if (view === 'transit') {
        chrome.storage.local.get('ks_latest_astro', (data) => {
            if (!data.ks_latest_astro) { showKPEmpty("Waiting for the engine's first tick..."); return; }
            renderKPCusps(data.ks_latest_astro.cusps);
            renderKPPlanets(data.ks_latest_astro.planets);
        });
    } else {
        ksSendMessage({ action: "REQUEST_NATAL_KP_CHART" }, (res, err) => {
            if (err) { showKPEmpty("Background engine not responding — try switching tabs again in a moment."); return; }
            if (!res || res.error) { showKPEmpty(res?.error || "Save your birth Profile first."); return; }
            renderKPCusps(res.cusps);
            renderKPPlanets(res.planets);
        });
    }
    loadDashaChainAndSigs();
}
document.getElementById('kp-view-select')?.addEventListener('change', loadKPData);

// --- Running dasha chain + active significations (My Data tab) ---
function loadDashaChainAndSigs() {
    chrome.storage.local.get('ks_latest_astro', (data) => {
        renderDashaChain(data.ks_latest_astro?.dasha);
    });
}
function renderDashaChain(dasha) {
    const chainEl = document.getElementById('md-dasha-chain');
    const sigsEl = document.getElementById('md-active-sigs');
    if (!chainEl || !sigsEl) return;
    if (!dasha || !dasha.active || !dasha.active.length) {
        chainEl.innerHTML = `<div style="color:#7887A8; font-size:12px; text-align:center;">Save your Profile tab to unlock this.</div>`;
        sigsEl.innerHTML = `<div style="color:#7887A8; font-size:12px; text-align:center;">Save your Profile tab to unlock this.</div>`;
        return;
    }
    chainEl.innerHTML = `<div class="dasha-chain-display">${dasha.active.map(l => lbl(l.lord)).join(' - ')}</div>`;
    sigsEl.innerHTML = dasha.activeSignifications && dasha.activeSignifications.length
        ? dasha.activeSignifications.map(h => `<span class="sig-chip">${h}</span>`).join('')
        : `<div style="color:#7887A8; font-size:12px; text-align:center;">--</div>`;
}

// --- LIVE TRANSIT PANEL (top of Transit tab, auto-updating) ---
function renderLiveTransitPanel(data) {
    if (!data || data.error) return;
    const p = data.panchang || {};
    const set = (id, v) => { const el = document.getElementById(id); if (el) el.innerText = (v === undefined || v === null || v === '') ? '--' : v; };

    set('lv-weekday', p.weekday);
    set('lv-tithi', p.tithi || data.tithi);
    set('lv-hora', p.hora || data.hora);
    set('lv-rahukalam', p.rahuKalam);
    set('lv-choghadiya', p.choghadiya || data.choghadiya);
    set('lv-karana', p.karana);
    set('lv-yoga', p.yoga);
    if (data.planets && data.planets['Mo']) {
        set('lv-moonsign', signName(data.planets['Mo'].long));
        set('lv-moonstar', data.moonNakshatraName);
    }

    const taraEl = document.getElementById('lv-tarabala-body');
    if (taraEl) {
        if (!data.taraBala) {
            taraEl.innerHTML = `<div class="live-row"><span class="live-label" style="color:#7887A8;">Save your Profile tab to unlock this.</span></div>`;
        } else {
            const cls = data.taraBala.favorable ? 'chip-good' : 'chip-bad';
            taraEl.innerHTML = `
                <div class="live-row"><span class="live-label">Your Moon Sign/Star</span><span class="live-val">${data.taraBala.birthNakshatra}</span></div>
                <div class="live-row"><span class="live-label">Transit Moon Star</span><span class="live-val">${data.taraBala.transitNakshatra} (Pada ${data.taraBala.transitPada})</span></div>
                <div class="live-row"><span class="live-label">Tara</span><span class="live-val ${cls}">${data.taraBala.tara}</span></div>`;
        }
    }

    const avEl = document.getElementById('lv-ashtakavarga-body');
    if (avEl) {
        if (!data.ashtakavarga) {
            avEl.innerHTML = `<div class="live-row"><span class="live-label" style="color:#7887A8;">Save your Profile tab to unlock this.</span></div>`;
        } else {
            const cls = data.ashtakavarga.points >= 4 ? 'chip-good' : 'chip-bad';
            avEl.innerHTML = `
                <div class="live-row"><span class="live-label">Transit Moon Sign</span><span class="live-val">${data.ashtakavarga.sign}</span></div>
                <div class="live-row"><span class="live-label">Bindus (Points)</span><span class="live-val ${cls}">${data.ashtakavarga.points} / ${data.ashtakavarga.maxPoints}</span></div>`;
        }
    }

    const lagnaEl = document.getElementById('lv-lagna-body');
    if (lagnaEl && data.cusps && data.cusps[1]) {
        const c1 = data.cusps[1];
        lagnaEl.innerHTML = `
            <div class="live-row"><span class="live-label">Lagna</span><span class="live-val">${data.lagnaName || signName(c1.long)}</span></div>
            <div class="live-row"><span class="live-label">Lagna Lord</span><span class="live-val">${lbl(c1.sssl.SgL)}</span></div>
            <div class="live-row"><span class="live-label">Lagna Star</span><span class="live-val">${c1.sssl.NakName}</span></div>
            <div class="live-row"><span class="live-label">Lagna Sub Lord</span><span class="live-val">${lbl(data.lagnaSSL || c1.sssl.SSL)}</span></div>
            <div class="live-row"><span class="live-label">Sub Lord Significations</span><span class="live-val" style="font-size:10.5px;">${data.lagnaABCD || '-'}</span></div>`;
    }

    const moonEl = document.getElementById('lv-moondetail-body');
    const mo = data.planets && data.planets['Mo'];
    if (moonEl && mo) {
        moonEl.innerHTML = `
            <div class="live-row"><span class="live-label">Moon Sign</span><span class="live-val">${signName(mo.long)}</span></div>
            <div class="live-row"><span class="live-label">Moon Star</span><span class="live-val">${data.moonNakshatraName || mo.sssl.NakName}</span></div>
            <div class="live-row"><span class="live-label">Moon Sub Lord</span><span class="live-val">${lbl(mo.sssl.SL)}</span></div>
            <div class="live-row"><span class="live-label">Sub Lord Significations</span><span class="live-val" style="font-size:10.5px;">${mo.abcd || '-'}</span></div>
            <div class="live-row"><span class="live-label">Moon Significations</span><span class="live-val">${mo.houseSigStr || '-'}</span></div>`;
    }

    const conjEl = document.getElementById('lv-conjunctions-body');
    if (conjEl) {
        conjEl.innerHTML = (data.conjunctions && data.conjunctions.length)
            ? data.conjunctions.map(c => `<span class="pair-chip">${lbl(c.a)} + ${lbl(c.b)} (${c.sign})</span>`).join('')
            : `<span style="color:#7887A8; font-size:12px;">None right now.</span>`;
    }

    const aspEl = document.getElementById('lv-aspects-body');
    if (aspEl) {
        aspEl.innerHTML = (data.aspects && data.aspects.length)
            ? data.aspects.map(a => `<span class="pair-chip">${lbl(a.from)} &rarr; ${lbl(a.to)} (${a.house}th)</span>`).join('')
            : `<span style="color:#7887A8; font-size:12px;">None right now.</span>`;
    }

    const sbcEl = document.getElementById('lv-sbc-body');
    if (sbcEl) {
        if (!data.sbc || !data.sbc.perPlanet) {
            sbcEl.innerHTML = `<span style="color:#7887A8; font-size:12px;">Waiting for data...</span>`;
        } else {
            let html = '';
            Object.entries(data.sbc.perPlanet).forEach(([planet, info]) => {
                const targets = info.vedhaTargets.length
                    ? info.vedhaTargets.map(v => `<span class="pair-chip" style="background:rgba(239,68,68,0.15); color:#ff5733;">${v.nakshatra} (${v.type})</span>`).join('')
                    : `<span class="sig-chip">No Vedha</span>`;
                html += `<div style="margin-bottom:6px; padding-bottom:6px; border-bottom:1px solid #1f2b47;">
                    <div class="live-row"><span class="live-label"><strong style="color:#FFD700;">${planet}</strong> — ${info.nakshatra} (Pada ${info.pada})</span><span class="live-val" style="font-size:10px; color:#94a3b8;">${info.motion}</span></div>
                    <div style="margin-top:3px;">${targets}</div>
                    ${info.latta ? `<div style="margin-top:3px; font-size:11px; color:#f59e0b;">Latta &rarr; ${info.latta}</div>` : ''}
                </div>`;
            });
            sbcEl.innerHTML = html;
        }
    }
}

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

// Keep the live Transit panel, the Transit KP view, and the dasha
// chain/significations all in sync while the popup stays open — background.js
// pushes a fresh ks_latest_astro roughly every 30s.
chrome.storage.onChanged.addListener((changes, area) => {
    if (area !== 'local' || !changes.ks_latest_astro) return;
    const data = changes.ks_latest_astro.newValue;
    renderLiveTransitPanel(data);
    renderDashaChain(data?.dasha);
    if (document.getElementById('kp-view-select')?.value === 'transit' && document.getElementById('tab-kp')?.classList.contains('active')) {
        renderKPCusps(data.cusps);
        renderKPPlanets(data.planets);
    }
});
