import { ezhp_t, ezhp_getHouseSystemName, EZHP_HOUSE_SYSTEMS } from './i18n.js';

// Flatpickr locale mapping
const ezhp_flatpickrLocales = {
    en: 'default',
    fr: 'fr',
    it: 'it',
    de: 'de',
    es: 'es',
    pt: 'pt',
    ru: 'ru',
    ja: 'ja',
    zh: 'zh',
    ko: 'ko',
    ar: 'ar',
    hi: 'hi',
    tr: 'tr',
    pl: 'pl',
    nl: 'nl',
    sv: 'sv',
    uk: 'uk',
    cs: 'cs',
    el: 'gr',
    bg: 'bg',
    ro: 'ro',
    hu: 'hu',
    fi: 'fi',
    da: 'da',
    nb: 'no',
    th: 'th',
    id: 'id',
    ms: 'ms',
    bn: 'bn',
    fa: 'fa',
    he: 'he',
    et: 'et',
    lt: 'lt',
    lv: 'lv',
    sk: 'sk',
    sl: 'sl',
    ca: 'cat',
    sq: 'sq',
    az: 'az',
    ga: 'ga',
    eo: 'eo',
    tl: 'default'
};

// Track if flatpickr assets are loading/loaded
let ezhp_flatpickrLoading = false;
let ezhp_flatpickrLoaded = false;
let ezhp_flatpickrCallbacks = [];

// Load flatpickr CSS
function ezhp_loadFlatpickrCSS() {
    if (!document.querySelector('link[href*="flatpickr"]')) {
        const ezhp_link = document.createElement('link');
        ezhp_link.rel = 'stylesheet';
        ezhp_link.href = 'https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css';
        document.head.appendChild(ezhp_link);
    }
}

// Load flatpickr JS and locale (with callback queue)
function ezhp_loadFlatpickr(ezhp_locale, ezhp_callback) {
    // Already loaded
    if (ezhp_flatpickrLoaded && window.flatpickr) {
        ezhp_loadFlatpickrLocale(ezhp_locale, ezhp_callback);
        return;
    }

    // Add to callback queue
    ezhp_flatpickrCallbacks.push({ locale: ezhp_locale, callback: ezhp_callback });

    // Already loading, just wait
    if (ezhp_flatpickrLoading) {
        return;
    }

    ezhp_flatpickrLoading = true;

    const ezhp_script = document.createElement('script');
    ezhp_script.src = 'https://cdn.jsdelivr.net/npm/flatpickr';
    ezhp_script.onload = () => {
        ezhp_flatpickrLoaded = true;
        // Process all queued callbacks
        ezhp_flatpickrCallbacks.forEach(item => {
            ezhp_loadFlatpickrLocale(item.locale, item.callback);
        });
        ezhp_flatpickrCallbacks = [];
    };
    ezhp_script.onerror = () => {
        // Flatpickr failed to load - callbacks won't be called, native input remains
        ezhp_flatpickrLoading = false;
        ezhp_flatpickrCallbacks = [];
    };
    document.head.appendChild(ezhp_script);
}

// Load locale file separately
function ezhp_loadFlatpickrLocale(ezhp_locale, ezhp_callback) {
    if (!ezhp_locale || ezhp_locale === 'default') {
        ezhp_callback();
        return;
    }

    // Check if locale already loaded
    if (window.flatpickr.l10ns && window.flatpickr.l10ns[ezhp_locale]) {
        ezhp_callback();
        return;
    }

    const ezhp_localeScript = document.createElement('script');
    ezhp_localeScript.src = `https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/${ezhp_locale}.js`;
    ezhp_localeScript.onload = ezhp_callback;
    ezhp_localeScript.onerror = ezhp_callback; // Still init even if locale fails
    document.head.appendChild(ezhp_localeScript);
}

window.addEventListener('load', ezhp_bindSynastryChartBlocks);

