/**
 * Tilvora — Quote Request Modal
 *
 * Intercepts the "Get a Quote" button (capture phase, before woo-bridge.js),
 * shows a modal with the customer's current selections (floor, wall, etc.)
 * and a contact form that submits via AJAX to the business owner's email.
 *
 * Runs as a regular (non-module) script so it executes synchronously during
 * HTML parsing — guaranteeing event-listener registration before woo-bridge.js
 * (deferred module) can attach its own click handler.
 */

(function () {
  'use strict';

  var overlay    = document.getElementById('fv-quote-overlay');
  var modal      = document.getElementById('fv-quote-modal');
  var cartBtn    = document.getElementById('btn-add-to-cart');
  var closeBtn   = document.getElementById('fv-quote-close');
  var successDiv = document.getElementById('fv-quote-success');
  var form       = document.getElementById('fv-quote-form');
  var submitBtn  = document.getElementById('fv-q-submit');
  var successCloseBtn = document.getElementById('fv-success-close');

  if (!overlay || !cartBtn) return;

  // ── Current order snapshot ────────────────────────────────────────────────
  // window.Configurator.getOrder() is app.js's own public API — it already
  // knows every control's current selection (whatever tabs/controls a
  // product's config.json defines, generically, including material-grid's
  // name+SKU formatting, thumbnail, and the live price total) and stays
  // correct as config.json changes over time. Scraping DOM classes like
  // ".noor-stk.active" instead would silently go stale the moment a
  // tab/control is renamed or removed — which is exactly what happened when
  // the old "Finish" tab was retired but this modal kept looking for
  // ".noor-finish-card.active".
  var lastOrder = null;
  function getOrder() {
    if (window.Configurator && typeof window.Configurator.getOrder === 'function') {
      try { return window.Configurator.getOrder(); } catch (e) { return null; }
    }
    return null;
  }

  // ── Design snapshot ───────────────────────────────────────────────────────
  // Captured synchronously on click while the WebGL buffer still holds the
  // current frame. With preserveDrawingBuffer:false (Three.js default) this
  // is the only reliable capture point — before the next draw call clears it.
  var designImageData = null;

  function captureCanvas() {
    var canvas = document.getElementById('canvas');
    if (!canvas || !canvas.width || !canvas.height) { return; }
    try {
      var src = canvas;
      var maxW = 1200;
      if (canvas.width > maxW) {
        var off = document.createElement('canvas');
        off.width  = maxW;
        off.height = Math.round(canvas.height * (maxW / canvas.width));
        off.getContext('2d').drawImage(canvas, 0, 0, off.width, off.height);
        src = off;
      }
      var data = src.toDataURL('image/jpeg', 0.82);
      // A blank WebGL canvas produces a very short data URL (~4 KB base64).
      // Keep only captures that contain real pixel data.
      designImageData = (data && data.length > 10000) ? data : null;
    } catch (e) {
      designImageData = null;
    }
  }

  // ── Intercept cart button (capture phase) ─────────────────────────────────
  cartBtn.addEventListener('click', function (e) {
    e.stopImmediatePropagation();
    e.preventDefault();
    captureCanvas();
    openModal();
  }, true);

  // ── Open / close ──────────────────────────────────────────────────────────
  function openModal() {
    populateTilePreview();
    overlay.classList.add('is-open');
    document.body.style.overflow = 'hidden';
    setTimeout(function () {
      var first = modal.querySelector('input');
      if (first) first.focus();
    }, 320);
  }

  function closeModal() {
    overlay.classList.remove('is-open');
    document.body.style.overflow = '';
  }

  function resetModal() {
    closeModal();
    setTimeout(function () {
      form.style.display         = '';
      form.reset();
      successDiv.style.display   = 'none';
      submitBtn.disabled         = false;
      submitBtn.textContent      = 'Request a Quote';
    }, 380);
  }

  overlay.addEventListener('click', function (e) {
    if (e.target === overlay) resetModal();
  });
  closeBtn.addEventListener('click', resetModal);
  if (successCloseBtn) successCloseBtn.addEventListener('click', resetModal);

  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape' && overlay.classList.contains('is-open')) resetModal();
  });

  // ── Populate selection chips from the live order snapshot ───────────────────
  // One chip per order-eligible control — a customer who picked both a floor
  // and a wall material sees both, each with its own thumbnail, instead of
  // only the first selection made anywhere in the product.
  var SEL_PLACEHOLDER_ICON = '<svg width="18" height="18" viewBox="0 0 20 20" fill="none">' +
    '<rect x="2" y="2" width="7" height="7" rx="1.5" stroke="currentColor" stroke-width="1.4"/>' +
    '<rect x="11" y="2" width="7" height="7" rx="1.5" stroke="currentColor" stroke-width="1.4"/>' +
    '<rect x="2" y="11" width="7" height="7" rx="1.5" stroke="currentColor" stroke-width="1.4"/>' +
    '<rect x="11" y="11" width="7" height="7" rx="1.5" stroke="currentColor" stroke-width="1.4"/>' +
    '</svg>';

  function escapeHtml(s) {
    var div = document.createElement('div');
    div.textContent = s;
    return div.innerHTML;
  }

  function populateTilePreview() {
    lastOrder = getOrder();
    var fields = (lastOrder && lastOrder.fields) || [];
    var container = document.getElementById('fv-q-selections');

    if (!fields.length) {
      container.innerHTML =
        '<div class="fv-sel-chip"><div class="fv-sel-thumb-ph">' + SEL_PLACEHOLDER_ICON + '</div>' +
        '<div class="fv-sel-text"><div class="fv-sel-value">No selection yet</div></div></div>';
      return;
    }

    container.innerHTML = fields.map(function (f) {
      var thumb = f.thumbnail
        ? '<img class="fv-sel-thumb" src="' + escapeHtml(f.thumbnail) + '" alt="" />'
        : '<div class="fv-sel-thumb-ph">' + SEL_PLACEHOLDER_ICON + '</div>';
      return '<div class="fv-sel-chip">' + thumb +
        '<div class="fv-sel-text">' +
        '<div class="fv-sel-label">' + escapeHtml(f.label) + '</div>' +
        '<div class="fv-sel-value">' + escapeHtml(String(f.value)) + '</div>' +
        '</div></div>';
    }).join('');
  }

  // ── Form submit → AJAX ────────────────────────────────────────────────────
  form.addEventListener('submit', function (e) {
    e.preventDefault();

    var name     = document.getElementById('fv-q-name').value.trim();
    var email    = document.getElementById('fv-q-email').value.trim();
    if (!name || !email) {
      highlightEmpty();
      return;
    }

    submitBtn.disabled    = true;
    submitBtn.textContent = 'Sending…';

    // Re-snapshot right before submit (not just whatever populateTilePreview()
    // captured on open) so a customer who changes their mind after opening
    // the modal — unlikely given the modal blocks the panel, but cheap to
    // guard against — still submits their final selection.
    var order      = getOrder() || lastOrder;
    var fields     = (order && order.fields) || [];
    var price      = order && order.price;
    var tileNameText = fields.length ? fields.map(function (f) { return f.value; }).join(' + ') : 'No selection yet';

    var fd = new FormData();
    fd.append('action',      'tilvora_quote_request');
    fd.append('nonce',       window.configuratorAjax ? window.configuratorAjax.quoteNonce : '');
    fd.append('project_id',  window.configuratorAjax ? window.configuratorAjax.projectId  : '');
    fd.append('tile_name',   tileNameText);
    fd.append('fields_json', JSON.stringify(fields));
    fd.append('price_total', price && price.total != null ? price.total : '');
    fd.append('currency',    price ? (price.currency || '') : '');
    fd.append('name',        name);
    fd.append('email',       email);
    fd.append('phone',       document.getElementById('fv-q-phone').value.trim());
    fd.append('postcode',    document.getElementById('fv-q-postcode').value.trim());
    fd.append('notes',       document.getElementById('fv-q-notes').value.trim());
    if (designImageData) {
      fd.append('design_image', designImageData);
    }

    fetch(window.configuratorAjax ? window.configuratorAjax.ajaxUrl : '/wp-admin/admin-ajax.php', {
      method: 'POST',
      body: fd,
    })
      .then(function (r) { return r.json(); })
      .then(function (res) {
        if (res.success) {
          form.style.display       = 'none';
          successDiv.style.display = 'flex';
          var nameEl = document.getElementById('fv-success-tile-name');
          if (nameEl) nameEl.textContent = tileNameText;
        } else {
          submitBtn.disabled    = false;
          submitBtn.textContent = 'Request a Quote';
          showError(res.data && res.data.message ? res.data.message : 'Something went wrong. Please try again.');
        }
      })
      .catch(function () {
        submitBtn.disabled    = false;
        submitBtn.textContent = 'Request a Quote';
        showError('Connection error. Please check your internet and try again.');
      });
  });

  function highlightEmpty() {
    ['fv-q-name', 'fv-q-email'].forEach(function (id) {
      var el = document.getElementById(id);
      if (!el || el.value.trim()) return;
      el.style.borderColor = '#f87171';
      el.addEventListener('input', function clear() {
        el.style.borderColor = '';
        el.removeEventListener('input', clear);
      });
    });
  }

  function showError(msg) {
    var err = document.getElementById('fv-q-error');
    if (!err) return;
    err.textContent    = msg;
    err.style.display  = 'block';
    setTimeout(function () { err.style.display = 'none'; }, 5000);
  }

})();
