"use client";

import { useCallback, useEffect, useRef, useState, type TouchEvent } from "react";

/*
  O passo a passo de um carrossel de imagens: qual quadro está à vista, o
  avanço sozinho (que para quando o mouse está em cima, quando a aba está
  escondida e para quem pediu menos movimento) e o arrasto com o dedo. Só a
  lógica: cada template desenha o seu.
*/
export function useCarrossel(total: number, automatico: boolean, intervaloS: number) {
  const [indice, setIndice] = useState(0);
  const [parado, setParado] = useState(false);
  const toque = useRef<{ x: number; y: number } | null>(null);

  const atual = total > 0 ? ((indice % total) + total) % total : 0;

  const ir = useCallback((proximo: number) => setIndice(total > 0 ? ((proximo % total) + total) % total : 0), [total]);
  const anterior = useCallback(() => setIndice((i) => (total > 0 ? (i - 1 + total) % total : 0)), [total]);
  const seguinte = useCallback(() => setIndice((i) => (total > 0 ? (i + 1) % total : 0)), [total]);

  useEffect(() => {
    if (!automatico || total <= 1 || parado) return;
    if (typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
    const relogio = window.setInterval(() => {
      if (document.visibilityState === "hidden") return;
      setIndice((i) => (i + 1) % total);
    }, Math.max(3, intervaloS) * 1000);
    return () => window.clearInterval(relogio);
  }, [automatico, total, parado, intervaloS]);

  const eventos = {
    onMouseEnter: () => setParado(true),
    onMouseLeave: () => setParado(false),
    onTouchStart: (e: TouchEvent) => {
      const t = e.touches[0];
      toque.current = t ? { x: t.clientX, y: t.clientY } : null;
      setParado(true);
    },
    onTouchEnd: (e: TouchEvent) => {
      const inicio = toque.current;
      toque.current = null;
      setParado(false);
      const t = e.changedTouches[0];
      if (!inicio || !t) return;
      const dx = t.clientX - inicio.x;
      const dy = t.clientY - inicio.y;
      if (Math.abs(dx) < 40 || Math.abs(dx) < Math.abs(dy)) return;
      if (dx < 0) seguinte();
      else anterior();
    },
  };

  return { atual, ir, anterior, seguinte, eventos };
}
