import { PRG_MONEY }        from '/js/database/programs/money.js';
import { PRG_RELATIONS }    from '/js/database/programs/relations.js';
import { PRG_TAIL }         from '/js/database/programs/tail.js';
import { PRG_TALENTS }      from '/js/database/programs/talents.js';
import { PRG_FATHER }       from '/js/database/programs/father.js';
import { PRG_MOTHER }       from '/js/database/programs/mother.js';
import { PRG_DESTINY }      from '/js/database/programs/destiny.js'; 

import forecastContent      from '/js/database/lichn/arcanas/forecast.js'; 
import { compatForecastContent } from '/js/database/compat/arcanas/forecast.js';

import { ARCANA_DATA }      from '/js/tech/config/arcanaData.js';
import { MASTER_TITLES }    from '/js/database/programs/program_titles.js';

const reduce = (n) => {
    let v = Math.abs(n);
    while (v > 22) {
        v = v.toString().split('').reduce((a, b) => parseInt(a) + parseInt(b), 0);
    }
    return v === 0 ? 22 : v;
};

const ARCANA_NAMES = ["", "Маг", "Жрица", "Императрица", "Император", "Иерофант", "Влюбленные", "Колесница", "Справедливость", "Отшельник", "Колесо Фортуны", "Сила", "Повешенный", "Смерть", "Умеренность", "Дьявол", "Башня", "Звезда", "Луна", "Солнце", "Суд", "Мир", "Шут"];
export function arcanaName(n) { return ARCANA_NAMES[n] || `Аркан ${n}`; }

// === КОНФИГУРАЦИЯ ===
export const SECTIONS_CONFIG = {
    general: { 
        id: 'general', title: 'ОБЩЕЕ', type: 'simple',
        ids: ['Pers_Levo_3', 'Pers_Verh_3', 'Pers_Pravo_3', 'Pers_Niz_3', 'Center']
    },
    purpose_pers: { 
        id: 'purpose_pers', 
        title: 'ЛИЧНОЕ', 
        type: 'program', 
        db: PRG_DESTINY, 
        ids: ['Pers_Levo_3', 'Pers_Verh_3', 'Pers_Pravo_3', 'Pers_Niz_3'] 
    },
    purpose_soc: { 
        id: 'purpose_soc', 
        title: 'СОЦИУМ', 
        type: 'program', 
        db: PRG_DESTINY, 
        ids: ['Rod_F_Verh_3', 'Rod_M_Verh_3', 'Rod_F_Niz_3', 'Rod_M_Niz_3']
    },
    money: { 
        id: 'money', title: 'ДЕНЬГИ', type: 'program', db: PRG_MONEY,
        ids: ['Pers_Pravo_2', 'Budget_odin', 'Obshee'] 
    },
    relations: { 
        id: 'relations', title: 'ОТНОШЕНИЯ', type: 'program', db: PRG_RELATIONS,
        ids: ['Lubov_odin', 'Obshee', 'Pers_Niz_2'] 
    },
    talents: { 
        id: 'talents', title: 'ТАЛАНТЫ', type: 'program', db: PRG_TALENTS,
        ids: ['Pers_Verh_3', 'Pers_Verh_1', 'Pers_Verh_2']
    },
    tail: { 
        id: 'tail', title: 'ХВОСТ', type: 'program', db: PRG_TAIL,
        ids: ['Pers_Niz_3', 'Pers_Niz_1', 'Pers_Niz_2']
    },
    father: { 
        id: 'father', title: 'РОД (О)', type: 'program', db: PRG_FATHER,
        ids: ['Rod_F_Verh_3', 'Rod_F_Verh_1', 'Rod_F_Verh_2'] 
    },
    mother: { 
        id: 'mother', title: 'РОД (М)', type: 'program', db: PRG_MOTHER,
        ids: ['Rod_M_Verh_3', 'Rod_M_Verh_1', 'Rod_M_Verh_2']
    },
    health: { id: 'health', title: 'ЗДОРОВЬЕ', type: 'special' },
    forecast: { 
        id: 'forecast', title: 'ПРОГНОЗ', type: 'forecast',
        ids: ['Pers_Levo_3', 'Pers_Verh_3']
    }
};

export const ORDERED_SECTIONS = [
  'general', 'purpose_pers', 'purpose_soc', 'money', 'relations', 
  'health', 'talents', 'tail', 'father', 'mother', 'forecast'
];

