/* SideraHR — interazioni del sito (nessuna dipendenza esterna) */
(function () {
  'use strict';
  const $ = (s, r) => (r || document).querySelector(s);
  const $$ = (s, r) => Array.from((r || document).querySelectorAll(s));
  const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  /* ---------- Header: ombra allo scroll + menu mobile ---------- */
  const header = $('.site-header');
  const onScroll = () => header && header.classList.toggle('is-scrolled', window.scrollY > 8);
  onScroll();
  window.addEventListener('scroll', onScroll, { passive: true });

  const burger = $('.nav-burger');
  const collapse = $('.nav-collapse');
  if (burger && collapse) {
    burger.addEventListener('click', () => {
      const open = collapse.classList.toggle('is-open');
      burger.setAttribute('aria-expanded', String(open));
      document.body.style.overflow = open ? 'hidden' : '';
    });
    window.matchMedia('(min-width: 1024px)').addEventListener('change', (e) => {
      if (e.matches) { collapse.classList.remove('is-open'); burger.setAttribute('aria-expanded', 'false'); document.body.style.overflow = ''; }
    });
  }
  // sottomenu (click/tap; su desktop funziona anche in hover via CSS)
  $$('.nav-toggle-sub').forEach((btn) => {
    btn.addEventListener('click', (e) => {
      e.preventDefault();
      const li = btn.parentElement;
      const open = li.classList.toggle('open');
      btn.setAttribute('aria-expanded', String(open));
    });
  });
  document.addEventListener('click', (e) => {
    if (!e.target.closest('.nav-menu')) $$('.nav-menu li.open').forEach((li) => { li.classList.remove('open'); const b = $('.nav-toggle-sub', li); b && b.setAttribute('aria-expanded', 'false'); });
  });
  document.addEventListener('keydown', (e) => { if (e.key === 'Escape') $$('.nav-menu li.open').forEach((li) => li.classList.remove('open')); });

  /* ---------- Dialog delle funzionalità ---------- */
  $$('[data-dialog]').forEach((btn) => {
    btn.addEventListener('click', () => {
      const dlg = document.getElementById(btn.getAttribute('data-dialog'));
      if (!dlg) return;
      if (typeof dlg.showModal === 'function') dlg.showModal(); else dlg.setAttribute('open', '');
      $('.modal-body', dlg) && ($('.modal-body', dlg).scrollTop = 0);
    });
  });
  $$('dialog').forEach((dlg) => {
    $$('[data-close]', dlg).forEach((b) => b.addEventListener('click', () => dlg.close()));
    // chiudi cliccando sullo sfondo
    dlg.addEventListener('click', (e) => {
      const r = dlg.getBoundingClientRect();
      const inside = e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom;
      if (!inside && e.target === dlg) dlg.close();
    });
  });
  // apertura da hash (#f-nome) per link diretti alle funzionalità
  const openFromHash = () => {
    const id = location.hash.replace('#', '');
    if (!id) return;
    const dlg = document.getElementById(id);
    if (dlg && dlg.tagName === 'DIALOG' && !dlg.open) dlg.showModal();
  };
  window.addEventListener('hashchange', openFromHash);
  openFromHash();

  /* ---------- Galleria: frecce + lightbox ---------- */
  const lb = $('#lightbox');
  const lbImg = lb && $('img', lb);
  const lbCap = lb && $('figcaption', lb);
  let lbItems = [], lbIndex = 0;
  const showLb = (i) => {
    lbIndex = (i + lbItems.length) % lbItems.length;
    const it = lbItems[lbIndex];
    lbImg.src = it.src; lbImg.alt = it.alt || '';
    lbCap.textContent = it.cap || '';
  };
  $$('.gallery').forEach((g) => {
    const track = $('.gallery-track', g);
    const figs = $$('figure', track);
    $$('button', track).forEach((b, i) => b.addEventListener('click', () => {
      if (!lb) return;
      lbItems = figs.map((f) => { const im = $('img', f); return { src: im.getAttribute('data-full') || im.src, alt: im.alt, cap: ($('figcaption', f) || {}).textContent }; });
      showLb(i);
      lb.showModal();
    }));
    const step = () => (figs[0] ? figs[0].getBoundingClientRect().width + 16 : 400);
    $$('.gallery-nav [data-dir]', g).forEach((b) => b.addEventListener('click', () => {
      track.scrollBy({ left: step() * Number(b.getAttribute('data-dir')), behavior: reduced ? 'auto' : 'smooth' });
    }));
  });
  if (lb) {
    $('[data-lb-prev]', lb).addEventListener('click', () => showLb(lbIndex - 1));
    $('[data-lb-next]', lb).addEventListener('click', () => showLb(lbIndex + 1));
    lb.addEventListener('keydown', (e) => { if (e.key === 'ArrowLeft') showLb(lbIndex - 1); if (e.key === 'ArrowRight') showLb(lbIndex + 1); });
  }

  /* ---------- Contatori animati ---------- */
  const fmt = new Intl.NumberFormat('it-IT');
  const animate = (el) => {
    const target = Number(el.getAttribute('data-count'));
    const suffix = el.getAttribute('data-suffix') || '';
    const dur = 1400, t0 = performance.now();
    const tick = (t) => {
      const p = Math.min(1, (t - t0) / dur), e = 1 - Math.pow(1 - p, 3);
      el.firstChild.textContent = fmt.format(Math.round(target * e));
      if (p < 1) requestAnimationFrame(tick); else el.firstChild.textContent = fmt.format(target);
    };
    if (reduced) { el.firstChild.textContent = fmt.format(target); return; }
    requestAnimationFrame(tick);
    void suffix;
  };

  /* ---------- Reveal on scroll ---------- */
  if ('IntersectionObserver' in window) {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((en) => {
        if (!en.isIntersecting) return;
        en.target.classList.add('in');
        if (en.target.hasAttribute('data-count')) animate(en.target);
        io.unobserve(en.target);
      });
    }, { threshold: 0.15, rootMargin: '0px 0px -40px 0px' });
    $$('.reveal, [data-count]').forEach((el) => io.observe(el));
  } else {
    $$('.reveal').forEach((el) => el.classList.add('in'));
    $$('[data-count]').forEach(animate);
  }

  /* ---------- Torna su ---------- */
  const toTop = $('.to-top');
  if (toTop) {
    const tt = () => toTop.classList.toggle('show', window.scrollY > 600);
    tt(); window.addEventListener('scroll', tt, { passive: true });
    toTop.addEventListener('click', () => window.scrollTo({ top: 0, behavior: reduced ? 'auto' : 'smooth' }));
  }

  /* ---------- Grafici (Chart.js, se presente) ---------- */
  const charts = $$('canvas[data-chart]');
  if (charts.length && window.Chart) {
    const colors = ['#2d81b1', '#ec6725', '#c8412b', '#e9b44c'];
    charts.forEach((cv, i) => {
      let cfg; try { cfg = JSON.parse(cv.getAttribute('data-chart')); } catch (e) { return; }
      const c = colors[i % colors.length];
      new window.Chart(cv, {
        type: 'line',
        data: { labels: cfg.labels, datasets: [{ data: cfg.data, borderColor: c, backgroundColor: c + '22', fill: true, tension: .35, pointRadius: 3, pointHoverRadius: 6, pointBackgroundColor: c, borderWidth: 2.5 }] },
        options: {
          responsive: true, maintainAspectRatio: false, animation: reduced ? false : { duration: 900 },
          plugins: { legend: { display: false }, tooltip: { callbacks: { label: (ctx) => ' ' + fmt.format(ctx.parsed.y) + (cfg.unit ? ' ' + cfg.unit : '') } } },
          scales: { y: { beginAtZero: true, ticks: { callback: (v) => fmt.format(v) }, grid: { color: 'rgba(0,0,0,.06)' } }, x: { grid: { display: false } } }
        }
      });
    });
  }

  /* ---------- Form contatti: compone la mail (nessun backend) ---------- */
  const form = $('#contact-form');
  if (form) {
    form.addEventListener('submit', (e) => {
      e.preventDefault();
      const d = new FormData(form);
      const subject = 'Richiesta ' + (d.get('motivo') || 'informazioni') + ' — ' + (d.get('azienda') || d.get('nome') || '');
      const body = [
        'Nome: ' + d.get('nome'), 'Azienda: ' + (d.get('azienda') || '-'), 'Email: ' + d.get('email'), 'Telefono: ' + (d.get('telefono') || '-'),
        'Dipendenti: ' + (d.get('dipendenti') || '-'), 'Interesse: ' + (d.get('motivo') || '-'), '', d.get('messaggio') || ''
      ].join('\n');
      location.href = 'mailto:info@siderahr.it?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body);
      const ok = $('#form-ok'); if (ok) ok.hidden = false;
    });
  }

  /* ---------- Anno corrente nel footer ---------- */
  $$('[data-year]').forEach((el) => { el.textContent = new Date().getFullYear(); });
})();
