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

window.addEventListener('load', ezhp_bindZodiacProfileBlocks);

function ezhp_bindZodiacProfileBlocks() {

    var blocks = document.querySelectorAll('.ez-zodiac-profile-block');
    if (!blocks.length) return;

    blocks.forEach(function (block) {

        var lang = block.dataset.ezhpLang || 'en';

        // ⭐ Translate form UI
        var formLabel = block.querySelector('.ezhp-form label');
        if (formLabel) formLabel.textContent = ezhp_t(lang, 'enterBirthdate');

        var btn = block.querySelector('.ezhp-fetch-button');
        if (btn) btn.textContent = ezhp_t(lang, 'getZodiacSignProfile');

        var dateInput       = block.querySelector('.ezhp-date-input');
        var button          = block.querySelector('.ezhp-fetch-button');
        var resultContainer = block.querySelector('.ez-zodiac-profile-result');

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

        button.addEventListener('click', function () {

            var birthdate = dateInput.value;

            if (!birthdate) {
                resultContainer.innerHTML = '<div class="ezhp-validation-msg">' + ezhp_t(lang, 'pleaseEnterBirthdate') + '</div>';
                return;
            }

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

            var url = '/wp-json/ezhp/v1/zodiac-profile?birthdate=' +
                      encodeURIComponent(birthdate) +
                      '&language=' + encodeURIComponent(lang);

            fetch(url)
                .then(function (res) { return res.json(); })
                .then(function (data) {
                    if (data.error || !data.profileData) {
                        resultContainer.innerHTML = '<div class="ezhp-error">' + (data.error || ezhp_t(lang, 'noProfileFound')) + '</div>';
                        return;
                    }
                    resultContainer.innerHTML = '<div class="ez-zodiac-profile" dir="' + (ezhp_isRTL(lang) ? 'rtl' : 'ltr') + '">' +
                        ezhp_buildZodiacProfile(data.profileData, block, lang) + '</div>';
                })
                .catch(function (err) {
                    console.error('Zodiac Profile error:', err);
                    resultContainer.innerHTML = '<div class="ezhp-error">' + ezhp_t(lang, 'errorLoading') + '</div>';
                });
        });
    });
}