function ezhp_bindSynastryChartBlocks() {

    const ezhp_blocks = document.querySelectorAll('.synastry-chart-block');

    if (ezhp_blocks.length === 0) {
        return;
    }

    // Load flatpickr CSS (non-blocking)
    ezhp_loadFlatpickrCSS();

    ezhp_blocks.forEach(ezhp_block => {

        const ezhp_lang = ezhp_block.dataset.ezhpLang || 'en';
        const ezhp_flatpickrLocale = ezhp_flatpickrLocales[ezhp_lang] || 'default';

        // Translate Person A labels
        const ezhp_personLabelA = ezhp_block.querySelector('.ezhp-person-label-a');
        if (ezhp_personLabelA) {
            ezhp_personLabelA.textContent = ezhp_t(ezhp_lang, 'personA');
        }

        const ezhp_innerWheelLabel = ezhp_block.querySelector('.ezhp-inner-wheel-label');
        if (ezhp_innerWheelLabel) {
            ezhp_innerWheelLabel.textContent = ezhp_t(ezhp_lang, 'innerWheel');
        }

        const ezhp_nameLabelA = ezhp_block.querySelector('.ezhp-name-label-a');
        if (ezhp_nameLabelA) {
            ezhp_nameLabelA.textContent = ezhp_t(ezhp_lang, 'enterNameA');
        }

        const ezhp_locationLabelA = ezhp_block.querySelector('.ezhp-location-label-a');
        if (ezhp_locationLabelA) {
            ezhp_locationLabelA.textContent = ezhp_t(ezhp_lang, 'enterLocationA');
        }

        const ezhp_datetimeLabelA = ezhp_block.querySelector('.ezhp-datetime-label-a');
        if (ezhp_datetimeLabelA) {
            ezhp_datetimeLabelA.textContent = ezhp_t(ezhp_lang, 'enterBirthDateTimeA');
        }

        // Set placeholder for name input A
        const ezhp_nameInputA = ezhp_block.querySelector('.ezhp-name-input-a');
        if (ezhp_nameInputA) {
            ezhp_nameInputA.placeholder = ezhp_t(ezhp_lang, 'personA');
        }

        // Translate Person B labels
        const ezhp_personLabelB = ezhp_block.querySelector('.ezhp-person-label-b');
        if (ezhp_personLabelB) {
            ezhp_personLabelB.textContent = ezhp_t(ezhp_lang, 'personB');
        }

        const ezhp_outerWheelLabel = ezhp_block.querySelector('.ezhp-outer-wheel-label');
        if (ezhp_outerWheelLabel) {
            ezhp_outerWheelLabel.textContent = ezhp_t(ezhp_lang, 'outerWheel');
        }

        const ezhp_nameLabelB = ezhp_block.querySelector('.ezhp-name-label-b');
        if (ezhp_nameLabelB) {
            ezhp_nameLabelB.textContent = ezhp_t(ezhp_lang, 'enterNameB');
        }

        const ezhp_locationLabelB = ezhp_block.querySelector('.ezhp-location-label-b');
        if (ezhp_locationLabelB) {
            ezhp_locationLabelB.textContent = ezhp_t(ezhp_lang, 'enterLocationB');
        }

        const ezhp_datetimeLabelB = ezhp_block.querySelector('.ezhp-datetime-label-b');
        if (ezhp_datetimeLabelB) {
            ezhp_datetimeLabelB.textContent = ezhp_t(ezhp_lang, 'enterBirthDateTimeB');
        }

        // Set placeholder for name input B
        const ezhp_nameInputB = ezhp_block.querySelector('.ezhp-name-input-b');
        if (ezhp_nameInputB) {
            ezhp_nameInputB.placeholder = ezhp_t(ezhp_lang, 'personB');
        }

        // Translate house system label
        const ezhp_houseSystemLabel = ezhp_block.querySelector('.ezhp-house-system-label');
        if (ezhp_houseSystemLabel) {
            ezhp_houseSystemLabel.textContent = ezhp_t(ezhp_lang, 'selectHouseSystem');
        }

        // Translate house system dropdown options
        const ezhp_houseSystemSelect = ezhp_block.querySelector('.ezhp-house-system-select');
        if (ezhp_houseSystemSelect && EZHP_HOUSE_SYSTEMS[ezhp_lang]) {
            const ezhp_options = ezhp_houseSystemSelect.querySelectorAll('option');
            ezhp_options.forEach(ezhp_option => {
                const ezhp_key = ezhp_option.value;
                ezhp_option.textContent = ezhp_getHouseSystemName(ezhp_lang, ezhp_key);
            });
            
            // Set initial value from data attribute
            const ezhp_initialHouseSystem = ezhp_block.dataset.houseSystem || 'placidus';
            ezhp_houseSystemSelect.value = ezhp_initialHouseSystem;
        }

        // Translate button
        const ezhp_btn = ezhp_block.querySelector('.ezhp-fetch-button');
        if (ezhp_btn) {
            ezhp_btn.textContent = ezhp_t(ezhp_lang, 'generateChart');
        }

        // Get form inputs
        const ezhp_locationInputA = ezhp_block.querySelector('.ezhp-location-input-a');
        const ezhp_datetimeInputA = ezhp_block.querySelector('.ezhp-datetime-input-a');
        const ezhp_locationInputB = ezhp_block.querySelector('.ezhp-location-input-b');
        const ezhp_datetimeInputB = ezhp_block.querySelector('.ezhp-datetime-input-b');
        const ezhp_button = ezhp_block.querySelector('.ezhp-fetch-button');
        const ezhp_resultContainer = ezhp_block.querySelector('.synastry-chart-result');

        if (!ezhp_locationInputA || !ezhp_datetimeInputA || !ezhp_locationInputB || !ezhp_datetimeInputB || !ezhp_button || !ezhp_resultContainer) {
            return;
        }

        // Try to enhance datetime inputs with flatpickr (non-blocking, native input works as fallback)
        if (ezhp_lang !== 'en') {
            ezhp_loadFlatpickr(ezhp_flatpickrLocale, () => {
                if (window.flatpickr) {
                    try {
                        const ezhp_fpConfig = {
                            enableTime: true,
                            dateFormat: 'Y-m-d\\TH:i',
                            time_24hr: true,
                            allowInput: true
                        };

                        // Set locale if available
                        if (ezhp_flatpickrLocale !== 'default' && window.flatpickr.l10ns && window.flatpickr.l10ns[ezhp_flatpickrLocale]) {
                            ezhp_fpConfig.locale = ezhp_flatpickrLocale;
                        }

                        // Initialize flatpickr on both datetime inputs
                        if (ezhp_datetimeInputA) {
                            window.flatpickr(ezhp_datetimeInputA, ezhp_fpConfig);
                        }
                        if (ezhp_datetimeInputB) {
                            window.flatpickr(ezhp_datetimeInputB, ezhp_fpConfig);
                        }
                    } catch (e) {
                        // Flatpickr init failed, native input still works
                    }
                }
            });
        }

        ezhp_button.addEventListener('click', async () => {

            const ezhp_nameA = ezhp_nameInputA ? ezhp_nameInputA.value.trim() : '';
            const ezhp_locationA = ezhp_locationInputA.value.trim();
            let ezhp_datetimeA = ezhp_datetimeInputA.value;

            const ezhp_nameB = ezhp_nameInputB ? ezhp_nameInputB.value.trim() : '';
            const ezhp_locationB = ezhp_locationInputB.value.trim();
            let ezhp_datetimeB = ezhp_datetimeInputB.value;

            // Validate inputs
            if (!ezhp_locationA || !ezhp_datetimeA || !ezhp_locationB || !ezhp_datetimeB) {
                ezhp_resultContainer.innerHTML = '<div class="ezhp-error">' + ezhp_t(ezhp_lang, 'pleaseEnterDetails') + '</div>';
                return;
            }

            // Normalize datetime format (handle both native and flatpickr formats)
            if (ezhp_datetimeA.includes(' ')) {
                ezhp_datetimeA = ezhp_datetimeA.replace(' ', 'T');
            }
            if (ezhp_datetimeB.includes(' ')) {
                ezhp_datetimeB = ezhp_datetimeB.replace(' ', 'T');
            }

            ezhp_resultContainer.innerHTML = '<div class="ezhp-loading">' + ezhp_t(ezhp_lang, 'loading') + '</div>';

            // Build style settings from data attributes
            const ezhp_isTransparent = ezhp_block.dataset.transparentBackground === 'true';
            const ezhp_styleSettings = {
                backgroundColor: ezhp_isTransparent ? 'transparent' : ezhp_block.dataset.backgroundColor,
                transparentBackground: ezhp_isTransparent,
                circleColor: ezhp_block.dataset.circleColor,
                pointsColor: ezhp_block.dataset.pointsColor,
                signsColor: ezhp_block.dataset.signsColor,
                cuspsColor: ezhp_block.dataset.cuspsColor,
                lineColor: ezhp_block.dataset.lineColor,
                axisFontColor: ezhp_block.dataset.axisFontColor,
                legendFontColor: ezhp_block.dataset.legendFontColor,
                legendBorderColor: ezhp_block.dataset.legendBorderColor,
                colorAries: ezhp_block.dataset.colorAries,
                colorTaurus: ezhp_block.dataset.colorTaurus,
                colorGemini: ezhp_block.dataset.colorGemini,
                colorCancer: ezhp_block.dataset.colorCancer,
                colorLeo: ezhp_block.dataset.colorLeo,
                colorVirgo: ezhp_block.dataset.colorVirgo,
                colorLibra: ezhp_block.dataset.colorLibra,
                colorScorpio: ezhp_block.dataset.colorScorpio,
                colorSagittarius: ezhp_block.dataset.colorSagittarius,
                colorCapricorn: ezhp_block.dataset.colorCapricorn,
                colorAquarius: ezhp_block.dataset.colorAquarius,
                colorPisces: ezhp_block.dataset.colorPisces,
                aspectColors: {
                    Conjunction: ezhp_block.dataset.aspectColorConjunction,
                    Opposition: ezhp_block.dataset.aspectColorOpposition,
                    Trine: ezhp_block.dataset.aspectColorTrine,
                    Square: ezhp_block.dataset.aspectColorSquare,
                    Sextile: ezhp_block.dataset.aspectColorSextile,
                    Quincunx: ezhp_block.dataset.aspectColorQuincunx
                },
                aspectConfigs: {
                    Conjunction: {
                        color: ezhp_block.dataset.aspectColorConjunction,
                        orbit: parseFloat(ezhp_block.dataset.aspectOrbitConjunction)
                    },
                    Opposition: {
                        color: ezhp_block.dataset.aspectColorOpposition,
                        orbit: parseFloat(ezhp_block.dataset.aspectOrbitOpposition)
                    },
                    Trine: {
                        color: ezhp_block.dataset.aspectColorTrine,
                        orbit: parseFloat(ezhp_block.dataset.aspectOrbitTrine)
                    },
                    Square: {
                        color: ezhp_block.dataset.aspectColorSquare,
                        orbit: parseFloat(ezhp_block.dataset.aspectOrbitSquare)
                    },
                    Sextile: {
                        color: ezhp_block.dataset.aspectColorSextile,
                        orbit: parseFloat(ezhp_block.dataset.aspectOrbitSextile)
                    },
                    Quincunx: {
                        color: ezhp_block.dataset.aspectColorQuincunx,
                        orbit: parseFloat(ezhp_block.dataset.aspectOrbitQuincunx)
                    }
                },
                symbolScale: parseFloat(ezhp_block.dataset.symbolScale),
                pointsTextSize: parseInt(ezhp_block.dataset.pointsTextSize, 10),
                pointsStroke: parseFloat(ezhp_block.dataset.pointsStroke),
                signsStroke: parseFloat(ezhp_block.dataset.signsStroke),
                circleStrong: parseFloat(ezhp_block.dataset.circleStroke),
                cuspsStroke: parseFloat(ezhp_block.dataset.cuspsStroke),
                axisStroke: parseFloat(ezhp_block.dataset.axisStroke),
                margin: parseInt(ezhp_block.dataset.margin, 10),
                padding: parseInt(ezhp_block.dataset.padding, 10),
                collisionRadius: parseInt(ezhp_block.dataset.collisionRadius, 10),
                indoorCircleRadiusRatio: parseFloat(ezhp_block.dataset.indoorCircleRadiusRatio),
                innerCircleRadiusRatio: parseFloat(ezhp_block.dataset.innerCircleRadiusRatio),
                rulerRadius: parseFloat(ezhp_block.dataset.rulerRadius),
                shiftInDegrees: parseInt(ezhp_block.dataset.shiftInDegrees, 10),
                strokeOnly: ezhp_block.dataset.strokeOnly === 'true',
                addClickArea: ezhp_block.dataset.addClickArea === 'true',
                showDignitiesText: ezhp_block.dataset.showDignitiesText === 'true',
                debug: ezhp_block.dataset.debug === 'true'
            };

            try {
                const ezhp_houseSystemValue = ezhp_block.querySelector('.ezhp-house-system-select')?.value || ezhp_block.dataset.houseSystem || 'placidus';

                const ezhp_payload = {
                    locationA: ezhp_locationA,
                    birthDateTimeLocalA: ezhp_datetimeA,
                    nameA: ezhp_nameA || ezhp_t(ezhp_lang, 'personA'),
                    locationB: ezhp_locationB,
                    birthDateTimeLocalB: ezhp_datetimeB,
                    nameB: ezhp_nameB || ezhp_t(ezhp_lang, 'personB'),
                    language: ezhp_lang,
                    houseSystem: ezhp_houseSystemValue,
                    styleSettings: ezhp_styleSettings
                };

                const ezhp_response = await fetch('/wp-json/ezhp/v1/synastry-chart?_=' + Date.now(), {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Cache-Control': 'no-cache'
                    },
                    body: JSON.stringify(ezhp_payload)
                });

                const ezhp_data = await ezhp_response.json();

                if (ezhp_data.image) {
                    ezhp_resultContainer.innerHTML = '<img src="' + ezhp_data.image + '" alt="Synastry Chart" class="ezhp-chart-image">';
                } else if (ezhp_data.error) {
                    ezhp_resultContainer.innerHTML = '<div class="ezhp-error">' + ezhp_data.error + '</div>';
                } else {
                    ezhp_resultContainer.innerHTML = '<div class="ezhp-error">' + ezhp_t(ezhp_lang, 'errorLoading') + '</div>';
                }

            } catch (ezhp_err) {
                ezhp_resultContainer.innerHTML = '<div class="ezhp-error">' + ezhp_t(ezhp_lang, 'errorLoading') + '</div>';
            }
        });
    });
}