// source --> https://elanillounico.com/wp-content/plugins/eau-analytics/assets/js/eau-analytics.js?ver=1780356662 
(function () {
    'use strict';

    var config = window.eauAnalyticsConfig || {};
    var sent = Object.create(null);
    var startedForms = Object.create(null);
    var scrollDepths = [25, 50, 75, 90];
    var articleMilestones = Object.create(null);
    var lastScrollRun = 0;
    var storageKey = 'eauv6_cookie_consent';

    function analyticsAllowed() {
        if (config.disable_on_staging && config.entorno === 'staging') return false;
        try {
            var consent = JSON.parse(window.localStorage.getItem(storageKey) || 'null');
            return !consent || consent.analytics !== false;
        } catch (error) {
            return true;
        }
    }

    function snake(value) {
        return String(value || '')
            .toLowerCase()
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[^a-z0-9]+/g, '_')
            .replace(/^_+|_+$/g, '')
            .slice(0, 64);
    }

    function cleanText(value, max) {
        return String(value || '').replace(/\s+/g, ' ').trim().slice(0, max || 120);
    }

    function sanitizedUrl(value) {
        try {
            var url = new URL(value, window.location.href);
            return url.origin + url.pathname;
        } catch (error) {
            return '';
        }
    }

    function cleanParameters(parameters) {
        var clean = {};
        Object.keys(parameters || {}).forEach(function (key) {
            var value = parameters[key];
            var cleanKey = snake(key);
            if (!cleanKey || value === undefined || value === null || value === '') return;
            if (/email|password|pass|comment|message|content|ip_address|real_name/.test(cleanKey)) return;
            if (typeof value === 'boolean' || typeof value === 'number') {
                clean[cleanKey] = value;
                return;
            }
            clean[cleanKey] = cleanText(value, cleanKey.indexOf('url') !== -1 ? 240 : 120);
        });
        return clean;
    }

    function commonParameters() {
        return {
            page_path: window.location.pathname,
            page_title: cleanText(document.title, 120),
            post_id: Number(config.post_id || 0) || undefined,
            post_type: config.post_type || undefined,
            seccion: config.seccion || 'general',
            user_logged_in: !!config.is_user_logged_in,
            entorno: config.entorno || 'production',
            idioma: config.language || document.documentElement.lang || 'es',
            device_hint: window.matchMedia && window.matchMedia('(max-width: 767px)').matches ? 'mobile' : 'desktop'
        };
    }

    function track(eventName, parameters, options) {
        try {
            if (!analyticsAllowed()) return false;
            var normalizedName = snake(eventName);
            if (!normalizedName) return false;

            var payload = Object.assign({}, commonParameters(), cleanParameters(parameters || {}), {
                event: 'eau_event',
                eau_event_name: normalizedName
            });
            var dedupeKey = normalizedName + ':' + JSON.stringify(payload);
            var now = Date.now();
            if (sent[dedupeKey] && now - sent[dedupeKey] < ((options && options.dedupeMs) || 1200)) return false;
            sent[dedupeKey] = now;

            if (Array.isArray(window.dataLayer)) {
                window.dataLayer.push(payload);
            } else if (typeof window.gtag === 'function') {
                window.gtag('event', normalizedName, payload);
            } else {
                return false;
            }
            if (config.debug && window.console) console.debug('[EAU Analytics]', normalizedName, payload);
            return true;
        } catch (error) {
            if (config.debug && window.console) console.debug('[EAU Analytics] error', error);
            return false;
        }
    }

    window.eauTrack = track;

    function externalUrl(anchor) {
        if (!anchor || !anchor.href) return null;
        try {
            var url = new URL(anchor.href, window.location.href);
            if (!/^https?:$/.test(url.protocol) || url.hostname === window.location.hostname) return null;
            return url;
        } catch (error) {
            return null;
        }
    }

    function applyOutboundUtm(anchor) {
        var url = externalUrl(anchor);
        if (!url) return;
        if (!url.searchParams.has('utm_source')) url.searchParams.set('utm_source', config.utm_source || 'https://elanillounico.com');
        anchor.href = url.toString();
    }

    function linkText(anchor) {
        return cleanText(anchor.getAttribute('aria-label') || anchor.textContent || anchor.title || '', 80);
    }

    function shareNetwork(anchor) {
        var haystack = (anchor.href + ' ' + anchor.className).toLowerCase();
        var network = ['whatsapp', 'telegram', 'facebook', 'instagram', 'youtube', 'twitter', 'x.com'].find(function (candidate) {
            return haystack.indexOf(candidate) !== -1;
        }) || 'otros';
        return network === 'twitter' || network === 'x.com' ? 'x' : network;
    }

    function formInfo(form) {
        var id = form.id || form.getAttribute('name') || form.getAttribute('action') || 'formulario';
        return { form_id: snake(id), form_name: snake(form.getAttribute('name') || form.id || 'formulario'), form_context: config.seccion || 'general' };
    }

    function normalizeSearch(value) {
        return cleanText(value, 80).toLowerCase();
    }

    function routeEvents() {
        var path = window.location.pathname;
        var query = new URLSearchParams(window.location.search);
        var searchTerm = normalizeSearch(query.get('s') || query.get('q') || query.get('buscar') || '');
        var contestMessage = ['crl_msg', 'cpo_msg', 'cac_msg', 'cft_msg', 'cil_msg', 'ctc_msg'].map(function (key) {
            return query.get(key);
        }).find(Boolean);
        if (/^\/tolkienpedia\/?$/.test(path)) track('tolkienpedia_home_view');
        if (/^\/tolkienpedia\/[^/]+\/?$/.test(path)) track('tolkienpedia_category_view', { cpt: path.split('/')[2] });
        if (config.post_type && /^tolkienpedia_/.test(config.post_type)) track('tolkienpedia_entry_view', { cpt: config.post_type, entry_slug: path.split('/').filter(Boolean).pop() });
        if (/^\/mapas\/?/.test(path)) track('map_view', { map_age: document.body.getAttribute('data-map-age') || 'sin_especificar' });
        if (/^\/tolkienpedia\/arboles-genealogicos\/?/.test(path)) track('genealogy_view');
        if (/^\/tolkien\/citas\/?/.test(path)) track('quote_view');
        if (/^\/juegos\/[^/]+\/?/.test(path)) track('game_view', { game_slug: path.split('/')[2], game_name: path.split('/')[2] });
        if (/^\/foros\/ver-foro\/?/.test(path)) track('forum_view', { forum_slug: path.split('/').filter(Boolean).pop() });
        if (/^\/foros\/tema\/?/.test(path)) track('topic_view');
        if (/^\/usuarios\/[^/]+\/?$/.test(path)) track('profile_view');
        if (/^\/premios\/[^/]+\/?/.test(path)) track('contest_view', { contest_slug: path.split('/')[2] });
        if (searchTerm) {
            if (config.seccion === 'tolkienpedia') track('tolkienpedia_search', { search_term_normalized: searchTerm, result_count: config.result_count });
            if (config.seccion === 'mapas') track('map_search', { search_term_normalized: searchTerm, result_count: config.result_count });
            if (config.seccion === 'foros') track('forum_search', { search_term_normalized: searchTerm, result_count: config.result_count });
        }
        if (contestMessage === 'sent') {
            track('form_success', {form_context: 'contest'});
            track('contest_submit_complete', {contest_slug: path.split('/')[2] || 'premios'});
        } else if (contestMessage) {
            track('form_error', {form_context: 'contest', error_type: contestMessage});
        }
    }

    document.addEventListener('click', function (event) {
        var clicked = event.target;
        if (!clicked || typeof clicked.closest !== 'function') return;
        var target = clicked.closest('a, button');
        var marker = clicked.closest('[data-marker-id], .leaflet-marker-icon');
        var genealogyNode = clicked.closest('[data-genealogy-id], .genealogy-node');

        if (marker) track('map_marker_click', { post_id: marker.getAttribute('data-marker-id') || undefined });
        if (genealogyNode) track('genealogy_node_click', { clicked_character_id: genealogyNode.getAttribute('data-genealogy-id') || undefined });
        if (!target) return;
        if (target.matches('[data-menu-toggle], .menu-toggle, .hamburger')) track(target.getAttribute('aria-expanded') === 'true' ? 'menu_close' : 'menu_open', { menu_location: 'principal' });

        if (target.matches('a')) {
            applyOutboundUtm(target);
            var url = externalUrl(target);
            if (url) track('outbound_click', { link_domain: url.hostname, link_url_sanitized: sanitizedUrl(url.href), link_text: linkText(target) });
            if (target.closest('.entry-share-actions') || /share|whatsapp|telegram|facebook|instagram|youtube|twitter|x\.com/i.test(target.href + ' ' + target.className)) {
                track('share_click', { network: shareNetwork(target) });
            }
            if (target.closest('nav, .menu, #site-navigation')) track('menu_click', { menu_location: 'principal', link_text: linkText(target), link_url: sanitizedUrl(target.href) });
            if (/wp-login\.php/.test(target.href)) track('login_click');
            if (/registr|register/.test(target.href)) track('register_click');
            if (/lostpassword|recuperar|reset/.test(target.href)) track('password_reset_click');
            if (/\/bases\/?$/.test(new URL(target.href, window.location.href).pathname)) track('contest_rules_open', { contest_slug: config.seccion });
            if (/\/messages\/compose\/?/.test(new URL(target.href, window.location.href).pathname)) track('private_message_click');
            if (target.closest('[data-tolkienpedia-result], .search-results article')) track('tolkienpedia_result_click', { link_url: sanitizedUrl(target.href) });
        }

        if (target.matches('[data-game-start], [data-eau-new-game], .game-start, .start-game')) track('game_start', { game_name: config.seccion });
        if (target.matches('[data-rules-open], [data-eau-open-rules], .rules-open')) track('silmarils_rules_open');
        if (target.matches('[data-rules-close], [data-eau-close-rules], .rules-close')) track('silmarils_rules_close');
        if (target.matches('[data-map-age], [data-age]')) track('map_age_change', { new_age: target.getAttribute('data-map-age') || target.getAttribute('data-age') });
        if (target.matches('[data-map-zoom], .leaflet-control-zoom-in, .leaflet-control-zoom-out')) track('map_zoom', { direction: target.matches('.leaflet-control-zoom-out') ? 'out' : 'in' });
        if (target.matches('[data-map-locate], .leaflet-control-locate a')) track('map_locate');
        if (target.matches('[data-genealogy-path]')) track('genealogy_path_click');
        if (target.matches('[data-random], .random-entry, .random-quote, .eau-random')) track(config.seccion === 'citas' ? 'quote_random_click' : 'random_click', { section: config.seccion });
    }, true);

    document.addEventListener('focusin', function (event) {
        var form = event.target.closest('form');
        if (!form) return;
        var info = formInfo(form);
        if (!startedForms[info.form_id]) {
            startedForms[info.form_id] = true;
            track('form_start', info);
            if (/contest|premio|concurso/.test(info.form_context + ' ' + info.form_id)) track('contest_submit_start', info);
            if (/topic|new-post|bbp-topic/.test(info.form_id)) track('topic_create_start', info);
        }
    }, true);

    document.addEventListener('submit', function (event) {
        var form = event.target;
        if (!form || !form.matches('form')) return;
        var info = formInfo(form);
        track('form_submit', info);
        if (form.matches('[role="search"], .search-form') || form.querySelector('input[type="search"], input[name="s"]')) {
            var field = form.querySelector('input[type="search"], input[name="s"]');
            var searchContext = config.seccion === 'tolkienpedia' ? 'tolkienpedia' : config.seccion === 'foros' ? 'foro' : config.seccion === 'mapas' ? 'mapa' : 'global';
            var searchTerm = normalizeSearch(field && field.value);
            track('search_submit', { search_context: searchContext, search_term_normalized: searchTerm });
            if (searchContext === 'tolkienpedia') track('tolkienpedia_search', { search_term_normalized: searchTerm });
            if (searchContext === 'mapa') track('map_search', { search_term_normalized: searchTerm });
            if (searchContext === 'foro') track('forum_search', { search_term_normalized: searchTerm });
        }
        if (/reply|bbp-reply/.test(info.form_id)) track('reply_submit', info);
        if (/topic|new-post|bbp-topic/.test(info.form_id)) track('topic_create_submit', info);
    }, true);

    function readingEvents() {
        var article = document.querySelector('article .entry-content, article.entry-content, .entry-content');
        if (!article) return;
        var rect = article.getBoundingClientRect();
        var total = Math.max(article.offsetHeight, 1);
        var read = Math.min(total, Math.max(0, window.innerHeight - rect.top));
        var percent = Math.round(read / total * 100);
        if (!articleMilestones.start && percent > 0) {
            articleMilestones.start = true;
            track('article_read_start', { category: config.category });
        }
        if (!articleMilestones.half && percent >= 50) {
            articleMilestones.half = true;
            track('article_read_50', { category: config.category });
        }
        if (!articleMilestones.complete && percent >= 90) {
            articleMilestones.complete = true;
            track('article_read_complete', { category: config.category });
        }
    }

    function onScroll() {
        var now = Date.now();
        if (now - lastScrollRun < 250) return;
        lastScrollRun = now;
        var height = Math.max(document.documentElement.scrollHeight - window.innerHeight, 1);
        var depth = Math.round(window.scrollY / height * 100);
        scrollDepths.forEach(function (milestone) {
            if (depth >= milestone && !articleMilestones['scroll' + milestone]) {
                articleMilestones['scroll' + milestone] = true;
                track('scroll_depth', { depth: milestone });
            }
        });
        readingEvents();
    }

    document.querySelectorAll('a[href]').forEach(applyOutboundUtm);
    document.addEventListener('eau:track', function (event) {
        if (event.detail && event.detail.evento) track(event.detail.evento, event.detail.parametros || {});
    });
    window.addEventListener('scroll', onScroll, { passive: true });
    routeEvents();
    readingEvents();
}());