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

window.addEventListener('load', ezhp_bindChineseHoroscopeBlocks);

function ezhp_bindChineseHoroscopeBlocks() {

    const blocks = document.querySelectorAll('.chinese-horoscope-block');

    blocks.forEach(block => {

        // ⭐ FRONTEND TRANSLATION OF STATIC PHP UI
        const lang = block.dataset.ezhpLang || 'en';

        const label = block.querySelector('.ezhp-form label');
        if (label) {
            label.textContent = ezhp_t(lang, 'enterBirthdate');
        }

        const btn = block.querySelector('.ezhp-fetch-button');
        if (btn) {
            btn.textContent = ezhp_t(lang, 'getHoroscope');
        }

        const dateInput = block.querySelector('.ezhp-date-input');
        const button = block.querySelector('.ezhp-fetch-button');
        const resultContainer = block.querySelector('.chinese-horoscope-result');

        if (!dateInput || !button || !resultContainer) return;

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

            const birthdate = dateInput.value;
            const lang = block.dataset.ezhpLang || 'en';

            if (!birthdate) {
                resultContainer.innerHTML = `<div>${ezhp_t(lang, 'pleaseEnterBirthdate')}</div>`;
                return;
            }

            resultContainer.innerHTML = `<div>${ezhp_t(lang, 'loading')}</div>`;

            try {
                const url = `/wp-json/ezhp/v1/chinese-horoscope?birthDate=${encodeURIComponent(birthdate)}&language=${encodeURIComponent(lang)}`;
                const res = await fetch(url);
                const data = await res.json();

                if (!data.html) {
                    resultContainer.innerHTML = '<div>No horoscope found.</div>';
                    return;
                }

                // RAW API HTML
                let html = data.html;

                // ⭐ FIX: Remove accidental early </section> tags that break parsing
                html = html.replace(/<\/section>/gi, '');

                // ⭐ FIX: Ensure all horoscope content is wrapped safely
                html = `<section class="chinese-horoscope">${html}</section>`;

                // ⭐ Parse only our cleaned section
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const section = doc.querySelector('section.chinese-horoscope');

                if (!section) {
                    resultContainer.innerHTML = html;
                    return;
                }

                /* -----------------------------------------------
                   SPLIT INTO HERO PART + BODY PART (matches Daily)
                ------------------------------------------------- */

                const h2 = section.querySelector('h2.horoscope-title');
                const dateP = section.querySelector('p.horoscope-date');
                const introP = section.querySelector('p.horoscope-intro');

                const hideHeading = block.dataset.hideHeading === "1";

                const heroPieces = [];
                if (h2 && !hideHeading) heroPieces.push(h2.outerHTML);
                if (dateP) heroPieces.push(dateP.outerHTML);
                if (introP) heroPieces.push(introP.outerHTML);

                // Remove hero pieces from section
                if (h2) h2.remove();
                if (dateP) dateP.remove();
                if (introP) introP.remove();

                // ⭐ Body now contains FULL horoscope no matter how messy API HTML is
                const bodyHtml = section.innerHTML;

                /* -----------------------------------------------
                   BUILD HERO WRAPPER
                ------------------------------------------------- */

                const mode = block.dataset.heroMode || 'background';
                const heroUrl = block.dataset.heroUrl || '';
                const heroAlt = block.dataset.heroAlt || '';

                let heroHTML = `
                    <section class="ez-hero">
                        <div class="ez-hero-content">
                            <div class="ez-hero-text">
                                ${heroPieces.join("")}
                            </div>
                        </div>
                    </section>
                `;

                /* -----------------------------------------------
                   INLINE MODE
                ------------------------------------------------- */
                if (mode === 'inline' && heroUrl) {

                    const wrap = block.dataset.heroWrap || 'none';
                    const maxWidth = block.dataset.heroMaxWidth || '40%';

                    const floatCSS =
                        wrap === 'left' ? 'float:left;margin:0 1rem 1rem 0;' :
                        wrap === 'right' ? 'float:right;margin:0 0 1rem 1rem;' :
                        'display:block;margin:0 auto 1rem auto;';

                    const inlineImg = `
                        <div class="ez-daily-inline-image" style="max-width:${maxWidth};position:relative;">
                            <img src="${heroUrl}" alt="${heroAlt}" style="${floatCSS}border-radius:8px;max-width:100%;">
                        </div>
                    `;

                    heroHTML = heroHTML.replace(
                        '<div class="ez-hero-text">',
                        `<div class="ez-hero-text">${inlineImg}`
                    );
                }

                /* -----------------------------------------------
                   BACKGROUND MODE
                ------------------------------------------------- */
                if (mode === 'background' && heroUrl) {

                    const align = block.dataset.heroAlign || 'center';

                    heroHTML = heroHTML.replace(
                        '<section class="ez-hero">',
                        `<section class="ez-hero" style="background-image:url('${heroUrl}');background-size:cover;background-repeat:no-repeat;background-position:${align};min-height:300px;position:relative;display:flex;flex-direction:column;">`
                    );

                    const opacity = parseFloat(block.dataset.heroOpacity || 50) / 100;
                    const color = (block.dataset.heroColor === 'white') ? '255,255,255' : '0,0,0';

                    const overlay = `
                        <div class="ez-hero-overlay" style="position:absolute;inset:0;background-color:rgba(${color},${opacity});pointer-events:none;border-radius:0;"></div>
                    `;

                    heroHTML = heroHTML.replace(
                        '<div class="ez-hero-content">',
                        overlay + '<div class="ez-hero-content">'
                    );
                }

                /* -----------------------------------------------
                   FINAL OUTPUT
                ------------------------------------------------- */

                const dirAttr = ezhp_isRTL(lang) ? 'rtl' : 'ltr';

                resultContainer.innerHTML = `
                    <section class="chinese-horoscope" dir="${dirAttr}">
                        ${heroHTML}
                        ${bodyHtml}
                    </section>
                `;

            } catch (err) {
                resultContainer.innerHTML = '<div>Error loading horoscope.</div>';
            }
        });
    });
}