/**
 * BrewmyApp — Mobile Checkout Enhancements
 * Injects dynamic UI elements for a polished checkout experience.
 */
(function () {
  'use strict';

  // Only run inside bma-mobile-checkout context
  if (!document.body.classList.contains('bma-mobile-checkout')) return;

  // Utility: wait for an element, then run callback
  function whenReady(selector, cb, timeout) {
    timeout = timeout || 5000;
    var el = document.querySelector(selector);
    if (el) return cb(el);
    var start = Date.now();
    var iv = setInterval(function () {
      el = document.querySelector(selector);
      if (el) { clearInterval(iv); cb(el); }
      if (Date.now() - start > timeout) clearInterval(iv);
    }, 200);
  }

  // ─── Secure Payment Badge ───────────────────
  function injectSecureBadge() {
    whenReady('#payment .place-order, #payment .form-row.place-order', function (placeOrder) {
      if (document.querySelector('.bma-secure-badge')) return;
      var badge = document.createElement('div');
      badge.className = 'bma-secure-badge';
      badge.innerHTML =
        '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">' +
        '<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>' +
        '<path d="M7 11V7a5 5 0 0 1 10 0v4"/>' +
        '</svg>' +
        '<span>Secure &amp; encrypted payment</span>';
      // Insert after the place-order section
      placeOrder.parentNode.insertBefore(badge, placeOrder.nextSibling);
    });
  }

  // ─── Powered by BrewmyApp Footer ─────────────
  function injectPoweredBy() {
    var woo = document.querySelector('.woocommerce');
    if (!woo) return;
    if (document.querySelector('.bma-powered')) return;
    var p = document.createElement('div');
    p.className = 'bma-powered';
    p.innerHTML = 'Powered by <a href="https://brewmyapp.io" target="_blank" rel="noopener">BrewmyApp</a>';
    woo.appendChild(p);
  }

  // ─── Remove duplicate WooCommerce notices ────
  function dedupeNotices() {
    var seen = {};
    document.querySelectorAll('.woocommerce-error li, .woocommerce-message').forEach(function (el) {
      var text = el.textContent.trim();
      if (seen[text]) { el.remove(); }
      else { seen[text] = true; }
    });
  }

  // ─── Smooth scroll to errors ─────────────────
  function scrollToErrors() {
    var err = document.querySelector('.woocommerce-error, .woocommerce-NoticeGroup');
    if (err) {
      err.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }

  // ─── Inject styles for dynamically injected elements ──
  function injectDynamicStyles() {
    var style = document.createElement('style');
    style.textContent =
      '.bma-secure-badge{' +
      'display:flex;align-items:center;justify-content:center;gap:6px;' +
      'padding:10px 0;color:#9ca3af;font-size:12px;font-weight:500;letter-spacing:0.3px' +
      '}' +
      '.bma-powered{' +
      'text-align:center;padding:12px 0 4px;color:#9ca3af;font-size:11px;opacity:0.6' +
      '}' +
      '.bma-powered a{color:#4b5563;text-decoration:none;font-weight:600}';
    document.head.appendChild(style);
  }

  // ─── Disable iOS auto-zoom on input focus ───
  function disableZoom() {
    var viewport = document.querySelector('meta[name="viewport"]');
    var content = 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no';
    if (viewport) {
      viewport.setAttribute('content', content);
    } else {
      viewport = document.createElement('meta');
      viewport.name = 'viewport';
      viewport.content = content;
      document.head.appendChild(viewport);
    }
  }

  // ─── Initialise ─────────────────────────────
  function init() {
    disableZoom();
    injectDynamicStyles();
    injectSecureBadge();
    // injectPoweredBy();
    dedupeNotices();
    scrollToErrors();

    // Re-run on WooCommerce AJAX updates (e.g. payment method change)
    if (typeof jQuery !== 'undefined') {
      jQuery(document.body).on('updated_checkout payment_method_selected', function () {
        setTimeout(function () {
          injectSecureBadge();
          dedupeNotices();
        }, 300);
      });
    }
  }

  // Fire on DOMContentLoaded or immediately if already loaded
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
