import { EZHP_UI, EZHP_ZODIAC, isRtlLanguage } from './i18n';
window.addEventListener('load', ezhp_bindCompatibilityBlocks);

function ezhp_bindCompatibilityBlocks() {

    const ezhp_blocks = document.querySelectorAll('.ezhp-compatibility-block');

    ezhp_blocks.forEach(ezhp_block => {

        const ezhp_yourSignSelect = ezhp_block.querySelector('.ezhp-your-sign');
        const ezhp_theirSignSelect = ezhp_block.querySelector('.ezhp-their-sign');
        const ezhp_button = ezhp_block.querySelector('.ezhp-fetch-button');
        const ezhp_result = ezhp_block.querySelector('.ezhp-compatibility-result');

        // Determine language FIRST (must come before any translation!)
        const currentLang = ezhp_block.dataset.ezhpLang || 'en';

        // Apply RTL direction if needed
        if (isRtlLanguage(currentLang)) {
            ezhp_block.setAttribute('dir', 'rtl');
        } else {
            ezhp_block.setAttribute('dir', 'ltr');
        }

        // Apply translated UI labels
        const ezhp_labelYour = ezhp_block.querySelector('.ezhp-label-your');
        if (ezhp_labelYour) {
            ezhp_labelYour.textContent = EZHP_UI[currentLang].yourSign;
        }

        const ezhp_labelTheir = ezhp_block.querySelector('.ezhp-label-their');
        if (ezhp_labelTheir) {
            ezhp_labelTheir.textContent = EZHP_UI[currentLang].theirSign;
        }

        const ezhp_buttonCompat = ezhp_block.querySelector('.ezhp-button-compat');
        if (ezhp_buttonCompat) {
            ezhp_buttonCompat.textContent = EZHP_UI[currentLang].button;
        }

        // Apply translated dropdown labels
        ezhp_yourSignSelect.querySelectorAll('option').forEach(opt => {
            const value = opt.value;
            if (value && EZHP_ZODIAC[currentLang] && EZHP_ZODIAC[currentLang][value]) {
                opt.textContent = EZHP_ZODIAC[currentLang][value];
            }
        });

        ezhp_theirSignSelect.querySelectorAll('option').forEach(opt => {
            const value = opt.value;
            if (value && EZHP_ZODIAC[currentLang] && EZHP_ZODIAC[currentLang][value]) {
                opt.textContent = EZHP_ZODIAC[currentLang][value];
            }
        });

        // STOP HERE if anything missing
        if (!ezhp_yourSignSelect || !ezhp_theirSignSelect || !ezhp_button || !ezhp_result) {
            return;
        }





        if (!ezhp_yourSignSelect || !ezhp_theirSignSelect || !ezhp_button || !ezhp_result) {
            return;
        }

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

            const ezhp_yourSign = ezhp_yourSignSelect.value;
            const ezhp_theirSign = ezhp_theirSignSelect.value;
            const ezhp_lang = ezhp_block.dataset.ezhpLang || 'en';

            if (!ezhp_yourSign || !ezhp_theirSign) {
                ezhp_result.innerHTML = `<div>${EZHP_UI[ezhp_lang].selectBoth}</div>`;
                return;
            }

            ezhp_result.innerHTML = `
    <div class="ezhp-progress-container">
        <div class="ezhp-progress-bar"></div>
    </div>
    <div>${EZHP_UI[ezhp_lang].loading}</div>
`;

            try {
                const ezhp_url = `/wp-json/ezhp/v1/zodiac-compatibility?yourSign=${encodeURIComponent(ezhp_yourSign)}&theirSign=${encodeURIComponent(ezhp_theirSign)}&language=${encodeURIComponent(ezhp_lang)}`;

                const ezhp_res = await fetch(ezhp_url);
                const ezhp_data = await ezhp_res.json();

                if (!ezhp_data.html) {
                    ezhp_result.innerHTML = `<div>${EZHP_UI[ezhp_lang].noResult}</div>`;
                    return;
                }

                let ezhp_html = ezhp_data.html;

                /* ---------------------------------------------------------
                   INLINE HERO IMAGE SUPPORT
                --------------------------------------------------------- */
                const ezhp_heroUrl = ezhp_block.dataset.heroUrl || '';
                const ezhp_heroAlt = ezhp_block.dataset.heroAlt || '';
                const ezhp_wrap = ezhp_block.dataset.heroWrap || 'none';
                const ezhp_maxWidth = ezhp_block.dataset.heroMaxWidth || '40%';

                if (ezhp_heroUrl) {

                    const ezhp_parser = new DOMParser();
                    const ezhp_doc = ezhp_parser.parseFromString(ezhp_html, 'text/html');

                    const ezhp_firstH2 = ezhp_doc.querySelector('h2');

                    if (ezhp_firstH2) {

                        // Build wrapper WITHOUT float in inline styles (theme-safe)
                        const ezhp_floatClass =
                            ezhp_wrap === 'left' ? 'ez-wrap-left' :
                                ezhp_wrap === 'right' ? 'ez-wrap-right' :
                                    '';

                        const ezhp_inlineImg = `
    <img 
    src="${ezhp_heroUrl}" 
    alt="${ezhp_heroAlt}" 
    class="ez-inline-hero-img ${ezhp_floatClass}"
    style="border-radius:8px;max-width:${ezhp_maxWidth};height:auto;"
>
`;



                        if (ezhp_wrap === 'none') {
                            // Insert image ABOVE the H2
                            ezhp_firstH2.insertAdjacentHTML('beforebegin', ezhp_inlineImg);
                        } else {
                            // Insert image INSIDE the H2 to allow wrapping
                            ezhp_firstH2.insertAdjacentHTML('afterbegin', ezhp_inlineImg);
                        }

                        ezhp_html = ezhp_doc.body.innerHTML;
                    }
                }

                /* ---------------------------------------------------------
                   OUTPUT FINAL RESULT
                --------------------------------------------------------- */
                ezhp_result.innerHTML = ezhp_html;

            } catch (ezhp_err) {
                ezhp_result.innerHTML = '<div>Error loading compatibility.</div>';
            }
        });
    });
}