// /home/Autopartes/pos/static/js/offline-banner.js
// Global offline/online banner controller.
// Include this script in any page that has an #offlineBanner element.

(function () {
  'use strict';

  var banner     = document.getElementById('offlineBanner');
  var bannerText = document.getElementById('offlineBannerText');
  if (!banner || !bannerText) return;

  var dismissTimer = null;

  function showOffline() {
    clearTimeout(dismissTimer);
    banner.className = 'banner banner--error';
    banner.style.display = 'flex';
    banner.style.animation = 'slideDown 0.35s ease-out forwards';
    bannerText.innerHTML = '<strong>Conexion perdida</strong> — Intentando reconectar...';
  }

  function showOnline() {
    clearTimeout(dismissTimer);
    banner.className = 'banner banner--success';
    banner.style.display = 'flex';
    banner.style.animation = 'slideDown 0.35s ease-out forwards';
    bannerText.innerHTML = '<strong>Conexion restaurada</strong> — Sincronizando datos...';

    // Auto-dismiss after 3 seconds
    dismissTimer = setTimeout(function () {
      banner.style.animation = 'slideUp 0.3s ease-in forwards';
      banner.addEventListener('animationend', function onEnd() {
        banner.style.display = 'none';
        banner.removeEventListener('animationend', onEnd);
      }, { once: true });
    }, 3000);
  }

  // Show warning immediately if already offline
  if (!navigator.onLine) {
    showOffline();
  }

  window.addEventListener('offline', showOffline);
  window.addEventListener('online', showOnline);
})();