export function getContent(sectionId, allNodes, mode = 'single') {
    const config = SECTIONS_CONFIG[sectionId];
    if (!config) return null;

    const rawValues = (config.ids || []).map(id => {
        const node = allNodes.find(n => n.id === id);
        return node ? parseInt(node.val) : 0;
    });

    // --- ПРОГНОЗ ---
    if (config.type === 'forecast') {
        const [day, month] = rawValues;
        if (!day || !month) return null;

        const currentYear = new Date().getFullYear();
        const forecasts = [];
        const sourceDB = (mode === 'compat') ? compatForecastContent : forecastContent;

        for (let i = 0; i < 10; i++) {
            const targetYear = currentYear + i;
            const yearArcana = reduce(day + month + reduce(targetYear));
            const data = (sourceDB && sourceDB[yearArcana]) ? sourceDB[yearArcana] : {};
            
            forecasts.push({
                year: targetYear,
                val: yearArcana,
                name: arcanaName(yearArcana),
                text: data
            });
        }
        return { type: 'forecast', sectionTitle: config.title, items: forecasts };
    }

    // --- ПРОГРАММЫ ---
    if (config.type === 'program') {
        let searchKey = "";
        let displayCodes = rawValues;

        if (sectionId === 'purpose_pers') {
            const [day, month, year, tail] = rawValues;
            const sky = reduce(month + tail);
            const earth = reduce(day + year);
            const total = reduce(sky + earth);
            
            // === ПОРЯДОК 12-18-3 (Небо - Земля - Итог) ===
            const order = [sky, total, earth]; 
            
            searchKey = order.join('-'); 
            displayCodes = order;
            
            // ОТЛАДКА: Посмотри в консоль браузера (F12)
            console.log(`[DEBUG] ЛИЧНОЕ: Ищем ключ "${searchKey}"`);
        }
        else if (sectionId === 'purpose_soc') {
            const [f, g, h, i] = rawValues;
            const male = reduce(f + h);
            const female = reduce(g + i);
            const total = reduce(male + female);
            
            // === ПОРЯДОК 1-3-2 ===
            const order = [male, female, total];
            
            searchKey = order.join('-'); 
            displayCodes = order;
        }
        else {
            searchKey = rawValues.join('-');
        }

        let masterTitle = null;
        let finalText = null;
        let advice = "";

        if (mode === 'single') {
            masterTitle = MASTER_TITLES[searchKey];
            const db = config.db || {};
            // Пробуем найти прямой ключ
            const prog = db[searchKey] || db[searchKey.replace(/-/g, ' ')] || {};

            masterTitle = masterTitle || prog.title;
            finalText = prog.text;
            
            if (!finalText && (prog.positive || prog.negative)) {
                finalText = `
                    <div style="margin-bottom:10px;"><strong style="color:#C6FF00">ПЛЮС:</strong> ${prog.positive}</div>
                    <div><strong style="color:#ff4d4d">МИНУС:</strong> ${prog.negative}</div>
                `;
            }
            advice = prog.advice;
        } 
        
        const programTitle = masterTitle || config.title;

        // === ГЕНЕРАЦИЯ КАРТОЧЕК ===
        const cards = displayCodes.map(val => {
            const rootData = ARCANA_DATA[val] || {};
            let source = rootData;
            
            if (mode === 'compat' && rootData.compat) {
                source = rootData.compat;
            }

            if (sectionId === 'money' && source.money && (source.money.plus || source.money.positive)) {
                source = source.money;
            }
            else if (sectionId === 'relations' && source.relations && (source.relations.plus || source.relations.positive)) {
                source = source.relations;
            }

            const name = (mode === 'compat' && rootData.compat) ? rootData.compat.name : arcanaName(val);

            return {
                val: val,
                name: name,
                plus: source.plus || source.positive,
                minus: source.minus || source.negative,
                advice: source.advice
            };
        });

        return {
            type: 'program',
            sectionTitle: config.title,
            programTitle: programTitle, 
            text: finalText, 
            advice: advice || "",
            codes: displayCodes,
            cards: cards 
        };
    }

    // --- ПРОСТЫЕ ---
    if (config.type === 'simple') {
        const cards = rawValues.map(val => {
            const rootData = ARCANA_DATA[val] || {};
            const source = (mode === 'compat' && rootData.compat) ? rootData.compat : rootData;
            
            return {
                val: val,
                name: source.name || arcanaName(val),
                plus: source.plus || source.positive,
                minus: source.minus || source.negative,
                advice: source.advice
            };
        });
        return { type: 'simple', sectionTitle: config.title, cards };
    }

    return { type: config.type, sectionTitle: config.title };
}