/* =============================================================================
   MAIN BUILD FUNCTION
============================================================================= */
function ezhp_buildZodiacProfile(profile, block, lang) {

    var sign = profile.sign || '';
    var hideHeading = block.dataset.hideHeading === '1';
    var t = function (key) { return ezhp_t(lang, key); };
    var html = '';

    /* ─── HERO ─── */
    var heroParts = [];
    if (!hideHeading) {
        heroParts.push('<h2 class="ez-profile-title">' + ezhp_esc(profile.unicode_symbol || '') + ' ' + ezhp_esc(sign) + '</h2>');
    }
    heroParts.push('<p class="ez-profile-subtitle">' + ezhp_esc(profile.symbol || '') + ' \u2014 ' + ezhp_esc(profile.date_range || '') + '</p>');

    var vitals = [];
    if (profile.element)       vitals.push('<span class="ez-vital"><strong>' + ezhp_esc(t('element'))      + ':</strong> ' + ezhp_esc(profile.element)       + '</span>');
    if (profile.modality)      vitals.push('<span class="ez-vital"><strong>' + ezhp_esc(t('modality'))     + ':</strong> ' + ezhp_esc(profile.modality)      + '</span>');
    if (profile.ruling_planet) vitals.push('<span class="ez-vital"><strong>' + ezhp_esc(t('rulingPlanet')) + ':</strong> ' + ezhp_esc(profile.ruling_planet) + '</span>');
    if (profile.ruling_house)  vitals.push('<span class="ez-vital"><strong>' + ezhp_esc(t('house'))        + ':</strong> ' + ezhp_esc(profile.ruling_house)  + '</span>');
    if (profile.season)        vitals.push('<span class="ez-vital"><strong>' + ezhp_esc(t('season'))       + ':</strong> ' + ezhp_esc(profile.season)        + '</span>');
    heroParts.push('<div class="ez-profile-vitals">' + vitals.join('') + '</div>');

    html += '<section class="ez-zodiac-profile-section ez-hero"><div class="ez-hero-content"><div class="ez-hero-text">' +
            heroParts.join('') + '</div></div></section>';

    /* ─── PERSONALITY ─── */
    var p = profile.personality;
    if (p) {
        html += '<section class="ez-profile-section" id="personality"><div class="ez-profile-content">';
        html += '<h2>' + ezhp_esc(t('personality')) + '</h2>';
        if (p.overview) html += '<p>' + ezhp_esc(p.overview) + '</p>';
        if (p.core_motivation) html += '<p class="ez-core-motivation"><strong>' + ezhp_esc(t('coreMotivation')) + ':</strong> ' + ezhp_esc(p.core_motivation) + '</p>';

        html += '<div class="ez-traits-grid">';
        if (p.strengths && p.strengths.length) {
            html += '<div class="ez-trait-card ez-strengths"><h4>' + ezhp_esc(t('strengths')) + '</h4><ul>';
            p.strengths.forEach(function (s) { html += '<li>' + ezhp_esc(s) + '</li>'; });
            html += '</ul></div>';
        }
        if (p.challenges && p.challenges.length) {
            html += '<div class="ez-trait-card ez-challenges"><h4>' + ezhp_esc(t('challenges')) + '</h4><ul>';
            p.challenges.forEach(function (c) { html += '<li>' + ezhp_esc(c) + '</li>'; });
            html += '</ul></div>';
        }
        html += '</div>';

        if (p.communication_style) html += '<div class="ez-style-detail"><strong>' + ezhp_esc(t('communicationStyle')) + ':</strong> ' + ezhp_esc(p.communication_style) + '</div>';
        if (p.conflict_style)      html += '<div class="ez-style-detail"><strong>' + ezhp_esc(t('conflictStyle'))      + ':</strong> ' + ezhp_esc(p.conflict_style)      + '</div>';
        if (p.love_language)       html += '<div class="ez-style-detail"><strong>' + ezhp_esc(t('loveLanguage'))       + ':</strong> ' + ezhp_esc(p.love_language)       + '</div>';

        html += '</div></section>';
    }

    html += '<div data-cta-slot="after-personality"></div>';

    /* ─── DECANS ─── */
    var hasDecans = profile.decan_1 || profile.decan_2 || profile.decan_3;
    if (hasDecans) {
        html += '<section class="ez-profile-section" id="decans"><div class="ez-profile-content">';
        html += '<h2>' + ezhp_esc(t('decans')) + '</h2><div class="ez-decan-cards">';
        for (var i = 1; i <= 3; i++) {
            var d = profile['decan_' + i];
            if (d) {
                html += '<div class="ez-decan-card">';
                html += '<h4>' + ezhp_esc(t('decan')) + ' ' + i + '</h4>';
                if (d.date_range) html += '<p class="ez-decan-dates">' + ezhp_esc(d.date_range) + '</p>';
                if (d.sub_ruler)  html += '<p class="ez-decan-ruler"><strong>' + ezhp_esc(t('subRuler')) + ':</strong> ' + ezhp_esc(d.sub_ruler) + '</p>';
                if (d.traits)     html += '<p class="ez-decan-traits">' + ezhp_esc(d.traits) + '</p>';
                html += '</div>';
            }
        }
        html += '</div></div></section>';
    }

    /* ─── COMPATIBILITY ─── */
    var compat = profile.compatibility;
    if (compat) {
        html += '<section class="ez-profile-section" id="compatibility"><div class="ez-profile-content">';
        html += '<h2>' + ezhp_esc(t('compatibility')) + '</h2>';

        if (compat.most_compatible && compat.most_compatible.length) {
            html += '<div class="ez-compat-group"><h4 class="ez-compat-heading ez-compat-good">' + ezhp_esc(t('mostCompatible')) + '</h4><div class="ez-compat-cards">';
            compat.most_compatible.forEach(function (m) {
                html += '<div class="ez-compat-card ez-compat-positive"><strong>' + ezhp_esc(m.sign || '') + '</strong><p>' + ezhp_esc(m.reason || '') + '</p></div>';
            });
            html += '</div></div>';
        }

        if (compat.challenging_matches && compat.challenging_matches.length) {
            html += '<div class="ez-compat-group"><h4 class="ez-compat-heading ez-compat-challenge">' + ezhp_esc(t('challengingMatches')) + '</h4><div class="ez-compat-cards">';
            compat.challenging_matches.forEach(function (m) {
                html += '<div class="ez-compat-card ez-compat-challenging"><strong>' + ezhp_esc(m.sign || '') + '</strong><p>' + ezhp_esc(m.reason || '') + '</p></div>';
            });
            html += '</div></div>';
        }

        if (compat.opposite_sign) {
            html += '<div class="ez-opposite-sign"><strong>' + ezhp_esc(t('oppositeSign')) + ': ' + ezhp_esc(compat.opposite_sign) + '</strong>';
            if (compat.opposite_sign_dynamic) html += '<p>' + ezhp_esc(compat.opposite_sign_dynamic) + '</p>';
            html += '</div>';
        }

        html += '</div></section>';
    }

    html += '<div data-cta-slot="after-compatibility"></div>';

    /* ─── CAREER ─── */
    var career = profile.career;
    if (career) {
        html += '<section class="ez-profile-section" id="career"><div class="ez-profile-content">';
        html += '<h2>' + ezhp_esc(t('career')) + '</h2>';
        if (career.strengths_at_work) html += '<p>' + ezhp_esc(career.strengths_at_work) + '</p>';
        if (career.work_style) html += '<div class="ez-style-detail"><strong>' + ezhp_esc(t('workStyle')) + ':</strong> ' + ezhp_esc(career.work_style) + '</div>';
        if (career.ideal_fields && career.ideal_fields.length) {
            html += '<div class="ez-ideal-fields"><h4>' + ezhp_esc(t('idealFields')) + '</h4><ul>';
            career.ideal_fields.forEach(function (f) { html += '<li>' + ezhp_esc(f) + '</li>'; });
            html += '</ul></div>';
        }
        html += '</div></section>';
    }

    html += '<div data-cta-slot="after-career"></div>';

    /* ─── CORRESPONDENCES ─── */
    var cor = profile.correspondences;
    if (cor) {
        html += '<section class="ez-profile-section" id="correspondences"><div class="ez-profile-content">';
        html += '<h2>' + ezhp_esc(t('correspondences')) + '</h2><div class="ez-corresp-grid">';

        var items = [];
        if (cor.birthstone)       items.push([t('birthstone'),       cor.birthstone]);
        if (cor.additional_stones && cor.additional_stones.length) items.push([t('additionalStones'), cor.additional_stones.join(', ')]);
        if (cor.birth_flower)     items.push([t('birthFlower'),      cor.birth_flower]);
        if (cor.color)            items.push([t('color'),            cor.color]);
        if (cor.secondary_colors && cor.secondary_colors.length)   items.push([t('secondaryColors'),  cor.secondary_colors.join(', ')]);
        if (cor.lucky_numbers && cor.lucky_numbers.length)         items.push([t('luckyNumbers'),     cor.lucky_numbers.join(', ')]);
        if (cor.lucky_day)        items.push([t('luckyDay'),         cor.lucky_day]);
        if (cor.metal)            items.push([t('metal'),            cor.metal]);
        if (cor.herbs_and_plants && cor.herbs_and_plants.length)   items.push([t('herbsAndPlants'),   cor.herbs_and_plants.join(', ')]);
        if (cor.body_part_ruled)  items.push([t('bodyPartRuled'),    cor.body_part_ruled]);

        items.forEach(function (pair) {
            html += '<div class="ez-corresp-item"><span class="ez-corresp-label">' + ezhp_esc(pair[0]) + '</span><span class="ez-corresp-value">' + ezhp_esc(pair[1]) + '</span></div>';
        });
        html += '</div>';

        if (cor.tarot_card) {
            html += '<div class="ez-tarot-card"><h4>' + ezhp_esc(t('tarotCard')) + ': ' + ezhp_esc(cor.tarot_card) + '</h4>';
            if (cor.tarot_card_meaning) html += '<p>' + ezhp_esc(cor.tarot_card_meaning) + '</p>';
            html += '</div>';
        }

        html += '</div></section>';
    }

    /* ─── FAMOUS PEOPLE ─── */
    var famous = profile.famous_people;
    if (famous && famous.length) {
        var famousHeading = t('famousPeople').replace('{sign}', ezhp_esc(sign));
        html += '<section class="ez-profile-section" id="famous-people"><div class="ez-profile-content">';
        html += '<h2>' + famousHeading + '</h2><div class="ez-famous-cards">';
        famous.forEach(function (fp) {
            html += '<div class="ez-famous-card">';
            html += '<strong>' + ezhp_esc(fp.name || '') + '</strong>';
            if (fp.birth_date) html += '<span class="ez-famous-date">' + ezhp_esc(fp.birth_date) + '</span>';
            if (fp.known_for)  html += '<p>' + ezhp_esc(fp.known_for) + '</p>';
            html += '</div>';
        });
        html += '</div></div></section>';
    }

    /* ─── CTA INJECTION ─── */
    var ctaPlacement = block.dataset.ctaPlacement || 'none';
    if (ctaPlacement !== 'none') {
        var ctaHtml = ezhp_buildProfileCta(block);
        if (ctaHtml) {
            var parser  = new DOMParser();
            var tempDoc = parser.parseFromString('<div>' + html + '</div>', 'text/html');
            var slot    = tempDoc.querySelector('[data-cta-slot="' + ctaPlacement + '"]');
            if (slot) {
                slot.outerHTML = ctaHtml;
                html = tempDoc.body.firstElementChild.innerHTML;
            }
        }
    }

    // Remove unused CTA slots
    html = html.replace(/<div data-cta-slot="[^"]*"><\/div>/g, '');

    /* ─── HERO IMAGE INJECTION ─── */
    html = ezhp_injectProfileHeroImage(html, block);

    return html;
}

