{{-- Polling fluido board asporto (opzione B): sostituisce #asportoBoard se cambia signature --}}
<script>
window.AsportoBoardPoll = (function () {
  const DEFAULT_MS = 20000;

  let timer = null;
  let url = null;
  let intervalMs = DEFAULT_MS;
  let signature = null;
  let inFlight = false;
  let paused = false;
  let onUpdate = null;
  let started = false;

  function tick() {
    if (!url || document.hidden || inFlight || paused) return;

    inFlight = true;
    const sep = url.indexOf('?') >= 0 ? '&' : '?';
    const requestUrl = signature
      ? (url + sep + 'signature=' + encodeURIComponent(signature))
      : url;

    fetch(requestUrl, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      },
      credentials: 'same-origin'
    })
      .then(function (res) {
        if (!res.ok) throw new Error('Sync fallito');
        return res.json();
      })
      .then(function (data) {
        if (!data || typeof data.signature === 'undefined') return;
        signature = data.signature;
        if (!data.changed || !data.html || typeof onUpdate !== 'function') return;
        onUpdate(data.html, data);
      })
      .catch(function () {
        /* silenzioso: riprova al prossimo tick */
      })
      .finally(function () {
        inFlight = false;
      });
  }

  function onVisibility() {
    if (!document.hidden) tick();
  }

  function start(opts) {
    opts = opts || {};
    if (started) stop();

    url = opts.url || null;
    intervalMs = opts.intervalMs || DEFAULT_MS;
    onUpdate = opts.onUpdate || null;
    signature = opts.signature || null;
    paused = false;
    inFlight = false;

    if (!url || typeof onUpdate !== 'function') return;

    started = true;
    document.addEventListener('visibilitychange', onVisibility);
    timer = setInterval(tick, intervalMs);
  }

  function stop() {
    if (timer) clearInterval(timer);
    timer = null;
    document.removeEventListener('visibilitychange', onVisibility);
    started = false;
    inFlight = false;
  }

  function pause() {
    paused = true;
  }

  function resume() {
    paused = false;
  }

  function setSignature(value) {
    signature = value || null;
  }

  return {
    start: start,
    stop: stop,
    pause: pause,
    resume: resume,
    tick: tick,
    setSignature: setSignature
  };
})();
</script>
