/* ==========================================================================
   Niwa Chatbot -- Product Manager
   ---------------------------------------------------------------------------
   WooCommerce cart transport plus the ProductExperience render entry point.
   No jQuery. All DOM operations use vanilla JS.

   NAMESPACE: window.Niwa.ProductManager
   ========================================================================== */

window.Niwa = window.Niwa || {};

window.Niwa.ProductManager = (function () {
  'use strict';

  /* -- Helpers ------------------------------------------------------------ */

  function _utils() {
    return window.Niwa && window.Niwa.Utils;
  }

  function _renderer() {
    return window.Niwa && window.Niwa.MessageRenderer;
  }

  function _track(eventType, payload, options) {
    var u = _utils();
    if (!u || typeof u.trackFrontendEvent !== 'function') return;
    u.trackFrontendEvent(eventType, payload || {}, options || null);
  }

  function _appendNiwaContext(fd, context) {
    var u = _utils();
    var ctx = context || {};
    if (!ctx.recommended) return;

    fd.append('niwa_ai_recommended', '1');
    fd.append('niwa_ai_source', ctx.source || 'niwa_card');
    fd.append('niwa_ai_context', ctx.context || 'recommendation');
    fd.append('niwa_ai_page_url', window.location.href);
    if (u && typeof u.getSession === 'function') {
      fd.append('niwa_ai_session', u.getSession());
    }
  }

  function _appendVariationSelection(fd, context) {
    var ctx = context || {};
    var variationId = parseInt(ctx.variationId || 0, 10) || 0;
    var attributes = ctx.variationAttributes && typeof ctx.variationAttributes === 'object'
      ? ctx.variationAttributes
      : {};

    if (variationId > 0) fd.append('variation_id', String(variationId));
    if (Object.keys(attributes).length) {
      fd.append('variation_attributes', JSON.stringify(attributes));
      Object.keys(attributes).forEach(function (key) {
        fd.append(key, String(attributes[key] || ''));
      });
    }
  }

  function _productPayload(prod, source, extraMeta) {
    var meta = extraMeta || {};
    return {
      source: source || 'niwa_card',
      product_id: prod && prod.id ? prod.id : 0,
      product_name: prod && prod.name ? prod.name : '',
      meta: meta
    };
  }

  function _getBodyEl() {
    return document.querySelector('.niwa-morph__body')
      || document.querySelector('.niwa-center__body');
  }

  function _scrollToBottom() {
    var bodyEl = _getBodyEl();
    if (bodyEl && window.Niwa && window.Niwa.ScrollBehavior) {
      window.Niwa.ScrollBehavior.scrollToBottom(bodyEl);
    }
  }

  /* -- WooCommerce AJAX URL ----------------------------------------------- */

  function getWcAjaxUrl(endpoint) {
    try {
      if (window.wc_add_to_cart_params && window.wc_add_to_cart_params.wc_ajax_url) {
        return window.wc_add_to_cart_params.wc_ajax_url.replace('%%endpoint%%', endpoint);
      }
    } catch (e) { /* ignore */ }
    return '?wc-ajax=' + endpoint;
  }

  /* -- Apply WC fragment updates ------------------------------------------ */

  function applyWooFragments(fragments, cartHash, btnEl, options) {
    if (!fragments || typeof fragments !== 'object') return false;
    var opts = options || {};
    var emitAdded = opts.emitAdded !== false;
    var emitRefreshed = opts.emitRefreshed !== false;
    var replacedCount = 0;

    try {
      var keys = Object.keys(fragments);
      for (var i = 0; i < keys.length; i++) {
        var selector = keys[i];
        var html = fragments[selector];
        if (typeof html !== 'string' || !selector) continue;
        var targets = document.querySelectorAll(selector);
        for (var j = 0; j < targets.length; j++) {
          var temp = document.createElement('div');
          temp.innerHTML = html;
          var replacement = temp.firstElementChild || temp.firstChild;
          if (replacement && targets[j].parentNode) {
            targets[j].parentNode.replaceChild(replacement, targets[j]);
            replacedCount++;
          }
        }
      }
    } catch (e) { /* ignore */ }

    // Update cart hash in storage
    try {
      if (window.wc_cart_fragments_params) {
        if (cartHash && window.wc_cart_fragments_params.cart_hash_key) {
          sessionStorage.setItem(window.wc_cart_fragments_params.cart_hash_key, cartHash);
          localStorage.setItem(window.wc_cart_fragments_params.cart_hash_key, cartHash);
        }
        if (window.wc_cart_fragments_params.fragment_name) {
          var encoded = JSON.stringify(fragments);
          sessionStorage.setItem(window.wc_cart_fragments_params.fragment_name, encoded);
          localStorage.setItem(window.wc_cart_fragments_params.fragment_name, encoded);
        }
      }
    } catch (e) { /* ignore */ }

    // Dispatch WooCommerce events
    try {
      if (emitAdded) {
        document.body.dispatchEvent(new CustomEvent('added_to_cart', {
          detail: { fragments: fragments, cart_hash: cartHash || '' }
        }));
      }
      if (emitRefreshed) {
        document.body.dispatchEvent(new CustomEvent('wc_fragments_refreshed', {
          detail: { fragments: fragments, cart_hash: cartHash || '' }
        }));
      }
      // Also fire jQuery events if jQuery is present (for WC compatibility)
      if (typeof jQuery !== 'undefined') {
        if (emitAdded) {
          jQuery(document.body).trigger('added_to_cart', [fragments, cartHash || '', btnEl || null]);
        }
        if (emitRefreshed) {
          jQuery(document.body).trigger('wc_fragments_refreshed', [fragments, cartHash || '']);
        }
      }
    } catch (e) { /* ignore */ }

    return replacedCount > 0;
  }

  /* -- Refresh WC fragments ----------------------------------------------- */

  function refreshWcFragments(callback, options) {
    var opts = options || {};
    var url = getWcAjaxUrl('get_refreshed_fragments');
    var fd = new FormData();

    fetch(url, { method: 'POST', body: fd })
      .then(function (r) { return r.json(); })
      .then(function (resp) {
        applyWooFragments(
          resp && resp.fragments ? resp.fragments : null,
          resp && resp.cart_hash ? resp.cart_hash : '',
          null,
          { emitAdded: false }
        );
      })
      .catch(function () {
        var renderer = _renderer();
        var labels = (window.NiwaAI && window.NiwaAI.labels) || {};
        if (!opts.silent && renderer) {
          renderer.addMessage(labels.cart_refresh_error || 'Could not refresh cart. Please reload the page.', 'bot');
        }
      })
      .finally(function () {
        if (typeof callback === 'function') callback();
      });
  }

  /* -- Add to cart (WC native) -------------------------------------------- */

  function addToCartWoo(productId, qty, btnEl, cb, context) {
    var url = getWcAjaxUrl('add_to_cart');
    var fd = new FormData();
    fd.append('product_id', productId);
    fd.append('quantity', qty);
    _appendVariationSelection(fd, context);
    _appendNiwaContext(fd, context);

    fetch(url, { method: 'POST', body: fd })
      .then(function (r) { return r.json(); })
      .then(function (resp) {
        if (!resp || resp.error) {
          if (typeof cb === 'function') cb(false);
          return;
        }

        var fragmentsApplied = applyWooFragments(
          resp && resp.fragments ? resp.fragments : null,
          resp && resp.cart_hash ? resp.cart_hash : '',
          btnEl
        );
        if (!fragmentsApplied) {
          // Trigger fragment refresh as fallback
          document.body.dispatchEvent(new Event('wc_fragment_refresh'));
          if (typeof jQuery !== 'undefined') {
            jQuery(document.body).trigger('wc_fragment_refresh');
          }
        }
        if (typeof cb === 'function') cb(true);
      })
      .catch(function () {
        var renderer = _renderer();
        var labels = (window.NiwaAI && window.NiwaAI.labels) || {};
        if (renderer) {
          renderer.addMessage(labels.cart_error || 'Could not add to cart. Please try again.', 'bot');
        }
        if (typeof cb === 'function') cb(false);
      });
  }

  /* -- Add to cart (fallback via Niwa AJAX) ------------------------------- */

  function addToCartFallback(productId, qty, btnEl, cb, context) {
    var ajaxUrl = window.NiwaAI && window.NiwaAI.ajax;
    var ajaxNonce = window.NiwaAI && window.NiwaAI.nonce;
    if (!ajaxUrl || !ajaxNonce) {
      if (typeof cb === 'function') cb(false);
      return;
    }

    var fd = new FormData();
    fd.append('action', 'niwa_ai_add_to_cart');
    fd.append('nonce', ajaxNonce);
    fd.append('product_id', productId);
    fd.append('qty', qty);
    _appendVariationSelection(fd, context);
    _appendNiwaContext(fd, context);

    fetch(ajaxUrl, { method: 'POST', body: fd })
      .then(function (r) { return r.json(); })
      .then(function (r) {
        if (r && r.success && applyWooFragments(r.fragments || null, r.cart_hash || '', btnEl)) {
          if (typeof cb === 'function') cb(true);
          return;
        }
        refreshWcFragments(function () {
          if (typeof cb === 'function') cb(!!(r && r.success));
        });
      })
      .catch(function () {
        var renderer = _renderer();
        var labels = (window.NiwaAI && window.NiwaAI.labels) || {};
        if (renderer) {
          renderer.addMessage(labels.cart_error || 'Could not add to cart. Please try again.', 'bot');
        }
        if (typeof cb === 'function') cb(false);
      });
  }

  /* -- Smart add to cart -------------------------------------------------- */

  function addToCartSmart(productId, qty, btnEl, cb, context) {
    addToCartFallback(productId, qty, btnEl, function (ok) {
      if (ok) {
        if (typeof cb === 'function') cb(true);
        return;
      }

      if (window.wc_add_to_cart_params) {
        addToCartWoo(productId, qty, btnEl, function (wooOk) {
          if (wooOk) {
            if (typeof cb === 'function') cb(true);
          } else {
            // Don't double-add -- just refresh fragments
            refreshWcFragments(function () {
              if (typeof cb === 'function') cb(false);
            }, { silent: true });
          }
        }, context);
      } else {
        refreshWcFragments(function () {
          if (typeof cb === 'function') cb(false);
        }, { silent: true });
      }
    }, context);
  }

  /* -- Render product cards ----------------------------------------------- */

  function renderProducts(products, skipSave, opts) {
    if (!window.Niwa || !window.Niwa.ProductExperience || typeof window.Niwa.ProductExperience.render !== 'function') {
      return null;
    }
    return window.Niwa.ProductExperience.render(products, skipSave, opts || {});
  }

  /* -- Drag scroll for horizontal product rails --------------------------- */

  function enableDragScroll(railEl) {
    if (!railEl) return;
    var isDown = false;
    var startX = 0;
    var scrollL = 0;
    var moved = false;

    railEl.addEventListener('mousedown', function (e) {
      if (e.target.closest('button, a')) return;
      isDown = true;
      moved = false;
      railEl.classList.add('dragging');
      startX = e.pageX - railEl.getBoundingClientRect().left;
      scrollL = railEl.scrollLeft;
      e.preventDefault();
    });

    railEl.addEventListener('mousemove', function (e) {
      if (!isDown) return;
      var x = e.pageX - railEl.getBoundingClientRect().left;
      var walk = x - startX;
      if (Math.abs(walk) > 3) moved = true;
      railEl.scrollLeft = scrollL - walk;
    });

    railEl.addEventListener('mouseup', function () {
      isDown = false;
      railEl.classList.remove('dragging');
    });

    railEl.addEventListener('mouseleave', function () {
      isDown = false;
      railEl.classList.remove('dragging');
    });

    // Prevent click on cards when dragging
    railEl.addEventListener('click', function (e) {
      if (moved) {
        e.stopPropagation();
        e.preventDefault();
      }
    }, true);
  }

  /* -- Public API --------------------------------------------------------- */

  return {
    renderProducts: renderProducts,
    addToCartSmart: addToCartSmart,
    enableDragScroll: enableDragScroll,
    applyWooFragments: applyWooFragments,
    refreshWcFragments: refreshWcFragments
  };
})();

// Global alias for addToCartSmart (compatibility with CB and other modules)
window.niwaAI = window.niwaAI || {};
window.niwaAI.addToCartSmart = function (productId, qty, btn, cb, context) {
  window.Niwa.ProductManager.addToCartSmart(productId, qty, btn, cb, context);
};