/* =============================================================================
   HELPER: Escape HTML
============================================================================= */
function ezhp_esc(str) {
    if (!str) return '';
    var div = document.createElement('div');
    div.textContent = String(str);
    return div.innerHTML;
}

/* =============================================================================
   HELPER: Build CTA HTML from data attributes
============================================================================= */
function ezhp_buildProfileCta(block) {
    var headline   = block.dataset.ctaHeadline || '';
    var headingLvl = block.dataset.ctaHeadingLevel || 'h3';
    var text       = block.dataset.ctaText || '';
    var btnText    = block.dataset.ctaButtonText || '';
    var btnUrl     = block.dataset.ctaButtonUrl || '';
    var imgUrl     = block.dataset.ctaImageUrl || '';
    var imgAlt     = block.dataset.ctaImageAlt || '';
    var imgClick   = block.dataset.ctaImageClickable === '1';
    var imgMaxW    = block.dataset.ctaImageMaxWidth || '100%';
    var bgColor    = block.dataset.ctaBgColor || '';
    var bgTransp   = block.dataset.ctaBgTransparent === '1';
    var btnColor   = block.dataset.ctaButtonColor || '';

    if (!headline && !text && !btnText) return '';

    var style = '';
    var cls = 'ez-profile-cta';
    if (bgTransp) {
        style = 'background:transparent;box-shadow:none;border:none;';
        cls += ' ez-profile-cta-transparent';
    } else if (bgColor) {
        style = 'background:' + bgColor + ';';
    }

    var ctaHtml = '<div class="' + cls + '" style="' + style + '">';
    if (headline) ctaHtml += '<' + headingLvl + ' class="ez-profile-cta-headline">' + ezhp_esc(headline) + '</' + headingLvl + '>';
    if (imgUrl) {
        var imgTag = '<img src="' + ezhp_esc(imgUrl) + '" alt="' + ezhp_esc(imgAlt) + '" class="ez-profile-cta-image" style="max-width:' + ezhp_esc(imgMaxW) + ';">';
        ctaHtml += (imgClick && btnUrl) ? '<a href="' + ezhp_esc(btnUrl) + '" class="ez-profile-cta-image-link">' + imgTag + '</a>' : imgTag;
    }
    if (text) ctaHtml += '<p class="ez-profile-cta-text">' + ezhp_esc(text) + '</p>';
    if (btnText && btnUrl) {
        var btnStyle = btnColor ? 'background:' + btnColor + ';' : '';
        ctaHtml += '<a href="' + ezhp_esc(btnUrl) + '" class="ez-profile-cta-button" style="' + btnStyle + '">' + ezhp_esc(btnText) + '</a>';
    }
    ctaHtml += '</div>';
    return ctaHtml;
}

