// =========================================================================
// KALASUTRA V3 — KP CORE (shared constants + SgL/StL/SL/SSL + house lookup)
// Pure local JS, no server calls. Ported/consolidated from background.js
// and backtest.js so every module uses one single source of truth.
// =========================================================================

export const SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"];
export const SHORT_SIGNS = ["Ar", "Ta", "Ge", "Cn", "Le", "Vi", "Li", "Sc", "Sg", "Cp", "Aq", "Pi"];
export const SIGN_LORDS = ['Ma', 'Ve', 'Me', 'Mo', 'Su', 'Me', 'Ve', 'Ma', 'Ju', 'Sa', 'Sa', 'Ju'];

export const DASHA_LORDS = ['Ke', 'Ve', 'Su', 'Mo', 'Ma', 'Ra', 'Ju', 'Sa', 'Me'];
export const DASHA_YEARS = [7, 20, 6, 10, 7, 18, 16, 19, 17];
export const TOTAL_YEARS = 120;
export const NAK_ARC = 40 / 3; // 13°20'

export const NAK_NAMES = ["Ashwini", "Bharani", "Krittika", "Rohini", "Mrigashira", "Ardra", "Punarvasu", "Pushya", "Ashlesha", "Magha", "P.Phalguni", "U.Phalguni", "Hasta", "Chitra", "Swati", "Vishakha", "Anuradha", "Jyeshtha", "Mula", "P.Ashadha", "U.Ashadha", "Shravana", "Dhanishta", "Shatabhisha", "P.Bhadrapada", "U.Bhadrapada", "Revati"];

export const PLANET_NAMES = { Su: "Sun", Mo: "Moon", Ma: "Mars", Me: "Mercury", Ju: "Jupiter", Ve: "Venus", Sa: "Saturn", Ra: "Rahu", Ke: "Ketu", Ur: "Uranus", Ne: "Neptune", Pl: "Pluto" };

// The 9 Vedic (KP-significant) + 3 Western planets required by spec.
// Western outers are NOT used for KP SgL/StL/SL/SSL (they have no dasha lordship)
// but are shown for degree/sign/nakshatra reference only.
export const VEDIC_ORDER = ['Su', 'Mo', 'Ma', 'Me', 'Ju', 'Ve', 'Sa', 'Ra', 'Ke'];
export const WESTERN_ORDER = ['Ur', 'Ne', 'Pl'];
export const ALL_12_ORDER = [...VEDIC_ORDER, ...WESTERN_ORDER];

export const AVG_SPEEDS = { Su: 0.985, Mo: 13.176, Ma: 0.524, Me: 1.200, Ju: 0.083, Ve: 1.200, Sa: 0.033, Ra: 0.053, Ke: 0.053 };

