(function () {
  let currentSlide = 0;
  let autoTimer = null;
  const SLIDE_DURATION_MS = 15000; // 15 segundos por slide

  function showSlide(slides, indicators, index) {
    slides.forEach(s => s.classList.remove('active', 'exit'));
    indicators.forEach(i => i.classList.remove('active'));

    if (slides[currentSlide]) {
      slides[currentSlide].classList.add('exit');
    }

    currentSlide = index;
    slides[currentSlide].classList.add('active');
    indicators[currentSlide].classList.add('active');
  }

  function scheduleNext(slides, indicators) {
    clearTimeout(autoTimer);
    autoTimer = setTimeout(() => {
      const next = (currentSlide + 1) % slides.length;
      showSlide(slides, indicators, next);
      scheduleNext(slides, indicators);
    }, SLIDE_DURATION_MS);
  }

  function init() {
    const slides = Array.from(document.querySelectorAll('.sponsor-slide'));
    const indicators = Array.from(document.querySelectorAll('.indicator'));
    if (!slides.length || slides.length !== indicators.length) return;

    // Inicializa no primeiro slide e agenda avanço
    showSlide(slides, indicators, 0);
    scheduleNext(slides, indicators);

    // Clique nos indicadores reinicia o timer
    indicators.forEach((el, idx) => {
      el.addEventListener('click', () => {
        clearTimeout(autoTimer);
        showSlide(slides, indicators, idx);
        scheduleNext(slides, indicators);
      });
    });

    // Pausar ao passar o mouse
    const slider = document.querySelector('.sponsor-slider');
    if (slider) {
      slider.addEventListener('mouseenter', () => clearTimeout(autoTimer));
      slider.addEventListener('mouseleave', () => scheduleNext(slides, indicators));
    }

    // Pausar quando a aba não está visível (evita "acelerar" ao voltar)
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) {
        clearTimeout(autoTimer);
      } else {
        scheduleNext(slides, indicators);
      }
    });
  }

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

  // -------------------------
  // Efeito esteira participantes (com Livewire reativo)
  // Mostra 5 itens e dispara avanço quando o 5º muda
  // -------------------------
  let animating = false;
  let lastSignature = null;
  let lastRound = null;
  let awaitingAdvance = false;

  // Calcula passo vertical (altura do item + gap) de forma robusta
  function getStepHeight(viewport) {
    const first = viewport && viewport.children[0];
    if (!first) return 0;
    const rect1 = first.getBoundingClientRect();
    const second = viewport.children[1];
    let gap = 0;
    if (second) {
      const rect2 = second.getBoundingClientRect();
      gap = Math.max(0, rect2.top - rect1.bottom);
    } else {
      const cs = getComputedStyle(first);
      gap = parseFloat(cs.marginBottom || '0') || 0;
    }
    return rect1.height + gap;
  }

  // Ajusta altura da janela visível e overflow conforme disponibilidade
  function syncViewportHeight() {
    const viewport = document.getElementById('participantsList');
    if (!viewport) return;
    const section = viewport.closest('.participants-section');
    if (!section) return;
    const items = Array.from(viewport.children);
    const totalCount = items.length;
    const visibleCount = Math.min(5, totalCount);
    const step = getStepHeight(viewport);
    if (step > 0 && visibleCount > 0) {
      section.style.height = `${step * visibleCount}px`;
      // Sempre permitir rolagem quando existem mais de 5 itens
      section.style.overflowY = totalCount > 5 ? 'auto' : 'hidden';
    } else {
      // Fallback: permite rolagem para inspeção se não conseguirmos calcular o passo
      section.style.height = '';
      section.style.overflowY = 'auto';
    }
  }

  function attachLivewireHooks() {
    const hook = (window.Livewire && window.Livewire.hook) || (window.livewire && window.livewire.hook);
    if (hook) {
      hook('message.processed', checkTrigger);
    }
  }

  function sendAdvanceViewport(signature) {
    try {
      if (window.Livewire) {
        if (typeof window.Livewire.dispatch === 'function') {
          awaitingAdvance = true;
          window.Livewire.dispatch('advance-viewport', { signature });
          return;
        }
        if (typeof window.Livewire.emit === 'function') {
          awaitingAdvance = true;
          window.Livewire.emit('advance-viewport', signature);
          return;
        }
      }
    } catch (e) {
      // silencioso
    }
  }

  function animateAndAdvance(signature) {
    const viewport = document.getElementById('participantsList');
    if (!viewport || animating) return;
    const firstItem = viewport.children[0];
    if (!firstItem) return;
    const step = getStepHeight(viewport);
    const section = viewport.closest('.participants-section');
    const totalCount = viewport.children.length;
    const visibleCount = Math.min(5, totalCount);
    if (section && step > 0 && visibleCount > 0) {
      section.style.height = `${step * visibleCount}px`;
      // Sempre permitir rolagem quando existem mais de 5 itens
      section.style.overflowY = totalCount > 5 ? 'auto' : 'hidden';
    } else if (section) {
      section.style.height = '';
      section.style.overflowY = 'auto';
    }
    animating = true;

    viewport.style.transition = 'transform 500ms ease';
    viewport.style.transform = `translateY(-${step}px)`;

    const onEnd = () => {
      viewport.removeEventListener('transitionend', onEnd);
      viewport.style.transition = '';
      viewport.style.transform = '';
      animating = false;
      // Dispara avanço no Livewire (servidor cuida do wrap)
      sendAdvanceViewport(signature);
    };

    viewport.addEventListener('transitionend', onEnd);
  }

  function checkTrigger() {
    const viewport = document.getElementById('participantsList');
    if (!viewport) return;
    // Mantém altura e overflow da janela visível em sincronia
    syncViewportHeight();
    if (awaitingAdvance) {
      // Após avanço, espere render do servidor e sincronize assinatura
      const serverSig = viewport.getAttribute('data-last-signature') || null;
      if (serverSig !== null) {
        lastSignature = serverSig;
      }
      awaitingAdvance = false;
      return;
    }
    // Reinicia assinatura quando a rodada muda
    const round = viewport.getAttribute('data-round') || null;
    if (round !== lastRound) {
      lastRound = round;
      lastSignature = null;
    }
    const items = Array.from(viewport.children);
    if (items.length < 5) {
      // Com menos de 5 itens, apenas sincroniza altura e não anima
      syncViewportHeight();
      return;
    }
    const last = items[items.length - 1];
    const raw = last.getAttribute('data-value');
    const valueStr = (raw === null || raw === '') ? 'null' : String(raw);
    const id = last.getAttribute('data-id') || '';
    const signature = `${id}:${valueStr}`;
    // Dispara somente quando o último item deixa de ser 'null' (de  null -> 0/1)
    if (signature !== lastSignature && valueStr !== 'null') {
      lastSignature = signature;
      animateAndAdvance(signature);
    }
  }

  // Observa mudanças no DOM visível como fallback para disparar checagem
  const observerInit = () => {
    const viewport = document.getElementById('participantsList');
    if (!viewport) return;
    const mo = new MutationObserver(() => {
      if (!animating) checkTrigger();
    });
    // Observa alterações de filhos e atributos (especialmente data-value e data-round)
    mo.observe(viewport, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ['data-value', 'data-round']
    });
  };

  // Hooka com Livewire quando carregar
  document.addEventListener('livewire:load', () => {
    attachLivewireHooks();
    checkTrigger();
  });
  // Tenta anexar hooks imediatamente (caso Livewire já esteja pronto)
  attachLivewireHooks();
  // Inicia fallback de observer
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', observerInit);
  } else {
    observerInit();
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', checkTrigger);
  } else {
    checkTrigger();
  }
})();