/* =============================================================================
   HELPER: Inject hero image into the hero section
============================================================================= */
function ezhp_injectProfileHeroImage(html, block) {
    var mode    = block.dataset.heroMode || 'inline';
    var heroUrl = block.dataset.heroUrl || '';

    if (!heroUrl) return html;

    var heroAlt  = block.dataset.heroAlt || '';
    var dirIsRtl = block.dir === 'rtl';

    if (mode === 'inline') {
        var wrap     = block.dataset.heroWrap || 'none';
        var maxWidth = block.dataset.heroMaxWidth || '40%';
        var floatCSS;
        if (wrap === 'left') {
            floatCSS = dirIsRtl ? 'float:right;margin:0 0 1rem 1rem;' : 'float:left;margin:0 1rem 1rem 0;';
        } else if (wrap === 'right') {
            floatCSS = dirIsRtl ? 'float:left;margin:0 1rem 1rem 0;' : 'float:right;margin:0 0 1rem 1rem;';
        } else {
            floatCSS = 'display:block;margin:0 auto 1rem auto;';
        }
        var inlineImg =
            '<div class="ez-profile-inline-image" style="max-width:' + maxWidth + ';position:relative;' + floatCSS + '">' +
            '<img src="' + heroUrl + '" alt="' + heroAlt + '" style="width:100%;height:auto;border-radius:8px;display:block;">' +
            '</div>';
        html = html.replace('<div class="ez-hero-text">', '<div class="ez-hero-text">' + inlineImg);

    } else if (mode === 'background') {
        var align = block.dataset.heroAlign || 'center';
        html = html.replace(
            '<section class="ez-zodiac-profile-section ez-hero">',
            '<section class="ez-zodiac-profile-section 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;">'
        );
        var opacity = parseFloat(block.dataset.heroOpacity || 50) / 100;
        var color = (block.dataset.heroColor === 'white') ? '255,255,255' : '0,0,0';
        var overlay = '<div class="ez-profile-overlay" style="position:absolute;inset:0;background-color:rgba(' + color + ',' + opacity + ');pointer-events:none;border-radius:0;"></div>';
        html = html.replace('<div class="ez-hero-content">', overlay + '<div class="ez-hero-content">');
    }

    return html;
}