import { EZHP_NUMEROLOGY_I18N, isRtlLanguage } from './i18n';

window.addEventListener('load', ezhp_bindNumerologyBlocks);

function ezhp_bindNumerologyBlocks() {

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

    blocks.forEach(block => {

        const nameInput = block.querySelector('.ezhp-name-input');
        const dateInput = block.querySelector('.ezhp-date-input');
        const button = block.querySelector('.ezhp-fetch-button');
        const resultContainer = block.querySelector('.numerology-result');

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

        const lang = block.dataset.ezhpLang || 'en';
        const t = EZHP_NUMEROLOGY_I18N[lang] || EZHP_NUMEROLOGY_I18N.en;

        // RTL detection (check data attribute or derive from language)
        const isRtl = block.dataset.ezhpRtl === '1' || isRtlLanguage(lang);

        // Apply translations to UI elements
        const label = block.querySelector('label');
        if (label) label.textContent = t.enter_name_birthdate;

        nameInput.placeholder = t.full_name;
        button.textContent = t.get_report;

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

            const fullName = nameInput.value.trim();
            const birthDate = dateInput.value;

            if (!fullName || !birthDate) {
                resultContainer.innerHTML = `<div>${t.enter_required}</div>`;
                return;
            }

            resultContainer.innerHTML = `
    <div class="ezhp-progress-container">
        <div class="ezhp-progress-bar"></div>
    </div>
    <div>${t.loading}</div>
`;

            try {
                const url = `/wp-json/ezhp/v1/numerology?fullName=${encodeURIComponent(fullName)}&birthDate=${encodeURIComponent(birthDate)}&language=${encodeURIComponent(lang)}`;
                console.log("Numerology API URL:", url);

                const res = await fetch(url);
                console.log("Response:", res);

                const data = await res.json();
                console.log("JSON Returned:", data);

                if (!data.html) {
                    resultContainer.innerHTML = `<div>${t.no_report}</div>`;
                    return;
                }

                let html = data.html;

                if (!html) {
                    console.error("HTML IS EMPTY — this is the cause!");
                    resultContainer.innerHTML = `<div>${t.error_loading}</div>`;
                    return;
                }

                // Parse returned HTML
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');

                let section =
                    doc.querySelector('section.numerology-report') ||
                    doc.querySelector('.numerology-report') ||
                    doc.querySelector('section');

                if (!section) {
                    section = document.createElement('section');
                    section.className = 'numerology-report';
                    section.innerHTML = html;
                }

                const bodyHtml = section.innerHTML;

                // HERO TITLE
                const heroTitle = `
    <h2 class="numerology-title">
        ${t.report_for} ${fullName} (${birthDate})
    </h2>
`;


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

                let heroPieces = [];
                if (!hideHeading) heroPieces.push(heroTitle);

                /*
                    BUILD HERO WRAPPER
                */
                const mode = 'inline';
                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 HERO MODE */
                if (mode === 'inline' && heroUrl) {

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

                    // Flip float directions for RTL
                    let floatCSS;
                    if (wrap === 'left') {
                        floatCSS = isRtl
                            ? 'float:right;margin:0 0 1rem 1rem;'
                            : 'float:left;margin:0 1rem 1rem 0;';
                    } else if (wrap === 'right') {
                        floatCSS = isRtl
                            ? 'float:left;margin:0 1rem 1rem 0;'
                            : 'float:right;margin:0 0 1rem 1rem;';
                    } else {
                        floatCSS = '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 HERO 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 loader = resultContainer.querySelector('.ezhp-progress-container');
                if (loader) loader.remove();

                resultContainer.innerHTML = `
                    ${heroHTML}
                    ${bodyHtml}
                `;

            } catch (err) {
                const loader = resultContainer.querySelector('.ezhp-progress-container');
                if (loader) loader.remove();

                resultContainer.innerHTML = `<div>${t.error_loading}</div>`;
            }

        });
    });
}