// Shared front-end behavior, loaded with `defer` from base.html.

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
}

// Inject CSRF token into all POST forms
document.addEventListener('DOMContentLoaded', function() {
  var meta = document.querySelector('meta[name="csrf-token"]');
  var token = meta ? meta.content : '';
  document.querySelectorAll('form').forEach(function(form) {
    if (form.method.toLowerCase() === 'post') {
      var inp = document.createElement('input');
      inp.type = 'hidden'; inp.name = 'csrf_token'; inp.value = token;
      form.appendChild(inp);
    }
  });
});

// "Select from list or type new" pattern on add/edit forms
function metaSelectChanged(sel, inputId) {
  var input = document.getElementById(inputId);
  if (sel.value === '__new__') {
    input.style.display = '';
    input.value = '';
    input.focus();
  } else {
    input.style.display = 'none';
    input.value = sel.value;
  }
  // battery_add defines updateLabelPreview to live-preview generated labels
  if ((inputId === 'brand' || inputId === 'size') && typeof updateLabelPreview === 'function') {
    updateLabelPreview();
  }
}

(function() {
  var modal     = document.getElementById('confirm-modal');
  var msgEl     = document.getElementById('confirm-modal-msg');
  var okBtn     = document.getElementById('confirm-modal-ok');
  var cancelBtn = document.getElementById('confirm-modal-cancel');
  var _cb = null;

  window.showConfirm = function(msg, onOk, okLabel, okClass) {
    msgEl.textContent = msg;
    okBtn.textContent = okLabel || 'Confirm';
    okBtn.className = 'btn ' + (okClass || 'btn-danger');
    modal.classList.add('open');
    _cb = onOk;
    cancelBtn.focus();
  };

  function closeModal() { modal.classList.remove('open'); _cb = null; }

  okBtn.addEventListener('click', function() {
    var cb = _cb; closeModal(); if (cb) cb();
  });
  cancelBtn.addEventListener('click', closeModal);
  modal.addEventListener('click', function(e) { if (e.target === modal) closeModal(); });
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && modal.classList.contains('open')) closeModal();
  });

  // Global handler: forms with data-confirm attribute
  document.addEventListener('submit', function(e) {
    var form = e.target;
    var msg = form.dataset.confirm;
    if (!msg || form.dataset.confirmed) return;
    e.preventDefault();
    var okLabel = form.dataset.confirmOk || 'Confirm';
    var okClass = form.dataset.confirmClass || 'btn-danger';
    window.showConfirm(msg, function() {
      form.dataset.confirmed = '1';
      form.submit();
    }, okLabel, okClass);
  });
}());
