/**
 * TechShop Perú - JavaScript Principal
 * 
 * Funcionalidades interactivas de la tienda.
 * Compatible con PHP y con un crecimiento gradual a TypeScript.
 * 
 * @package TechShop Perú
 * @version 1.0
 */

document.addEventListener('DOMContentLoaded', function () {
  const baseUrl = (document.body.dataset.baseUrl || '').replace(/\/$/, '');
  const apiUrl = function (path) {
    return baseUrl + '/' + path.replace(/^\//, '');
  };

  // Obtener token CSRF del meta tag generado en el header
  const csrfMeta = document.querySelector('meta[name="csrf-token"]');
  const csrfToken = csrfMeta ? csrfMeta.getAttribute('content') : '';

  if (typeof bootstrap === 'undefined') {
    console.warn('Bootstrap no está disponible; algunas funciones interactivas se deshabilitarán.');
  }

  // ============================================
  // AUTO-CERRAR ALERTAS después de 5 segundos
  // ============================================
  function showAppToast(message, type) {
    if (typeof window.showToast === 'function') {
      window.showToast(message, type);
      return;
    }
    console.info(message);
  }

  const alerts = document.querySelectorAll('.alert-dismissible');
  alerts.forEach(function (alert) {
    setTimeout(function () {
      const bsAlert = bootstrap.Alert.getOrCreateInstance(alert);
      if (bsAlert) bsAlert.close();
    }, 5000);
  });

  // ============================================
  // TOOLTIPS de Bootstrap
  // ============================================
  if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
    const tooltipTriggerList = [].slice.call(
      document.querySelectorAll('[data-bs-toggle="tooltip"]')
    );
    tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl);
    });
  }

  // ============================================
  // BOTONES DE CANTIDAD (+/-)
  // Cubre .qty-btn (carrito) y .detail-qty-btn (detalle de producto)
  // ============================================
  document.querySelectorAll('.qty-btn, .detail-qty-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
      const input = this.parentElement.querySelector('.quantity-input, .cart-qty-input');
      if (!input) return;
      const current = parseInt(input.value) || 1;
      const max = parseInt(input.getAttribute('max') || '999');
      if (this.classList.contains('qty-plus')) {
        if (current < max) input.value = current + 1;
      } else if (this.classList.contains('qty-minus')) {
        if (current > 1) input.value = current - 1;
      }
      // Aviso de stock máximo alcanzado en el detalle
      const stockLabel = document.getElementById('detailQtyStock');
      if (stockLabel) {
        stockLabel.textContent =
          parseInt(input.value) >= max
            ? 'Stock máximo (' + max + ')'
            : max + ' disponibles';
      }
      input.dispatchEvent(new Event('change'));
    });
  });

  // ============================================
  // ACTUALIZAR CARRITO POR AJAX (cantidad)
  // ============================================
  document.querySelectorAll('.cart-qty-input').forEach(function (input) {
    input.addEventListener('change', function () {
      const row = this.closest('.cart-item-row');
      const itemId = row.dataset.cartId;
      const quantity = parseInt(this.value) || 1;

      fetch(apiUrl('api/cart-update.php'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'cart_id=' + itemId + '&cantidad=' + quantity + '&csrf_token=' + encodeURIComponent(csrfToken)
      })
        .then(function (res) { return res.json(); })
        .then(function (data) {
          if (data.success) {
            location.reload();
          } else {
            alert(data.message || 'Error al actualizar carrito');
          }
        })
        .catch(function () {
          alert('Error de conexión');
        });
    });
  });

  // ============================================
  // ELIMINAR ITEM DEL CARRITO
  // ============================================
  document.querySelectorAll('.cart-remove-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
      if (!confirm('¿Eliminar este producto del carrito?')) return;
      const itemId = this.dataset.cartId;

      fetch(apiUrl('api/cart-remove.php'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'cart_id=' + itemId + '&csrf_token=' + encodeURIComponent(csrfToken)
      })
        .then(function (res) { return res.json(); })
        .then(function (data) {
          if (data.success) {
            location.reload();
          } else {
            alert(data.message || 'Error al eliminar');
          }
        })
        .catch(function () {
          alert('Error de conexión');
        });
    });
  });

  // ============================================
  // AGREGAR AL CARRITO desde tarjeta de producto
  // ============================================
  document.querySelectorAll('.add-to-cart-btn').forEach(function (btn) {
    btn.addEventListener('click', function (e) {
      e.preventDefault();
      const productoId = this.dataset.productoId;
      // En el detalle de producto usar la cantidad elegida (solo si el botón
      // está en el mismo bloque que el selector); en tarjetas siempre 1
      const qtyWrap = this.closest('.detail-purchase-box');
      const detailQty = qtyWrap ? qtyWrap.querySelector('.detail-qty-input') : null;
      const cantidad = detailQty ? (parseInt(detailQty.value) || 1) : 1;

      this.disabled = true;
      const originalHTML = this.innerHTML;
      this.innerHTML =
        '<span class="spinner-border spinner-border-sm me-1"></span>Agregando...';

      fetch(apiUrl('api/cart-add.php'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'producto_id=' + productoId + '&cantidad=' + cantidad + '&csrf_token=' + encodeURIComponent(csrfToken)
      })
        .then(function (res) { return res.json(); })
        .then(function (data) {
          if (data.success) {
            // Mostrar mini notificación
            showToast('Producto agregado al carrito', 'success');
            // Actualizar badge del carrito si existe
            const badge = document.querySelector('.cart-badge');
            if (badge) {
              badge.textContent = data.cart_count || '1';
              badge.style.display = 'inline-block';
            }
          } else {
            showToast(data.message || 'Error', 'danger');
          }
        })
        .catch(function () {
          showToast('Error de conexión', 'danger');
        })
        .finally(function () {
          btn.disabled = false;
          btn.innerHTML = originalHTML;
        });
    });
  });

  // ============================================
  // TOGGLE FAVORITOS (corazón)
  // ============================================
  document.querySelectorAll('.btn-fav').forEach(function (btn) {
    btn.addEventListener('click', function (e) {
      e.preventDefault();
      const productoId = this.dataset.productoId;

      fetch(apiUrl('api/favorite-toggle.php'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'producto_id=' + productoId + '&csrf_token=' + encodeURIComponent(csrfToken)
      })
        .then(function (res) { return res.json(); })
        .then(function (data) {
          if (data.success) {
            if (data.is_favorite) {
              btn.classList.add('active');
              btn.querySelector('i').classList.replace('bi-heart', 'bi-heart-fill');
              showToast('Agregado a favoritos', 'success');
            } else {
              btn.classList.remove('active');
              btn.querySelector('i').classList.replace('bi-heart-fill', 'bi-heart');
              showToast('Quitado de favoritos', 'info');
            }
          } else {
            showToast(data.message || 'Debes iniciar sesión', 'warning');
          }
        })
        .catch(function () {
          showToast('Error de conexión', 'danger');
        });
    });
  });

  // ============================================
  // BÚSQUEDA CON DEBOUNCE (live search) + HISTORIAL (Mejora 6)
  // ============================================
  const searchInput = document.getElementById('global-search-input');
  const suggestBox = document.getElementById('search-suggest-box');
  const historyBox = document.getElementById('search-history-box');
  const historyList = document.getElementById('search-history-list');
  const SEARCH_HISTORY_KEY = 'ts-search-history';
  const MAX_HISTORY = 6;

  function getSearchHistory() {
    try { return JSON.parse(localStorage.getItem(SEARCH_HISTORY_KEY) || '[]'); } catch(e) { return []; }
  }
  function saveSearchTerm(term) {
    let h = getSearchHistory().filter(function(t){ return t !== term; });
    h.unshift(term);
    h = h.slice(0, MAX_HISTORY);
    localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(h));
  }
  function renderHistoryBox() {
    if (!historyList || !historyBox) return;
    const h = getSearchHistory();
    if (h.length === 0) {
      historyList.innerHTML = '<li class="list-group-item border-0 text-muted small py-1 px-3">Sin búsquedas recientes</li>';
    } else {
      historyList.innerHTML = h.map(function(t){
        return '<li class="list-group-item list-group-item-action py-1 px-3 border-0 search-history-item" data-q="' + t + '" style="cursor:pointer;font-size:.87rem;"><i class="bi bi-clock me-2 text-muted"></i>' + t + '</li>';
      }).join('');
      historyList.querySelectorAll('.search-history-item').forEach(function(li){
        li.addEventListener('click', function(){ searchInput.value = this.dataset.q; searchInput.form.submit(); });
      });
    }
  }
  
  if (searchInput && historyBox) {
    searchInput.addEventListener('focus', function() {
      if (searchInput.value.trim().length < 2 && suggestBox) {
        suggestBox.style.display = 'none';
        renderHistoryBox();
        historyBox.style.display = 'block';
      }
    });
    document.querySelectorAll('#search-trends-list .search-history-item').forEach(function(li){
      li.addEventListener('click', function(){ searchInput.value = this.dataset.q; searchInput.form.submit(); });
    });
    const clearBtn = document.getElementById('clear-search-history');
    if (clearBtn) clearBtn.addEventListener('click', function(e){ e.stopPropagation(); localStorage.removeItem(SEARCH_HISTORY_KEY); renderHistoryBox(); });
    const searchMainForm = document.getElementById('search-form-main');
    if (searchMainForm) {
      searchMainForm.addEventListener('submit', function() {
        const q = searchInput.value.trim();
        if (q.length > 1) saveSearchTerm(q);
      });
    }
  }

  if (searchInput && suggestBox) {
    let searchTimeout;
    searchInput.addEventListener('input', function () {
      clearTimeout(searchTimeout);
      const query = this.value.trim();
      if (historyBox) historyBox.style.display = 'none';

      if (query.length < 2) {
        suggestBox.style.display = 'none';
        suggestBox.innerHTML = '';
        return;
      }

      searchTimeout = setTimeout(function () {
        fetch(apiUrl('api/search-suggest.php?q=' + encodeURIComponent(query)))
          .then(function (res) { return res.json(); })
          .then(function (data) {
            if (data.success && data.results.length > 0) {
              let html = '';
              data.results.forEach(function (item) {
                html += '<a href="' + item.url + '" class="dropdown-item d-flex align-items-center gap-2 py-2 border-bottom">' +
                  '<img src="' + item.imagen + '" alt="' + item.nombre + '" style="width: 40px; height: 40px; object-fit: contain;" class="rounded bg-light p-1">' +
                  '<div class="flex-grow-1 overflow-hidden">' +
                    '<div class="fw-bold text-truncate text-dark small mb-0">' + item.nombre + '</div>' +
                    '<small class="text-muted">' + item.categoria + '</small>' +
                  '</div>' +
                  '<div class="fw-bold text-primary small">' + item.precio_formateado + '</div>' +
                '</a>';
              });
              suggestBox.innerHTML = html;
              suggestBox.style.display = 'block';
            } else {
              suggestBox.innerHTML = '<div class="p-3 text-center text-muted small"><i class="bi bi-search me-1"></i>No se encontraron resultados</div>';
              suggestBox.style.display = 'block';
            }
          })
          .catch(function () {
            suggestBox.style.display = 'none';
          });
      }, 300);
    });

    document.addEventListener('click', function (e) {
      if (!searchInput.contains(e.target) && !suggestBox.contains(e.target)) {
        suggestBox.style.display = 'none';
        if (historyBox && !historyBox.contains(e.target)) historyBox.style.display = 'none';
      }
    });
  }

  // ============================================
  // QUICK VIEW MODAL (Vista Rápida - Mejora 7)
  // ============================================
  document.querySelectorAll('.btn-quick-view').forEach(function (btn) {
    btn.addEventListener('click', function (e) {
      e.preventDefault();
      e.stopPropagation();
      const productoId = this.dataset.productoId;
      const qvBody = document.getElementById('quick-view-body');
      const qvModal = document.getElementById('quickViewModal');
      if (!qvBody || !qvModal) return;
      qvBody.innerHTML = '<div class="text-center py-5"><div class="spinner-border text-primary"></div><p class="mt-2 text-muted small">Cargando...</p></div>';
      const modal = new bootstrap.Modal(qvModal);
      modal.show();
      fetch(apiUrl('api/product-quickview.php?id=' + productoId))
        .then(function(res){ return res.json(); })
        .then(function(data){
          if (data.success) {
            qvBody.innerHTML = data.html;
            // Re-bind add-to-cart inside modal
            qvBody.querySelectorAll('.add-to-cart-btn').forEach(function(b){
              b.addEventListener('click', function(){
                const pid = this.dataset.productoId;
                fetch(apiUrl('api/cart-add.php'), { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:'producto_id='+pid+'&cantidad=1&csrf_token='+encodeURIComponent(csrfToken) })
                  .then(function(r){ return r.json(); })
                  .then(function(d){ if(d.success){ showToast('Producto agregado al carrito','success'); const badge=document.querySelector('.cart-badge'); if(badge) badge.textContent=d.cart_count||'1'; } else { showToast(d.message||'Error','danger'); } });
              });
            });
          } else {
            qvBody.innerHTML = '<p class="text-danger text-center">' + (data.message || 'Error al cargar el producto') + '</p>';
          }
        })
        .catch(function(){ qvBody.innerHTML = '<p class="text-danger text-center">Error de conexión</p>'; });
    });
  });


  // ============================================
  // APLICAR CUPÓN DE DESCUENTO
  // ============================================
  const couponForm = document.getElementById('coupon-form');
  if (couponForm) {
    couponForm.addEventListener('submit', function (e) {
      e.preventDefault();
      const codeInput = document.getElementById('coupon-code-input');
      const code = codeInput ? codeInput.value.trim() : '';

      fetch(apiUrl('api/coupon-apply.php'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'codigo=' + encodeURIComponent(code) + '&csrf_token=' + encodeURIComponent(csrfToken)
      })
        .then(function (res) { return res.json(); })
        .then(function (data) {
          if (data.success) {
            showToast(data.message, 'success');
            setTimeout(function () { location.reload(); }, 800);
          } else {
            showToast(data.message || 'Error al aplicar cupón', 'danger');
          }
        })
        .catch(function () {
          showToast('Error de conexión', 'danger');
        });
    });
  }

  // ============================================
  // BOTÓN DE COMPARAR PRODUCTOS
  // ============================================
  document.querySelectorAll('.btn-compare').forEach(function (btn) {
    btn.addEventListener('click', function (e) {
      e.preventDefault();
      const productoId = this.dataset.productoId;

      fetch(apiUrl('api/compare-toggle.php'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'producto_id=' + productoId + '&csrf_token=' + encodeURIComponent(csrfToken)
      })
        .then(function (res) { return res.json(); })
        .then(function (data) {
          if (data.success) {
            showToast(data.message, 'success');
            const countEl = document.getElementById('compare-count');
            if (countEl) countEl.textContent = data.count;
            if (location.pathname.includes('comparar.php')) {
              setTimeout(function () { location.reload(); }, 600);
            }
          } else {
            showToast(data.message || 'Error en comparador', 'warning');
          }
        })
        .catch(function () {
          showToast('Error de conexión', 'danger');
        });
    });
  });

  // ============================================
  // SOLICITUD DE NOTIFICACIÓN DE STOCK AGOTADO
  // ============================================
  const stockForm = document.getElementById('stock-notify-form');
  if (stockForm) {
    stockForm.addEventListener('submit', function (e) {
      e.preventDefault();
      const formData = new FormData(this);
      formData.append('csrf_token', csrfToken);
      const btn = this.querySelector('button[type="submit"]');
      if (btn) btn.disabled = true;

      fetch(apiUrl('api/stock-notify.php'), {
        method: 'POST',
        body: new URLSearchParams(formData)
      })
        .then(function (res) { return res.json(); })
        .then(function (data) {
          if (data.success) {
            showToast(data.message, 'success');
            stockForm.reset();
          } else {
            showToast(data.message || 'Error', 'danger');
          }
        })
        .catch(function () {
          showToast('Error de conexión', 'danger');
        })
        .finally(function () {
          if (btn) btn.disabled = false;
        });
    });
  }
  // PRODUCT GALLERY (detalle de producto)
  // ============================================
  document.querySelectorAll('.product-gallery-thumbs .thumb').forEach(function (thumb) {
    thumb.addEventListener('click', function () {
      const mainImg = document.querySelector('.product-gallery-main img');
      if (mainImg) {
        mainImg.src = this.querySelector('img').src;
      }
      // Actualizar clase active
      this.parentElement.querySelectorAll('.thumb').forEach(function (t) {
        t.classList.remove('active');
      });
      this.classList.add('active');
    });
  });

  // ============================================
  // VALIDACIÓN DE FORMULARIOS
  // ============================================
  document.querySelectorAll('.needs-validation').forEach(function (form) {
    form.addEventListener(
      'submit',
      function (event) {
        if (!form.checkValidity()) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      },
      false
    );
  });

  // ============================================
  // TOGGLE PASSWORD VISIBILITY
  // ============================================
  document.querySelectorAll('.toggle-password').forEach(function (btn) {
    btn.addEventListener('click', function () {
      const input = document.querySelector(this.dataset.target);
      if (input) {
        const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
        input.setAttribute('type', type);
        this.querySelector('i').classList.toggle('bi-eye');
        this.querySelector('i').classList.toggle('bi-eye-slash');
      }
    });
  });

  // ============================================
  // DARK MODE TOGGLE (Consolidado)
  // ============================================
  const darkModeToggle = document.getElementById('darkModeToggle') || document.getElementById('theme-toggle-btn');
  const labelText = document.getElementById('darkModeLabelText');
  if (darkModeToggle) {
    if (document.body.classList.contains('dark-theme')) {
      if (labelText) labelText.textContent = 'Claro';
    }

    darkModeToggle.addEventListener('click', function () {
      const isDark = document.body.classList.toggle('dark-theme');
      localStorage.setItem('ts-theme', isDark ? 'dark' : 'light');
      document.documentElement.setAttribute('data-dark', isDark ? '1' : '0');
      if (labelText) {
        labelText.textContent = isDark ? 'Claro' : 'Oscuro';
      }
    });
  }

  // ============================================
  // COUNTDOWN TIMER (OFERTAS)
  // ============================================
  const countdownElements = document.querySelectorAll('.countdown-timer');
  if (countdownElements.length > 0) {
    setInterval(function () {
      const now = new Date().getTime();
      countdownElements.forEach(function (el) {
        const targetDate = new Date(el.dataset.date).getTime();
        const distance = targetDate - now;

        if (distance < 0) {
          el.innerHTML = "<span class='badge bg-danger'>¡Oferta expirada!</span>";
          return;
        }

        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);

        el.innerHTML = `
          <div class="countdown-wrapper">
            <div class="countdown-unit"><span class="countdown-num">${days}</span><span class="countdown-label">Días</span></div><div class="countdown-sep">:</div>
            <div class="countdown-unit"><span class="countdown-num">${hours.toString().padStart(2, '0')}</span><span class="countdown-label">Hrs</span></div><div class="countdown-sep">:</div>
            <div class="countdown-unit"><span class="countdown-num">${minutes.toString().padStart(2, '0')}</span><span class="countdown-label">Min</span></div><div class="countdown-sep">:</div>
            <div class="countdown-unit"><span class="countdown-num">${seconds.toString().padStart(2, '0')}</span><span class="countdown-label">Seg</span></div>
          </div>
        `;
      });
    }, 1000);
  }

  // ============================================
  // COMPRAR AHORA (agregar al carrito + ir al checkout)
  // ============================================
  document.querySelectorAll('.btn-buy-now').forEach(function (btn) {
    btn.addEventListener('click', function (e) {
      e.preventDefault();
      const productoId = this.dataset.productoId;
      const qtyWrap = this.closest('.detail-purchase-box');
      const detailQty = qtyWrap ? qtyWrap.querySelector('.detail-qty-input') : null;
      const cantidad = detailQty ? (parseInt(detailQty.value) || 1) : 1;

      this.disabled = true;
      const originalHTML = this.innerHTML;
      this.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Procesando...';

      fetch(apiUrl('api/cart-add.php'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'producto_id=' + productoId + '&cantidad=' + cantidad + '&csrf_token=' + encodeURIComponent(csrfToken)
      })
        .then(function (res) { return res.json(); })
        .then(function (data) {
          if (data.success) {
            window.location.href = apiUrl('pages/checkout.php');
          } else {
            showToast(data.message || 'Error', 'danger');
            btn.disabled = false;
            btn.innerHTML = originalHTML;
          }
        })
        .catch(function () {
          showToast('Error de conexión', 'danger');
          btn.disabled = false;
          btn.innerHTML = originalHTML;
        });
    });
  });

  // ============================================
  // FILTROS DINÁMICOS AJAX (Catálogo)
  // ============================================
  const filterForm = document.getElementById('filterForm');
  const productsContainer = document.getElementById('products-grid-container');
  if (filterForm && productsContainer) {
    const applyFilterAjax = function (page) {
      page = page || 1;
      const formData = new FormData(filterForm);
      const params = new URLSearchParams(formData);
      params.set('pagina', page);

      productsContainer.style.opacity = '0.5';

      fetch(apiUrl('api/products-filter.php?' + params.toString()))
        .then(function (res) { return res.json(); })
        .then(function (data) {
          if (data.success) {
            productsContainer.innerHTML = data.html;
            const countEl = document.getElementById('products-count');
            if (countEl) countEl.textContent = data.total + ' producto(s) encontrado(s)';
          }
        })
        .catch(function () {})
        .finally(function () {
          productsContainer.style.opacity = '1';
        });
    };

    filterForm.addEventListener('change', function () { applyFilterAjax(1); });
    filterForm.addEventListener('submit', function (e) {
      e.preventDefault();
      applyFilterAjax(1);
    });
  }

});


