/* Dr. Luiz França — menu mobile + carrossel de tratamentos */

/* ---------------- menu mobile ---------------- */
(function () {
  const nav = document.querySelector('.nav');
  if (!nav) return;
  const toggle = nav.querySelector('.nav__toggle');
  if (!toggle) return;

  toggle.addEventListener('click', () => {
    const open = nav.dataset.open === 'true';
    nav.dataset.open = String(!open);
    toggle.setAttribute('aria-expanded', String(!open));
    toggle.setAttribute('aria-label', open ? 'Abrir menu' : 'Fechar menu');
  });

  // fecha ao navegar
  nav.querySelectorAll('.nav__list a').forEach((a) =>
    a.addEventListener('click', () => {
      nav.dataset.open = 'false';
      toggle.setAttribute('aria-expanded', 'false');
    })
  );
})();

/* ---------------- carrossel ---------------- */
(function () {
  const root = document.querySelector('[data-carousel]');
  if (!root) return;

  const slides = Array.from(root.querySelectorAll('.carousel__slide'));
  const dotsBox = root.querySelector('[data-dots]');
  const n = slides.length;
  if (!n) return;

  let index = Math.floor(n / 2); // o PSD abre com o card do meio ativo
  let timer = null;

  // dots
  const dots = slides.map((_, i) => {
    const b = document.createElement('button');
    b.type = 'button';
    b.setAttribute('aria-label', `Ir para o tratamento ${i + 1}`);
    b.addEventListener('click', () => {
      go(i);
      restart();
    });
    dotsBox.appendChild(b);
    return b;
  });

  function render() {
    slides.forEach((s, i) => {
      // distância circular até o slide ativo
      let d = i - index;
      if (d > n / 2) d -= n;
      if (d < -n / 2) d += n;

      const pos = d === 0 ? 'center' : d === -1 ? 'left' : d === 1 ? 'right' : 'hidden';
      s.dataset.pos = pos;
      s.setAttribute('aria-hidden', pos === 'hidden' ? 'true' : 'false');
    });
    dots.forEach((b, i) => b.setAttribute('aria-current', String(i === index)));
  }

  function go(i) {
    index = ((i % n) + n) % n;
    render();
  }

  // clicar num card lateral traz ele para o centro
  slides.forEach((s, i) =>
    s.addEventListener('click', (e) => {
      if (s.dataset.pos === 'center') return; // no centro, deixa o link agir
      e.preventDefault();
      go(i);
      restart();
    })
  );

  function restart() {
    clearInterval(timer);
    if (!window.matchMedia('(max-width: 900px)').matches) {
      timer = setInterval(() => go(index + 1), 6000);
    }
  }

  render();
  restart();

  root.addEventListener('mouseenter', () => clearInterval(timer));
  root.addEventListener('mouseleave', restart);
})();
