// Guarda / restaura el estado de cualquier formulario basado en su id único
export function initStatePersistence(key, form) {
  if (!form) return;

  // ----- Restaurar -----
  const saved = localStorage.getItem(key);
  if (saved) {
    try {
      const data = JSON.parse(saved);
      Object.entries(data).forEach(([name, value]) => {
        const field = form.elements[name];
        if (!field) return;

        if (field.type === 'checkbox' || field.type === 'radio') {
          field.checked = value;
        } else {
          field.value = value;
        }
      });
    } catch (e) {
      console.warn('Estado corrupto para', key);
    }
  }

  // ----- Guardar en cada cambio -----
  form.addEventListener('input', () => saveForm());
  form.addEventListener('change', () => saveForm());

  function saveForm() {
    const data = {};
    Array.from(form.elements).forEach(el => {
      if (!el.name) return;
      data[el.name] = (el.type === 'checkbox' || el.type === 'radio')
        ? el.checked
        : el.value;
    });
    localStorage.setItem(key, JSON.stringify(data));
  }
}

// Limpiar cuando cobrás / finalizás
export function clearState(key) {
  localStorage.removeItem(key);
}
