/* ============================================================
   OTA PREMIUM STYLE — JS Enhancements (Cinematic Cards)
   Crea overlay sobre la imagen con título, precio y duración.
   ============================================================ */

(function otaPremiumCards() {
    'use strict';

    const CLOCK_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>`;

    // ── Traducciones ──
    const FROM_LABELS = {
        es: 'Desde',
        en: 'From',
        fr: 'À partir de',
        de: 'Ab',
        pt: 'A partir de'
    };

    function getSiteLang() {
        const lang = (document.documentElement.lang || 'es').toLowerCase().slice(0, 2);
        return FROM_LABELS[lang] ? lang : 'es';
    }

    function getServiceData(card) {
        const input = card.querySelector('input[id^="input-service-"]');
        if (!input) return null;
        const serviceId = parseInt(input.id.replace('input-service-', ''), 10);
        if (isNaN(serviceId) || typeof services === 'undefined') return null;
        return services.find(s => s.id === serviceId) || null;
    }

		function formatPrice(amount, currency) {
				if (typeof formatToLocaleMoney === 'function') {
						return formatToLocaleMoney(amount, currency);
				}
				return '$' + amount.toLocaleString();
		}

    function processCard(card) {
        if (card.dataset.otaProcessed) return;
        card.dataset.otaProcessed = 'true';

        const imageContainer = card.querySelector('.service-item__image');
        const durationEl = card.querySelector('.service-item__extra-duration');
        const titleEl = card.querySelector('.service-item__title');

        if (!imageContainer) return;

        // ── BADGE DE DURACIÓN (bottom-right, solo texto) ──
        if (durationEl) {
            const durationText = durationEl.querySelector('.service__duration-category');
            if (durationText) {
                const badge = document.createElement('div');
                badge.className = 'ota-duration-badge';

                const clonedSpan = durationText.cloneNode(true);
                clonedSpan.classList.remove('service__duration-category');
                badge.appendChild(clonedSpan);

                imageContainer.appendChild(badge);
            }
        }

        // ── OVERLAY CON TÍTULO + PRECIO ──
        setTimeout(() => {
            const svc = getServiceData(card);
            const lang = getSiteLang();

            // Crear overlay
            const overlay = document.createElement('div');
            overlay.className = 'ota-card-overlay';

            // Título
            if (titleEl) {
                const overlayTitle = document.createElement('div');
                overlayTitle.className = 'ota-card-overlay__title';
                overlayTitle.textContent = titleEl.textContent.trim();
                overlay.appendChild(overlayTitle);
            }

            // Precio
            if (svc) {
                const priceDiv = document.createElement('div');
                priceDiv.className = 'ota-card-overlay__price';

                const displayPrice = svc.priceType === 'deposit' && svc.remainingAmount > 0
                    ? svc.price + svc.remainingAmount
                    : svc.price;

                let priceHTML = `${FROM_LABELS[lang]} ${formatPrice(displayPrice, svc.currency)}`;

                // Si tiene moneda definida, agregar sufijo
                if (svc.currencyCode) {
                    priceHTML += ` ${svc.currencyCode}`;
                }

                // Precio tachado inline
                if (svc.crossedPrice && svc.crossedPrice > displayPrice) {
                    priceHTML += ` <span class="ota-overlay-crossed">${formatPrice(svc.crossedPrice, svc.currency)}</span>`;
                }

                priceDiv.innerHTML = priceHTML;
                overlay.appendChild(priceDiv);

                // ── BADGE DE DESCUENTO ──
                if (svc.crossedPrice && svc.crossedPrice > displayPrice) {
                    const pct = Math.round(((svc.crossedPrice - displayPrice) / svc.crossedPrice) * 100);
                    if (pct >= 1 && !imageContainer.querySelector('.ota-discount-badge')) {
                        const discountBadge = document.createElement('div');
                        discountBadge.className = 'ota-discount-badge';
                        discountBadge.textContent = `-${pct}%`;
                        imageContainer.appendChild(discountBadge);
                    }
                }
            }

            imageContainer.appendChild(overlay);
        }, 300);
    }

    function processAllCards() {
        document.querySelectorAll('.service-item:not([data-ota-processed])').forEach(processCard);
    }

    // ── INIT ──
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(processAllCards, 200);
        });
    } else {
        setTimeout(processAllCards, 200);
    }

    // Observer para cards dinámicas
    const observer = new MutationObserver((mutations) => {
        let hasNewCards = false;
        for (const mutation of mutations) {
            for (const node of mutation.addedNodes) {
                if (node.nodeType === 1) {
                    if (node.classList?.contains('service-item') || node.querySelector?.('.service-item')) {
                        hasNewCards = true;
                        break;
                    }
                }
            }
            if (hasNewCards) break;
        }
        if (hasNewCards) {
            setTimeout(processAllCards, 250);
        }
    });

    observer.observe(document.body, { childList: true, subtree: true });

})();