/* 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: invio a invia_contatto.asp (fetch, con fallback POST classico) ---------- */
  const form = $('#contact-form');
  if (form) {
    const msgBox = $('#form-msg');
    const show = (ok, text) => { if (!msgBox) return; msgBox.hidden = false; msgBox.textContent = text; msgBox.className = 'notice ' + (ok ? 'ok' : 'err'); msgBox.scrollIntoView({ block: 'nearest', behavior: reduced ? 'auto' : 'smooth' }); };
    const ts = form.querySelector('[name=ts]'); if (ts) ts.value = String(Date.now());
    // esito dopo un POST classico (senza JS): ?inviato=1 oppure ?errore=...
    const q = new URLSearchParams(location.search);
    if (q.get('inviato') === '1') { show(true, 'Grazie! Richiesta inviata: ti risponderemo al più presto.'); form.reset(); }
    else if (q.get('errore')) show(false, q.get('errore'));
    form.addEventListener('submit', async (e) => {
      if (!form.checkValidity()) { form.reportValidity(); e.preventDefault(); return; }
      if (!window.fetch) return;              // browser vecchio: POST normale
      e.preventDefault();
      const btn = form.querySelector('button[type=submit]'); btn.disabled = true;
      try {
        // le ASP classiche leggono Request.Form solo in formato urlencoded (non multipart)
        const body = new URLSearchParams(new FormData(form)).toString();
        const r = await fetch(form.action, { method: 'POST', body, headers: { 'X-Requested-With': 'fetch', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } });
        const d = await r.json();
        show(d.ok, d.msg);
        if (d.ok) { form.reset(); if (ts) ts.value = String(Date.now()); }
      } catch (err) {
        show(false, 'Non riesco a contattare il server: riprova fra poco oppure scrivici a info@siderahr.it');
      } finally { btn.disabled = false; }
    });
  }

  /* ---------- Live: cruscotto in tempo reale (stats.asp) ---------- */
  const liveEls = $$('[data-live]');
  if (liveEls.length) {
    const state = $('#live-state'), tsEl = $('#live-ts'), dots = $$('.live-dot'), ticker = $('#live-ticker');
    let chart = null, lastVals = {};
    const tipoLabel = { E: 'Entrata', U: 'Uscita', I: 'Entrata', O: 'Uscita', B: 'Beacon', G: 'GPS', A: 'App', T: 'Timbratore' };
    const setNum = (el, val) => {
      if (val < 0) { el.textContent = 'n.d.'; return; }
      const key = el.getAttribute('data-live');
      const from = lastVals[key] == null ? 0 : lastVals[key];
      if (from === val && el.textContent !== '–') return;
      lastVals[key] = val;
      if (reduced) { el.textContent = fmt.format(val); return; }
      const t0 = performance.now(), dur = 900;
      el.classList.add('bump');
      const tick = (t) => { const p = Math.min(1, (t - t0) / dur), e = 1 - Math.pow(1 - p, 3); el.textContent = fmt.format(Math.round(from + (val - from) * e)); if (p < 1) requestAnimationFrame(tick); else el.classList.remove('bump'); };
      requestAnimationFrame(tick);
    };
    const render = (d) => {
      liveEls.forEach((el) => { const k = el.getAttribute('data-live'); if (k in d) setNum(el, Number(d[k])); });
      if (state) state.textContent = 'Dati in tempo reale';
      if (tsEl) tsEl.textContent = 'aggiornato alle ' + new Date().toLocaleTimeString('it-IT');
      dots.forEach((x) => x.classList.remove('off'));
      if (ticker && Array.isArray(d.ultime)) {
        ticker.innerHTML = d.ultime.length ? d.ultime.map((u) => '<li><span>' + u.ora + '</span><span class="tipo">' + (tipoLabel[u.tipo] || 'timbratura ricevuta') + '</span></li>').join('') : '<li class="muted">Nessuna timbratura nelle ultime ore</li>';
      }
      const cv = $('#live-chart');
      if (cv && window.Chart && Array.isArray(d.ore)) {
        const colors = d.ore.map((_, i) => (i === 23 ? '#ec6725' : '#2d81b1'));
        if (!chart) {
          chart = new window.Chart(cv, { type: 'bar', data: { labels: d.ore_label, datasets: [{ data: d.ore, backgroundColor: colors, borderRadius: 6 }] },
            options: { responsive: true, maintainAspectRatio: false, animation: reduced ? false : { duration: 600 }, plugins: { legend: { display: false }, tooltip: { callbacks: { title: (it) => 'Ore ' + it[0].label + ':00', label: (c) => ' ' + fmt.format(c.parsed.y) + ' timbrature' } } },
              scales: { y: { beginAtZero: true, ticks: { callback: (v) => fmt.format(v) }, grid: { color: 'rgba(0,0,0,.06)' } }, x: { grid: { display: false }, ticks: { maxRotation: 0, autoSkip: true } } } } });
        } else { chart.data.labels = d.ore_label; chart.data.datasets[0].data = d.ore; chart.data.datasets[0].backgroundColor = colors; chart.update(); }
      }
    };
    const fail = () => { if (state) state.textContent = 'Dati momentaneamente non disponibili'; dots.forEach((x) => x.classList.add('off')); };
    const load = async () => {
      try { const r = await fetch('stats.asp?_=' + Date.now(), { cache: 'no-store' }); const d = await r.json(); if (d && d.ok) render(d); else fail(); } catch (e) { fail(); }
    };
    load();
    setInterval(() => { if (!document.hidden) load(); }, 15000);
    document.addEventListener('visibilitychange', () => { if (!document.hidden) load(); });
  }

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