export const formatDeg = (deg) => {
    let d = Math.floor(deg % 30);
    let m = Math.floor((deg % 1) * 60);
    let s = Math.floor((((deg % 1) * 60) % 1) * 60);
    return `${d.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
};

export function getSign(long) { return Math.floor(((long % 360) + 360) % 360 / 30); }
export function getNakIdx(long) { return Math.floor(((long % 360) + 360) % 360 / NAK_ARC); }
export function getPada(long) {
    const l = ((long % 360) + 360) % 360;
    return Math.floor((l % NAK_ARC) / (NAK_ARC / 4)) + 1;
}

// Finds which KP house (1-12, cusp-based, Placidus) a given longitude falls in.
export function getKPHouse(pLong, cuspsArr) {
    for (let i = 0; i < 12; i++) {
        let currentCusp = cuspsArr[i];
        let nextCusp = (i === 11) ? cuspsArr[0] : cuspsArr[i + 1];
        let houseNum = i + 1;
        if (currentCusp < nextCusp) {
            if (pLong >= currentCusp && pLong < nextCusp) return houseNum;
        } else {
            if (pLong >= currentCusp || pLong < nextCusp) return houseNum;
        }
    }
    return 12;
}

// Sign Lord / Star Lord / Sub Lord / Sub-Sub Lord for any sidereal longitude — the
// KP backbone. Sub-lord divisions follow the classical Vimshottari proportional split.
export function getKP_SSSL(degree) {
    let sign = getSign(degree);
    let nakIdx = getNakIdx(degree);
    let sgl = SIGN_LORDS[sign];
    let stlIdx = nakIdx % 9;
    let stl = DASHA_LORDS[stlIdx];
    let remDeg = degree % NAK_ARC;
    let accumulatedDeg = 0;
    let currentIdx = stlIdx;
    let sl = "", ssl = "";

    for (let i = 0; i < 9; i++) {
        let slSpan = (DASHA_YEARS[currentIdx] / TOTAL_YEARS) * NAK_ARC;
        if (remDeg <= accumulatedDeg + slSpan) {
            sl = DASHA_LORDS[currentIdx];
            let sslRemDeg = remDeg - accumulatedDeg;
            let sslAccumulated = 0;
            let sslCurrentIdx = currentIdx;
            for (let j = 0; j < 9; j++) {
                let sslSpan = (DASHA_YEARS[sslCurrentIdx] / TOTAL_YEARS) * slSpan;
                if (sslRemDeg <= sslAccumulated + sslSpan) { ssl = DASHA_LORDS[sslCurrentIdx]; break; }
                sslAccumulated += sslSpan;
                sslCurrentIdx = (sslCurrentIdx + 1) % 9;
            }
            break;
        }
        accumulatedDeg += slSpan;
        currentIdx = (currentIdx + 1) % 9;
    }
    return { SgL: sgl, StL: stl, SL: sl, SSL: ssl, Nak: nakIdx, NakName: NAK_NAMES[nakIdx], Pada: getPada(degree) };
}

// A/B/C/D level house significations for a planet, given the full cusps+planets map.
// Automatically calculates and returns the planet's Sub Lord significations as well.
export function getHouseSignifications(sym, cusps, planets) {
    const p = planets[sym];
    if (!p) return { str: "-", abcd: "[-] [-] [-] [-]", sl_str: "-", sl_abcd: "[-] [-] [-] [-]" };
    
    // --- 1. PLANET'S OWN SIGNIFICATIONS ---
    const stl = p.sssl.StL;
    const L1 = (planets[stl] && planets[stl].kp_house) ? planets[stl].kp_house : 0;
    const L2 = p.kp_house || 0;
    const L3 = [], L4 = [];
    
    for (let i = 1; i <= 12; i++) {
        if (cusps[i] && cusps[i].sssl.SgL === stl) L3.push(i);
        if (cusps[i] && cusps[i].sssl.SgL === sym) L4.push(i);
    }
    
    const allSigs = [L1, L2, ...L3, ...L4].filter(x => x > 0);
    
    // Removing the sort() function ensures the array keeps its A, B, C, D insertion priority
    const str = [...new Set(allSigs)].join(", ");
    const abcd = `[${L1 || '-'}] [${L2 || '-'}] [${L3.length ? L3.join(',') : '-'}] [${L4.length ? L4.join(',') : '-'}]`;

    // --- 2. SUB LORD'S SIGNIFICATIONS ---
    let sl_str = "-";
    let sl_abcd = "[-] [-] [-] [-]";
    
    if (p.sssl && p.sssl.SL) {
        const slSym = p.sssl.SL;
        const slP = planets[slSym];
        
        if (slP) {
            const sl_stl = slP.sssl.StL;
            const sl_L1 = (planets[sl_stl] && planets[sl_stl].kp_house) ? planets[sl_stl].kp_house : 0;
            const sl_L2 = slP.kp_house || 0;
            const sl_L3 = [], sl_L4 = [];
            
            for (let i = 1; i <= 12; i++) {
                if (cusps[i] && cusps[i].sssl.SgL === sl_stl) sl_L3.push(i);
                if (cusps[i] && cusps[i].sssl.SgL === slSym) sl_L4.push(i);
            }
            
            const sl_allSigs = [sl_L1, sl_L2, ...sl_L3, ...sl_L4].filter(x => x > 0);
            sl_str = [...new Set(sl_allSigs)].join(", ");
            sl_abcd = `[${sl_L1 || '-'}] [${sl_L2 || '-'}] [${sl_L3.length ? sl_L3.join(',') : '-'}] [${sl_L4.length ? sl_L4.join(',') : '-'}]`;
        }
    }

    return {
        str,
        abcd,
        sl_str,
        sl_abcd
    };
}

// Standard Julian-Day → JS Date (for display of dasha start/end dates).
export function jdToDate(jd) {
    return new Date((jd - 2440587.5) * 86400000);
}
export function jdToDateString(jd) {
    const dt = jdToDate(jd);
    return `${dt.getFullYear()}-${(dt.getMonth() + 1).toString().padStart(2, '0')}-${dt.getDate().toString().padStart(2, '0')}`;
}