/**
 * IMZ Artist Card — artista-card.js  v3
 * Toggle de redes sociais + popups dos feats + slider de músicas
 * Correcções: suporte a teclado, ARIA, debounce resize, passive listeners
 */
(function () {
    'use strict';

    /* =====================================================================
       SEGUIR ARTISTA (FOLLOW) — NOVO
       ===================================================================== */
    function initFollowButtons() {
        if (typeof imz_follow_data === 'undefined') return;
        document.querySelectorAll('.imz-artista-follow-btn').forEach(function (btn) {
            if (btn.dataset.bound === '1') return;
            btn.dataset.bound = '1';
            btn.addEventListener('click', function (e) {
                e.stopPropagation();
                if (btn.disabled) return;
                var artistaId = btn.getAttribute('data-artista-id');
                if (!artistaId) return;
                btn.disabled = true;

                var fd = new FormData();
                fd.append('action', 'imz_toggle_follow');
                fd.append('nonce', imz_follow_data.nonce);
                fd.append('artista_id', artistaId);

                fetch(imz_follow_data.ajax_url, { method: 'POST', body: fd, credentials: 'same-origin' })
                    .then(function (r) { return r.json(); })
                    .then(function (res) {
                        if (!res || !res.success) return;
                        var d = res.data;
                        btn.classList.toggle('following', d.following);
                        btn.setAttribute('aria-pressed', d.following ? 'true' : 'false');
                        var label = btn.querySelector('.imz-follow-label');
                        if (label) label.textContent = d.following ? 'A seguir' : 'Seguir';

                        var card = btn.closest('.imz-artista-card');
                        var counter = card ? card.querySelector('[data-follow-count]') : null;
                        if (counter) {
                            var numEl = counter.querySelector('[data-follow-num]');
                            if (numEl) numEl.textContent = d.count_display;
                            var wordEl = counter.querySelector('[data-follow-word]');
                            if (wordEl) wordEl.textContent = (d.count === 1) ? 'seguidor' : 'seguidores';
                        }
                        if (d.following) {
                            btn.classList.add('just-followed');
                            setTimeout(function () { btn.classList.remove('just-followed'); }, 600);
                        }
                    })
                    .catch(function () {})
                    .finally(function () { btn.disabled = false; });
            });
        });
    }

    /* =====================================================================
       TOGGLE REDES SOCIAIS
       ===================================================================== */

    function initArtistCards() {
        document.querySelectorAll('.imz-artista-toggle-btn').forEach(function (btn) {
            btn.addEventListener('click', function (e) {
                e.stopPropagation();
                var card = btn.closest('.imz-artista-card');
                if (!card) return;
                var redes = card.querySelector('.imz-artista-redes');
                if (!redes) return;
                var isOpen = !redes.hidden;
                closeAllRedes();
                closeAllFeatPopups();
                if (!isOpen) {
                    redes.hidden = false;
                    btn.classList.add('active');
                    btn.setAttribute('aria-expanded', 'true');
                    redes.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                } else {
                    btn.setAttribute('aria-expanded', 'false');
                }
            });
        });

        document.querySelectorAll('.imz-artista-nome').forEach(function (nome) {
            nome.addEventListener('click', function (e) {
                e.stopPropagation();
                var card = nome.closest('.imz-artista-card');
                if (!card) return;
                var btn = card.querySelector('.imz-artista-toggle-btn');
                if (btn) btn.click();
            });
        });

        document.querySelectorAll('.imz-artista-feat-pill').forEach(function (pill) {
            pill.addEventListener('click', function (e) {
                e.stopPropagation();
                var artistaId = pill.getAttribute('data-artista-id');
                var card = pill.closest('.imz-artista-card');
                if (!card || !artistaId) return;
                var popup = card.querySelector('#imz-feat-popup-' + artistaId);
                if (!popup) return;
                var isOpen = !popup.hidden;
                closeAllRedes();
                closeAllFeatPopups();
                if (!isOpen) {
                    popup.hidden = false;
                    pill.setAttribute('aria-expanded', 'true');
                    popup.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                }
            });
        });

        document.querySelectorAll('.imz-feat-popup-close').forEach(function (btn) {
            btn.addEventListener('click', function (e) {
                e.stopPropagation();
                closeAllFeatPopups();
            });
        });

        document.addEventListener('click', function (e) {
            if (!e.target.closest('.imz-artista-card')) {
                closeAllRedes();
                closeAllFeatPopups();
            }
        });

        // Fechar com Escape
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') {
                closeAllRedes();
                closeAllFeatPopups();
            }
        });
    }

    function closeAllRedes() {
        document.querySelectorAll('.imz-artista-redes').forEach(function (el) { el.hidden = true; });
        document.querySelectorAll('.imz-artista-toggle-btn').forEach(function (btn) {
            btn.classList.remove('active');
            btn.setAttribute('aria-expanded', 'false');
        });
    }

    function closeAllFeatPopups() {
        document.querySelectorAll('.imz-feat-redes-popup').forEach(function (el) { el.hidden = true; });
        document.querySelectorAll('.imz-artista-feat-pill').forEach(function (pill) {
            pill.setAttribute('aria-expanded', 'false');
        });
    }


    /* =====================================================================
       SLIDER DE MUSICAS (com teclado e ARIA)
       ===================================================================== */

    function initSliders() {
        document.querySelectorAll('.imz-slider-outer').forEach(function (outer) {
            var track   = outer.querySelector('.imz-slider-track');
            var slides  = outer.querySelectorAll('.imz-slide');
            var btnPrev = outer.querySelector('.imz-slider-prev');
            var btnNext = outer.querySelector('.imz-slider-next');
            var dots    = outer.querySelectorAll('.imz-slider-dot');

            if (!track || slides.length === 0) return;

            var current = 0;
            var total   = slides.length;

            // Configura ARIA
            track.setAttribute('role', 'list');
            track.setAttribute('aria-label', 'Músicas do artista');
            slides.forEach(function (slide, i) {
                slide.setAttribute('role', 'listitem');
                slide.setAttribute('aria-label', 'Música ' + (i + 1) + ' de ' + total);
            });

            function getPerView() {
                var w = outer.offsetWidth;
                if (w <= 360) return 2;
                if (w <= 560) return 3;
                if (w <= 820) return 4;
                return 5;
            }

            function goTo(idx) {
                var perView  = getPerView();
                var maxIndex = Math.max(0, total - perView);
                current = Math.max(0, Math.min(idx, maxIndex));

                var slideEl = slides[0];
                var slideW  = slideEl.offsetWidth;
                var gapStr  = window.getComputedStyle(track).columnGap
                           || window.getComputedStyle(track).gap
                           || '10px';
                var gap = parseFloat(gapStr) || 10;
                track.style.transform = 'translateX(-' + (current * (slideW + gap)) + 'px)';

                dots.forEach(function (d, i) {
                    var isActive = i === current;
                    d.classList.toggle('active', isActive);
                    d.setAttribute('aria-selected', isActive ? 'true' : 'false');
                });

                if (btnPrev) {
                    btnPrev.disabled = current === 0;
                    btnPrev.setAttribute('aria-disabled', current === 0 ? 'true' : 'false');
                }
                if (btnNext) {
                    btnNext.disabled = current >= maxIndex;
                    btnNext.setAttribute('aria-disabled', current >= maxIndex ? 'true' : 'false');
                }

                // Esconde setas se todos os slides cabem
                var hidden = total <= perView;
                if (btnPrev) btnPrev.style.display = hidden ? 'none' : '';
                if (btnNext) btnNext.style.display = hidden ? 'none' : '';

                // Anuncia slide atual para screen readers
                track.setAttribute('aria-live', 'polite');
            }

            if (btnPrev) btnPrev.addEventListener('click', function () { goTo(current - 1); });
            if (btnNext) btnNext.addEventListener('click', function () { goTo(current + 1); });

            dots.forEach(function (dot) {
                dot.setAttribute('role', 'tab');
                dot.addEventListener('click', function () {
                    goTo(parseInt(dot.getAttribute('data-index'), 10));
                });
            });

            // Navegação por teclado no slider
            outer.addEventListener('keydown', function (e) {
                if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
                    e.preventDefault();
                    goTo(current - 1);
                } else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
                    e.preventDefault();
                    goTo(current + 1);
                } else if (e.key === 'Home') {
                    e.preventDefault();
                    goTo(0);
                } else if (e.key === 'End') {
                    e.preventDefault();
                    goTo(total);
                }
            });

            // Swipe touch (passive)
            var startX = null;
            var startY = null;
            var isHorizontal = null;

            track.addEventListener('touchstart', function (e) {
                startX = e.touches[0].clientX;
                startY = e.touches[0].clientY;
                isHorizontal = null;
            }, { passive: true });

            track.addEventListener('touchmove', function (e) {
                if (startX === null || startY === null) return;
                // Detecta se o gesto é horizontal antes de decidir
                if (isHorizontal === null) {
                    var dx = Math.abs(e.touches[0].clientX - startX);
                    var dy = Math.abs(e.touches[0].clientY - startY);
                    isHorizontal = dx > dy;
                }
            }, { passive: true });

            track.addEventListener('touchend', function (e) {
                if (startX === null || !isHorizontal) {
                    startX = null;
                    startY = null;
                    isHorizontal = null;
                    return;
                }
                var dx = e.changedTouches[0].clientX - startX;
                if (Math.abs(dx) > 40) goTo(dx < 0 ? current + 1 : current - 1);
                startX = null;
                startY = null;
                isHorizontal = null;
            }, { passive: true });

            // Resize com debounce
            var resizeTimer;
            window.addEventListener('resize', function () {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(function () { goTo(current); }, 150);
            });

            goTo(0);
        });
    }


    /* =====================================================================
       INIT
       ===================================================================== */

    function init() {
        initArtistCards();
        initFollowButtons();
        initSliders();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
