const VIEWERS_MINIMO = 500; // Mínimo de viewers que podem ser exibidos
const VIEWERS_MAXIMO = 876; // Máximo de viewers que podem ser exibidos
const INTERVALO_ATUALIZACAO = 10; // 5 segundos
const CHANCE_INCREMENTO = 0.6; // 70% de chance de incrementar
const CHANCE_DECREMENTO = 0.4; // 30% de chance de decrementar
const VARIACAO_MAXIMA = 5; // Máximo de viewers que podem ser adicionados/removidos por vez
const DURACAO_ANIMACAO = 1000; // 1 segundo de duração da animação

const getCurrentViewers = () => {
  const savedViewers = localStorage.getItem("slimforme-viewers");
  return savedViewers ? parseInt(savedViewers) : VIEWERS_MINIMO;
};

const saveViewers = quantity =>
  localStorage.setItem("slimforme-viewers", quantity.toString());

const animateNumber = (element, start, end, duration) => {
  const startTime = performance.now();
  const updateNumber = currentTime => {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);

    // Função de easing para suavizar a animação
    const easeOutQuad = t => t * (2 - t);
    const current = Math.round(start + (end - start) * easeOutQuad(progress));

    element.textContent = current;

    if (progress < 1) requestAnimationFrame(updateNumber);
  };

  requestAnimationFrame(updateNumber);
};

const updateViewersElement = (quantity, withAnimation = true) => {
  const viewersElement = document.querySelector(".viewers__count");

  if (viewersElement) {
    const currentValue = parseInt(viewersElement.textContent) || VIEWERS_MINIMO;
    if (withAnimation)
      animateNumber(viewersElement, currentValue, quantity, DURACAO_ANIMACAO);
    else viewersElement.textContent = quantity;
  }
};

const generateVariation = () => {
  const variation = Math.floor(Math.random() * VARIACAO_MAXIMA) + 1;
  const random = Math.random();
  return random < CHANCE_INCREMENTO ? variation : -variation;
};

const updateViewers = () => {
  let currentViewers = getCurrentViewers();
  const viewersElement = document.querySelector(".viewers__count");
  const displayedViewers = viewersElement
    ? parseInt(viewersElement.textContent)
    : currentViewers;

  let variation;
  do variation = generateVariation();
  while (currentViewers + variation === displayedViewers);

  currentViewers = Math.min(
    VIEWERS_MAXIMO,
    Math.max(VIEWERS_MINIMO, currentViewers + variation)
  );

  saveViewers(currentViewers);
  updateViewersElement(currentViewers);
};

// Inicializa os viewers
updateViewersElement(getCurrentViewers(), false);

// Atualiza os viewers a cada X segundos
setInterval(updateViewers, INTERVALO_ATUALIZACAO * 1000);
