(function () {
    var DAY_NAMES = ['dom', 'lun', 'mar', 'mie', 'jue', 'vie', 'sab'];
    var MONTH_NAMES_LONG = [
        'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio',
        'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre',
    ];
    var MONTH_NAMES_SHORT = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sept', 'oct', 'nov', 'dic'];

    var CLOCK_ICON = '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true"><circle cx="8" cy="8" r="7" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M8 4v4l3 2" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>';
    var PIN_ICON = '<svg viewBox="0 0 12 16" width="10" height="14" aria-hidden="true"><path d="M6 15C2.5 11.5 1 8.9 1 6a5 5 0 1 1 10 0c0 2.9-1.5 5.5-5 9z" fill="none" stroke="currentColor" stroke-width="1.2"/><circle cx="6" cy="6" r="1.6" fill="currentColor"/></svg>';

    function pushDataLayerEvent(eventName, data) {
        try {
            window.dataLayer = window.dataLayer || [];
            var payload = { event: eventName };
            for (var key in data) {
                if (Object.prototype.hasOwnProperty.call(data, key)) {
                    payload[key] = data[key];
                }
            }
            window.dataLayer.push(payload);
        } catch (e) {
            // no-op: never break the widget because of analytics
        }
    }

    function formatTimeRange(isoString, durationLabel) {
        var date = new Date(isoString);
        var hours = ('0' + date.getHours()).slice(-2);
        var minutes = ('0' + date.getMinutes()).slice(-2);
        var start = hours + ':' + minutes;

        var end = null;
        if (durationLabel) {
            var hoursMatch = durationLabel.match(/(\d+)h/);
            var minutesMatch = durationLabel.match(/(\d+)\s*min/);
            var endDate = new Date(date.getTime());
            if (hoursMatch) {
                endDate.setHours(endDate.getHours() + parseInt(hoursMatch[1], 10));
            }
            if (minutesMatch) {
                endDate.setMinutes(endDate.getMinutes() + parseInt(minutesMatch[1], 10));
            }
            end = ('0' + endDate.getHours()).slice(-2) + ':' + ('0' + endDate.getMinutes()).slice(-2);
        }

        return end ? start + ' - ' + end : start;
    }

    function formatPrice(price) {
        return price.toFixed(2).replace('.', ',') + ' €';
    }

    function formatDateLong(isoString) {
        var date = new Date(isoString);
        var dayName = DAY_NAMES[date.getDay()];
        return dayName.charAt(0).toUpperCase() + dayName.slice(1) + ' ' + date.getDate() + ' de ' + MONTH_NAMES_LONG[date.getMonth()];
    }

    function renderMedia(event, className) {
        if (event.video) {
            var iframe = document.createElement('iframe');
            iframe.className = className;
            iframe.src = event.video;
            iframe.title = event.name;
            iframe.setAttribute('frameborder', '0');
            iframe.setAttribute('allowfullscreen', 'true');
            return iframe;
        }

        if (event.image) {
            var image = document.createElement('img');
            image.className = className;
            image.src = event.image;
            image.alt = event.name;
            return image;
        }

        return null;
    }

    function renderGridCard(event) {
        var card = document.createElement('div');
        card.className = 'vinofilos-event-card';

        var media = renderMedia(event, 'vinofilos-event-card__image');
        if (media) {
            card.appendChild(media);
        }

        var body = document.createElement('div');
        body.className = 'vinofilos-event-card__body';

        var title = document.createElement('h3');
        title.className = 'vinofilos-event-card__title';
        title.textContent = event.name;
        body.appendChild(title);

        var date = document.createElement('p');
        date.className = 'vinofilos-event-card__date';
        date.textContent = event.date
            ? formatDateLong(event.date) + ', ' + formatTimeRange(event.date, event.duration)
            : 'Duracion: ' + event.duration;
        body.appendChild(date);

        var location = document.createElement('p');
        location.className = 'vinofilos-event-card__location';
        location.textContent = event.location;
        body.appendChild(location);

        if (event.seats_available !== null && event.seats_available !== undefined) {
            var seats = document.createElement('p');
            seats.className = 'vinofilos-event-card__seats';
            seats.textContent = event.seats_available > 0
                ? event.seats_available + ' plazas disponibles'
                : 'Plazas agotadas';
            body.appendChild(seats);
        }

        var footer = document.createElement('div');
        footer.className = 'vinofilos-event-card__footer';

        var price = document.createElement('span');
        price.className = 'vinofilos-event-card__price';
        price.textContent = formatPrice(event.price);
        footer.appendChild(price);

        var button = document.createElement('a');
        button.className = 'vinofilos-event-card__button';
        button.href = event.url;
        button.target = '_blank';
        button.rel = 'noopener';
        button.textContent = 'Reservar plaza';
        button.addEventListener('click', function () {
            pushDataLayerEvent('vinofilos_events_click', {
                product_id: event.id_product,
                product_name: event.name,
                layout: 'grid',
            });
        });
        footer.appendChild(button);

        body.appendChild(footer);

        card.appendChild(body);
        return card;
    }

    function renderListItem(event) {
        var item = document.createElement('div');
        item.className = 'vinofilos-list-item';

        var badge = document.createElement('div');
        badge.className = 'vinofilos-list-item__badge';
        if (event.date) {
            var date = new Date(event.date);
            badge.innerHTML =
                '<span class="vinofilos-list-item__badge-month">' + MONTH_NAMES_SHORT[date.getMonth()] + '</span>'
                + '<span class="vinofilos-list-item__badge-day">' + date.getDate() + '</span>'
                + '<span class="vinofilos-list-item__badge-weekday">' + DAY_NAMES[date.getDay()] + '</span>';
        }
        item.appendChild(badge);

        var media = renderMedia(event, 'vinofilos-list-item__image');
        if (media) {
            item.appendChild(media);
        }

        var info = document.createElement('div');
        info.className = 'vinofilos-list-item__info';

        var title = document.createElement('div');
        title.className = 'vinofilos-list-item__title';
        title.textContent = event.name;
        info.appendChild(title);

        var timeOrDuration = event.date
            ? formatTimeRange(event.date, event.duration)
            : 'Duracion: ' + event.duration;

        var meta = document.createElement('div');
        meta.className = 'vinofilos-list-item__meta';
        meta.innerHTML =
            '<span class="vinofilos-list-item__meta-row">' + CLOCK_ICON + '<span>' + timeOrDuration + '</span></span>'
            + '<span class="vinofilos-list-item__meta-row">' + PIN_ICON + '<span>' + event.location + '</span></span>';
        info.appendChild(meta);

        if (event.seats_available !== null && event.seats_available !== undefined) {
            var seats = document.createElement('div');
            seats.className = 'vinofilos-list-item__seats';
            seats.textContent = event.seats_available > 0
                ? event.seats_available + ' plazas disponibles'
                : 'Plazas agotadas';
            info.appendChild(seats);
        }

        item.appendChild(info);

        var action = document.createElement('div');
        action.className = 'vinofilos-list-item__action';

        var price = document.createElement('span');
        price.className = 'vinofilos-list-item__price';
        price.textContent = formatPrice(event.price);
        action.appendChild(price);

        var button = document.createElement('a');
        button.className = 'vinofilos-list-item__button';
        button.href = event.url;
        button.target = '_blank';
        button.rel = 'noopener';
        button.textContent = 'Reservar';
        button.addEventListener('click', function () {
            pushDataLayerEvent('vinofilos_events_click', {
                product_id: event.id_product,
                product_name: event.name,
                layout: 'list',
            });
        });
        action.appendChild(button);

        item.appendChild(action);

        return item;
    }

    function renderGrid(container, events) {
        var grid = document.createElement('div');
        grid.className = 'vinofilos-events-grid';
        events.forEach(function (event) {
            grid.appendChild(renderGridCard(event));
        });
        container.appendChild(grid);
    }

    function renderList(container, events) {
        var wrapper = document.createElement('div');
        wrapper.className = 'vinofilos-events-list';

        var lastMonthKey = null;
        events.forEach(function (event) {
            var monthKey = 'sin-fecha';
            var headerText = 'Experiencias';

            if (event.date) {
                var date = new Date(event.date);
                monthKey = date.getFullYear() + '-' + date.getMonth();
                headerText = MONTH_NAMES_LONG[date.getMonth()] + ' de ' + date.getFullYear();
            }

            if (monthKey !== lastMonthKey) {
                var header = document.createElement('div');
                header.className = 'vinofilos-events-list__month-header';
                header.textContent = headerText;
                wrapper.appendChild(header);
                lastMonthKey = monthKey;
            }

            wrapper.appendChild(renderListItem(event));
        });

        container.appendChild(wrapper);
    }

    var CSS_URL = 'https://tienda.vinofilos.es/modules/vinofilosevents/views/css/vinofilos-events.css';

    function getShadowTarget(container, cssVersion) {
        var root = container.shadowRoot;
        if (!root) {
            root = container.attachShadow({ mode: 'open' });
            var link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = CSS_URL + (cssVersion ? '?v=' + cssVersion : '');
            root.appendChild(link);
            var content = document.createElement('div');
            content.className = 'vinofilos-events-content';
            root.appendChild(content);
        } else if (cssVersion) {
            var existingLink = root.querySelector('link[rel="stylesheet"]');
            var versionedHref = CSS_URL + '?v=' + cssVersion;
            if (existingLink && existingLink.href.indexOf(versionedHref) === -1) {
                existingLink.href = versionedHref;
            }
        }

        return root.querySelector('.vinofilos-events-content');
    }

    function renderEvents(container, events, layout, cssVersion, h1, h2) {
        var target = getShadowTarget(container, cssVersion);
        target.innerHTML = '';

        if (h1) {
            var titleEl = document.createElement('h2');
            titleEl.className = 'vinofilos-events-title';
            titleEl.textContent = h1;
            target.appendChild(titleEl);
        }

        if (h2) {
            var subtitleEl = document.createElement('p');
            subtitleEl.className = 'vinofilos-events-subtitle';
            subtitleEl.textContent = h2;
            target.appendChild(subtitleEl);
        }

        if (!events.length) {
            var empty = document.createElement('p');
            empty.textContent = 'No hay eventos programados por el momento.';
            target.appendChild(empty);
            return;
        }

        if (layout === 'list') {
            renderList(target, events);
        } else {
            renderGrid(target, events);
        }

        pushDataLayerEvent('vinofilos_events_view', {
            category_id: container.getAttribute('data-vinofilos-events'),
            events_count: events.length,
            layout: layout,
        });
    }

    function loadEvents(container) {
        var idCategory = container.getAttribute('data-vinofilos-events');
        var endpoint = 'https://tienda.vinofilos.es/index.php?fc=module&module=vinofilosevents&controller=calendar&cat=' + encodeURIComponent(idCategory);

        fetch(endpoint)
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {
                renderEvents(container, data.events || [], data.layout || 'grid', data.cssVersion, data.h1, data.h2);
            })
            .catch(function () {
                getShadowTarget(container).textContent = 'No se ha podido cargar el calendario de eventos.';
            });
    }

    document.addEventListener('DOMContentLoaded', function () {
        var containers = document.querySelectorAll('[data-vinofilos-events]');
        for (var i = 0; i < containers.length; i++) {
            loadEvents(containers[i]);
        }
    });
})();