// ============================================
// TOAST NOTIFICATION
// ============================================
function showToast(message, type) {
  // Crear contenedor de toasts si no existe
  let container = document.getElementById('toast-container');
  if (!container) {
    container = document.createElement('div');
    container.id = 'toast-container';
    container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
    container.style.zIndex = '9999';
    document.body.appendChild(container);
  }

  const id = 'toast-' + Date.now();
  const bgClass =
    type === 'success'
      ? 'bg-success'
      : type === 'danger'
      ? 'bg-danger'
      : type === 'warning'
      ? 'bg-warning text-dark'
      : 'bg-info';

  if (typeof bootstrap === 'undefined' || !bootstrap.Toast) {
    alert(message);
    return;
  }

  const html =
    '<div id="' +
    id +
    '" class="toast align-items-center text-white ' +
    bgClass +
    ' border-0" role="alert" aria-live="assertive" aria-atomic="true">' +
    '<div class="d-flex">' +
    '<div class="toast-body">' +
    message +
    '</div>' +
    '<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Cerrar"></button>' +
    '</div>' +
    '</div>';

  container.insertAdjacentHTML('beforeend', html);

  const toastEl = document.getElementById(id);
  const toast = new bootstrap.Toast(toastEl, { delay: 3000 });
  toast.show();

  toastEl.addEventListener('hidden.bs.toast', function () {
    toastEl.remove();
  });
}
