(function($) {
  'use strict';

  var activeBadge = null;
  var wpCache = {};
  var panelSources = {};

  function escapeAttr(value) {
    return String(value)
      .replace(/&/g, '&amp;')
      .replace(/"/g, '&quot;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;');
  }

  function getCurrentTabSessionId() {
    try {
      return sessionStorage.getItem('mindweco_tab_session_id') || '';
    } catch (error) {
      return '';
    }
  }

  function appendChatContextToUrl(url) {
    var resolvedUrl;

    if (!url) return url;

    try {
      resolvedUrl = new URL(url, window.location.href);
    } catch (error) {
      return url;
    }

    if (resolvedUrl.origin !== window.location.origin) {
      return url;
    }

    var tabSessionId = getCurrentTabSessionId();
    if (!tabSessionId) {
      return url;
    }

    resolvedUrl.searchParams.set('mindweco_tab_session_id', tabSessionId);
    return resolvedUrl.toString();
  }

  function findBadgesByUrl($messageContent, url) {
    return $messageContent.find('.mindweco-citation-badge[data-url]').filter(function() {
      return String($(this).data('url') || $(this).attr('data-url') || '') === String(url);
    });
  }

  function revealPendingBadges($messageContent) {
    $messageContent.find('.mindweco-citation-badge.mwc-badge-pending').each(function() {
      var num = $(this).data('num');
      if (num) {
        $(this)
          .text(num)
          .removeClass('mwc-badge-pending')
          .css('display', '');
      } else {
        $(this).remove();
      }
    });
  }

  function getSourceItemId(source) {
    if (!source || typeof source !== 'object') return null;
    return source.indexing_item_id || source.item_id || source.indexingItemId || null;
  }

  function removeDuplicateItemBadges($messageContent, sourceMetaByNum) {
    var renderedItems = {};

    $messageContent.find('.mindweco-citation-badge[data-num]').each(function() {
      var $badge = $(this);
      var num = String($badge.data('num') || $badge.attr('data-num') || '');
      var meta = sourceMetaByNum[num] || {};
      var itemId = meta.itemId;

      if (!itemId) return;

      if (renderedItems[itemId]) {
        $badge.remove();
        return;
      }

      renderedItems[itemId] = true;
    });
  }

  async function fetchWPPostData(url) {
    if (wpCache[url]) return wpCache[url];

    try {
      var response = await fetch(mindwecoFrontend.ajax_url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
          action: 'mindweco_get_citation_data',
          nonce: mindwecoFrontend.nonce,
          url: url
        }).toString()
      });

      var json = await response.json();
      if (json.success && json.data) {
        wpCache[url] = json.data;
        return json.data;
      }
    } catch (e) {}

    return null;
  }

  var cartIconSVG =
    '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">' +
    '<circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/>' +
    '<path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/>' +
    '</svg>';

  var checkSVG =
    '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">' +
    '<polyline points="20 6 9 17 4 12"/>' +
    '</svg>';

  var spinSVG =
    '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" style="animation:mwc-spin 0.7s linear infinite;">' +
    '<path d="M12 2a10 10 0 1 0 10 10" stroke-linecap="round"/>' +
    '</svg>';

  function ajaxAddToCart($btn, productId) {
    if ($btn.hasClass('loading') || $btn.hasClass('added')) return;

    $btn.addClass('loading').html(spinSVG + ' Adding…');

    var wcAjaxUrl;
    if (typeof wc_add_to_cart_params !== 'undefined' && wc_add_to_cart_params.wc_ajax_url) {
      wcAjaxUrl = wc_add_to_cart_params.wc_ajax_url.replace('%%endpoint%%', 'add_to_cart');
    } else if (typeof woocommerce_params !== 'undefined' && woocommerce_params.wc_ajax_url) {
      wcAjaxUrl = woocommerce_params.wc_ajax_url.replace('%%endpoint%%', 'add_to_cart');
    } else {
      wcAjaxUrl = window.location.origin + '/?wc-ajax=add_to_cart';
    }

    $.ajax({
      url: wcAjaxUrl,
      type: 'POST',
      dataType: 'json',
      data: {
        product_id: productId,
        quantity: 1
      },
      success: function(response) {
        if (response && !response.error) {
          btnSuccess($btn, response);
        } else {
          btnSuccess($btn, response);
        }
      },
      error: function(xhr) {
        if (xhr.status === 200 || xhr.status === 302) {
          btnSuccess($btn, null);
        } else {
          btnError($btn);
        }
      }
    });
  }

  function btnSuccess($btn, response) {
    $btn.removeClass('loading').addClass('added').html(checkSVG + ' Added!');

    if (response && response.fragments) {
      $.each(response.fragments, function(key, value) {
        $(key).replaceWith(value);
      });
    }

    $(document.body).trigger('wc_fragment_refresh');
    if (response) {
      $(document.body).trigger('added_to_cart', [
        response.fragments || {},
        response.cart_hash || '',
        $btn
      ]);
    }

    setTimeout(function() {
      $btn.removeClass('added').html(cartIconSVG + ' Add to cart');
    }, 2500);
  }

  function btnError($btn) {
    $btn.removeClass('loading')
      .css({
        background: '#dc2626',
        color: '#fff'
      })
      .html(
        '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">' +
        '<circle cx="12" cy="12" r="10"/>' +
        '<line x1="12" y1="8" x2="12" y2="12"/>' +
        '<line x1="12" y1="16" x2="12.01" y2="16"/>' +
        '</svg> Failed'
      );
    setTimeout(function() {
      $btn.css({
        background: '',
        color: ''
      }).html(cartIconSVG + ' Add to cart');
    }, 2500);
  }

  function positionPopup(badgeEl) {
    var popup = $('#citation-popup');
    var rect = badgeEl.getBoundingClientRect();
    var popupW = popup.outerWidth();
    var popupH = popup.outerHeight();
    var viewportW = window.innerWidth;
    var viewportH = window.innerHeight;
    var left, top, arrowSide;

    if (rect.left + rect.width + 10 + popupW <= viewportW - 12) {
      left = rect.left + rect.width + 10;
      top = rect.top - 10;
      arrowSide = 'left';
    } else if (rect.left - popupW - 10 >= 12) {
      left = rect.left - popupW - 10;
      top = rect.top - 10;
      arrowSide = 'right';
    } else {
      left = Math.max(8, Math.min(rect.left, viewportW - popupW - 8));
      top = rect.top + rect.height + 8;
      arrowSide = 'top';
    }

    if (top + popupH > viewportH - 8) {
      top = rect.top - popupH - 8;
      if (arrowSide === 'top') arrowSide = 'bottom';
    }
    if (top < 8) top = 8;

    $('#citation-popup-arrow').attr('class', '').addClass('arrow-' + arrowSide);
    popup.css({
      position: 'fixed',
      top: top,
      left: left
    });
  }

  function closePopup() {
    $('#citation-popup').fadeOut(120);
    activeBadge = null;
  }

  function renderPopupFallback(url) {
    var isTitle = !url.startsWith('http');
    var href = appendChatContextToUrl(url);
    $('#citation-popup-content').html(
      isTitle ?
      '<div class="citation-document-space"><span>Source: <strong>' + url + '</strong></span></div>' :
      '<a href="' + href + '" target="_blank" rel="noopener" class="citation-link">' + url + '</a>'
    );
  }

  function renderPopupLoading() {
    $('#citation-popup-content').html(
      '<div class="citation-wp-loading">' +
      '<span class="citation-wp-spinner"></span>' +
      '<span>Loading…</span>' +
      '</div>'
    );
  }

  function renderPopupWP(data, url) {
    var html = '<div class="citation-wp-content">';
    if (url) {
      var title = (data && data.title) ? data.title : url;
      html += '<a href="' + appendChatContextToUrl(url) + '" target="_blank" rel="noopener" class="citation-link">' + title + '</a>';
    }
    html += '</div>';
    $('#citation-popup-content').html(html);
  }

  function showPopup(badgeEl) {
    var popup = $('#citation-popup');
    popup.css({
      visibility: 'hidden',
      display: 'block'
    });
    positionPopup(badgeEl);
    popup.css({
      visibility: 'visible',
      display: 'none'
    }).fadeIn(150);
  }

  function switchPanelToSources() {
    var $panel = $('#mindweco-calendly-panel');
    $panel.addClass('mwc-panel-showing-sources').removeClass('mwc-panel-showing-services');
    $panel.find('.mindweco-calendly-panel-header .mwc-cal-title').text('Sources');
    $panel.find('.mindweco-calendly-panel-header .mwc-cal-sub').text('Referenced pages');
    $panel.find('.mwc-cal-iframe-wrapper').hide();
    $('#mwc-service-view-bar').hide();
    $('#mwc-services-body').hide();
    if ($panel.find('#mwc-sources-body').length === 0) {
      $panel.find('.mwc-cal-iframe-wrapper').after('<div id="mwc-sources-body"></div>');
    }
    $('#mwc-sources-body').show();
  }

  function ensureSourcesBody() {
    var $panel = $('#mindweco-calendly-panel');
    if ($panel.find('#mwc-sources-body').length === 0) {
      $panel.find('.mwc-cal-iframe-wrapper').after('<div id="mwc-sources-body"></div>');
    }
    return $('#mwc-sources-body');
  }

  function clearSourcesPanel() {
    panelSources = {};
    $('#mwc-sources-body').empty().hide();
  }

  function showEmptySourcesPanel() {
    var $body = ensureSourcesBody();
    panelSources = {};
    $body
      .empty()
      .append('<div class="mwc-source-empty">No sources for this answer.</div>');
    switchPanelToSources();
  }

  function switchPanelToCalendly() {
    var $panel = $('#mindweco-calendly-panel');
    $panel.addClass('mwc-panel-showing-services').removeClass('mwc-panel-showing-sources');
    $panel.find('.mindweco-calendly-panel-header .mwc-cal-title').text('Services & Options');
    $panel.find('.mindweco-calendly-panel-header .mwc-cal-sub').text('Choose what suits you best');
    $('#mwc-sources-body').hide();
    $panel.find('.mwc-cal-iframe-wrapper').show();
  }

  function openSourcesPanel() {
    var isMaximized = $('#mindweco-container').hasClass('maximized');
    if (!isMaximized) return;

    var $panel = $('#mindweco-calendly-panel');
    var $root = $('#mindweb-mindweco-root');
    var $closeBtn = $('.mindweco-close');
    var $chatPanel = $('#mindweco-container');
    var isMobileView = window.matchMedia('(max-width: 768px)').matches;

    switchPanelToSources();
    if ($panel.is(':visible')) return;

    $root.addClass('calendly-open');
    if (isMobileView) $chatPanel.css('display', 'none');
    if (!isMobileView) $closeBtn.hide();

    $panel
      .css('display', 'flex')
      .removeClass('mwc-leaving mwc-resize-mode')
      .addClass('mwc-entering');

    $panel.one('animationend webkitAnimationEnd', function() {
      $panel.removeClass('mwc-entering');
    });
  }

  function buildSourceCard(data, url, nums) {
    var numBadgeHtml = '';
    if (nums && nums.length) {
      var uniqueNums = [];
      var seenNums = {};
      nums.forEach(function(n) {
        var numStr = String(n);
        if (!seenNums[numStr]) {
          seenNums[numStr] = true;
          uniqueNums.push(numStr);
        }
      });
      uniqueNums.sort(function(a, b) {
        return parseInt(a) - parseInt(b);
      });
      numBadgeHtml = uniqueNums.map(function(n) {
        return '<span class="mwc-cite-num-badge">' + n + '</span>';
      }).join('');
    }
    var $card = $('<a class="mwc-source-card" target="_blank" rel="noopener"></a>');
    $card.attr('href', appendChatContextToUrl(data.url || url));
    $card.attr('data-source-url', url);

    if (data.type === 'wc_cart') {
      var html = '<div class="mwc-source-card-body mwc-wc-special">';
      html += '<div class="mwc-wc-special-header">🛒 ' + data.title + numBadgeHtml + '</div>';
      html += '<div class="mwc-wc-special-meta">' + data.item_count + ' items · ' + data.total + '</div>';
      if (data.items && data.items.length > 0) {
        html += '<div class="mwc-wc-mini-list">';
        data.items.forEach(function(item) {
          html += '<div class="mwc-wc-mini-item">';
          if (item.image) html += '<img src="' + item.image + '" alt="">';
          html += '<div class="mwc-wc-mini-item-info">';
          html += '<span class="mwc-wc-mini-item-title">' + item.title + '</span>';
          html += '<span class="mwc-wc-mini-item-price">' + item.price;
          if (item.quantity > 1) html += ' <em>x' + item.quantity + '</em>';
          html += '</span></div></div>';
        });
        html += '</div>';
      } else {
        html += '<div class="mwc-wc-empty">Cart is empty</div>';
      }
      html += '<span class="mwc-wc-cta">View Cart →</span></div>';
      $card.addClass('mwc-source-card--wc-special').html(html);
      return $card;
    }

    if (data.type === 'wc_shop') {
      var html = '<div class="mwc-source-card-body mwc-wc-special">';
      html += '<div class="mwc-wc-special-header">🏪 ' + data.title + numBadgeHtml + '</div>';
      html += '<span class="mwc-wc-special-header-subtitle"> ' + data.subtitle + '</div>';
      if (data.products && data.products.length > 0) {
        html += '<div class="mwc-wc-product-grid">';
        data.products.forEach(function(p) {
          html += '<a class="mwc-wc-grid-item" href="' + appendChatContextToUrl(p.url) + '" target="_blank" rel="noopener">';
          if (p.image) html += '<img src="' + p.image + '" alt="">';
          html += '<span class="mwc-wc-grid-title">' + p.title + '</span>';
          html += '<span class="mwc-wc-grid-price">' + p.price + '</span>';
          html += '</a>';
        });
        html += '</div>';
      }
      html += '<span class="mwc-wc-cta">Browse Shop →</span></div>';
      $card.addClass('mwc-source-card--wc-special').html(html);
      return $card;
    }

    if (data.type === 'wc_checkout') {
      var html = '<div class="mwc-source-card-body mwc-wc-special">';
      html += '<div class="mwc-wc-special-header">💳 ' + data.title + numBadgeHtml + '</div>';
      html += '<div class="mwc-wc-special-meta">' + data.items + ' items · ' + data.total + '</div>';
      html += '<span class="mwc-wc-cta">Go to Checkout →</span></div>';
      $card.addClass('mwc-source-card--wc-special').html(html);
      return $card;
    }

    if (data.type === 'product') {
      var inStock = data.in_stock;
      var stockBadge = inStock ?
        '<span style="background:#E1F5EE;color:#085041;font-size:10px;padding:2px 8px;border-radius:100px;">In stock</span>' :
        '<span style="background:#FCEBEB;color:#501313;font-size:10px;padding:2px 8px;border-radius:100px;">Out of stock</span>';

      var html = '';
      if (data.image) {
        html += '<div class="mwc-source-card-img-wrap">' +
          '<img class="mwc-source-card-img" src="' + data.image + '" alt="' + (data.title || '') + '" ' +
          'onerror="this.parentElement.style.display=\'none\';" />' +
          '</div>';
      }
      html += '<div class="mwc-source-card-body">';
      html += '<span class="mwc-source-card-title">' + (data.title || '') + numBadgeHtml + '</span>';
      if (data.price) html += '<span class="mwc-source-card-price">' + data.price + '</span>';
      if (data.excerpt) html += '<span class="mwc-source-card-excerpt">' + data.excerpt + '</span>';
      html += '<div class="mwc-source-card-footer">' + stockBadge;
      if (inStock && data.product_id) {
        html += '<button class="mwc-add-to-cart-btn" data-product-id="' + data.product_id + '">' +
          cartIconSVG + ' Add to cart</button>';
      }
      html += '</div>';
      html += '</div>';
      $card.html(html);
      return $card;
    }

    if (data.type === 'post' || data.type === 'page') {
      var html = '';
      if (data.image) {
        html += '<div class="mwc-source-card-img-wrap">' +
          '<img class="mwc-source-card-img" src="' + data.image + '" alt="' + (data.title || '') + '" ' +
          'onerror="this.parentElement.style.display=\'none\';" />' +
          '</div>';
      }
      html += '<div class="mwc-source-card-body">';
      html += '<span class="mwc-source-card-title">' + (data.title || '') + numBadgeHtml + '</span>';
      if (data.excerpt) html += '<span class="mwc-source-card-excerpt">' + data.excerpt + '</span>';
      html += '<span class="mwc-wc-cta">Read more →</span>';
      html += '</div>';
      $card.html(html);
      return $card;
    }

    if (data.type === 'smartmind') {
      var file = getDocumentInfo(url);
      var $card = $('<div class="mwc-source-card mwc-source-card--smartmind"></div>');
      var html = '<div class="mwc-source-card-body mwc-smartmind-card">';
      html += `<div class="mwc-smartmind-header">🗂 ${file.docType} ${numBadgeHtml}</div>`;
      html += `<div class="mwc-smartmind-filename">
                <span class="smartmind-document-filename"> ${file.fileName} </span>
                <a href="https://spaces.smartmind.services/" target="_blank" rel="noopener"> View More in Mind Spaces ↗ </a></div>`;
      html += '</div>';
      $card.addClass('mwc-source-card--smartmind').html(html);
      return $card;
    }

    if (data.type === 'attachment') {
      var file = getDocumentInfo(url);
      var $card = $('<a class="mwc-source-card" target="_blank" rel="noopener"></a>');
      $card.attr('href', appendChatContextToUrl(url));
      $card.attr('data-source-url', url);

      var title = data.title || file.fileName;
      var html = '<div class="mwc-source-card-body mwc-document-source">';
      html += '<div class="mwc-document-source-header">';
      html += '<span class="mwc-document-source-type">' + file.docType + '</span>';
      html += '<span class="mwc-document-source-badges">' + numBadgeHtml + '</span>';
      html += '</div>';
      html += '<span class="mwc-source-card-title">' + title + '</span>';
      html += '<span class="mwc-source-card-excerpt">' + file.fileName + '</span>';
      html += '<span class="mwc-wc-cta">Open document</span>';
      html += '</div>';
      $card.html(html);
      return $card;
    }

    if (data.type === 'external') {
      var host = url;
      try {
        host = new URL(url).hostname;
      } catch (e) {}

      var html = '<div class="mwc-source-card-body">';
      html += '<span class="mwc-source-card-title">' + host + numBadgeHtml + '</span>';
      html += '<span class="mwc-source-card-excerpt">' + url + '</span>';
      html += '<span class="mwc-wc-cta">Open source</span>';
      html += '</div>';
      $card.html(html);
      return $card;
    }

    $card.html('<div class="mwc-source-card-body">Unknown source</div>');
    return $card;
  }

  async function enrichMessageBadges($messageContent, sourcesMap, options) {
    options = options || {};
    var updatePanel = options.updatePanel !== false;

    var badges = $messageContent.find('.mindweco-citation-badge[data-url]');
    var urls = {};
    var sourceMetaByNum = {};

    Object.keys(sourcesMap || {}).forEach(function(num) {
      var source = sourcesMap[num];
      if (!source) return;

      var url = typeof source === 'string' ? source : (source.url || source.title || null);
      if (!url) return;

      sourceMetaByNum[String(num)] = {
        url: url,
        itemId: getSourceItemId(source) ? String(getSourceItemId(source)) : null
      };
    });

    removeDuplicateItemBadges($messageContent, sourceMetaByNum);
    badges = $messageContent.find('.mindweco-citation-badge[data-url]');

    if (badges.length === 0 && Object.keys(urls).length === 0) {
      if (updatePanel) {
        if ($('#mwc-sources-body').is(':visible')) {
          showEmptySourcesPanel();
        } else {
          clearSourcesPanel();
        }
      }
      return;
    }

    badges.each(function() {
      var url = $(this).data('url');
      var num = $(this).data('num');
      if (!url) return;
      if (!urls[url]) urls[url] = [];
      if (num && urls[url].indexOf(String(num)) === -1) urls[url].push(String(num));
    });

    if (Object.keys(urls).length === 0) return;

    revealPendingBadges($messageContent);

    var hasServices = !!mindwecoData?.show_calendly && mindwecoData.calendly_url;

    var fetchedDataByUrl = {};
    var fetches = Object.keys(urls).map(async function(url) {
      if (url.includes('spaces.smartmind.services')) {
        fetchedDataByUrl[url] = { type: 'smartmind' };
        findBadgesByUrl($messageContent, url)
          .each(function() { $(this).data('wp', { type: 'smartmind' }); });
        return;
      }
      var data = await fetchWPPostData(url);
      if (data) {
        fetchedDataByUrl[url] = data;
        findBadgesByUrl($messageContent, url)
          .each(function() { $(this).data('wp', data); });
      }
    });

    await Promise.all(fetches);
    revealPendingBadges($messageContent);

    if (!updatePanel) {
      return;
    }

    var wasSourcesVisible = $('#mwc-sources-body').is(':visible');
    var isMaximized = $('#mindweco-container').hasClass('maximized');

    if (wasSourcesVisible || (!hasServices && isMaximized)) {
      switchPanelToSources();
    } else {
      ensureSourcesBody().hide();
    }

    var $body = ensureSourcesBody();
    panelSources = {};
    $body.empty();

    var groupedSources = {};
    var renderedBadges = $messageContent.find('.mindweco-citation-badge[data-url]');

    if (renderedBadges.length) {
      renderedBadges.each(function() {
        var $badge = $(this);
        var url = $badge.data('url');
        var num = String($badge.data('num') || $badge.text() || '');
        if (!url || !num) return;

        var meta = sourceMetaByNum[num] || {};
        var itemId = meta.itemId || null;
        var key = itemId ? ('item:' + itemId) : ('url:' + url);

        if (!groupedSources[key]) {
          groupedSources[key] = {
            url: url,
            nums: [num],
            itemId: itemId
          };
        }
      });
    } else {
      Object.keys(urls).forEach(function(url) {
        urls[url].forEach(function(num) {
          var meta = sourceMetaByNum[String(num)] || {};
          var itemId = meta.itemId || null;
          var key = itemId ? ('item:' + itemId) : ('url:' + url);

          if (!groupedSources[key]) {
            groupedSources[key] = {
              url: url,
              nums: [],
              itemId: itemId
            };
          }

          if (groupedSources[key].nums.indexOf(String(num)) === -1) {
            groupedSources[key].nums.push(String(num));
          }

          if (!groupedSources[key].url || !fetchedDataByUrl[groupedSources[key].url]) {
            groupedSources[key].url = url;
          }
        });
      });
    }

    Object.keys(groupedSources).forEach(function(key) {
      var sourceGroup = groupedSources[key];
      var url = sourceGroup.url;
      var nums = sourceGroup.nums.sort(function(a, b) {
        return parseInt(a) - parseInt(b);
      });
      nums = nums.length ? [nums[0]] : [];
      if (panelSources[key]) return;
      panelSources[key] = true;

      var $badge = findBadgesByUrl($messageContent, url).first();
      var data = fetchedDataByUrl[url] || $badge.data('wp');

      if (!data && url.includes('spaces.smartmind.services')) {
        data = { type: 'smartmind' };
      }
      if (!data) {
        data = { type: 'external', url: url };
      }

      var $card = buildSourceCard(data, url, nums);
      $card.addClass('mwc-card-loading');
      $body.append($card);
    });

  }

  function renderWithCitations(text, sourcesMap, options) {
    sourcesMap = sourcesMap || {};
    options = options || {};
    var cleanText = window.MindwecoHelpers.cleanBotText(text);
    var messageId = window.MindwecoHelpers.generateMessageId(cleanText, 'bot');

    if (Object.keys(sourcesMap).length === 0) {
      try {
        var stored = localStorage.getItem('cit_' + messageId);
        if (stored) {
          var parsed = JSON.parse(stored);
          Object.keys(parsed).forEach(function(k) {
            sourcesMap[String(k)] = parsed[k];
          });
        }
      } catch (e) {}
    }


    function getUrl(num) {
      var v = sourcesMap[num] || sourcesMap[parseInt(num)];
      if (!v) return null;
      if (typeof v === 'string') return v;
      return v.url || v.title || null;
    }

    function getItemId(num) {
      var v = sourcesMap[num] || sourcesMap[parseInt(num)];
      return getSourceItemId(v);
    }

    function getGroupKey(num) {
      var url = getUrl(num);
      var itemId = getItemId(num);

      if (itemId) {
        return 'item:' + itemId;
      }

      if (url) {
        return 'url:' + url;
      }

      return null;
    }

    var itemIdToFirstNum = {};
    var urlToFirstNum = {};
    var groupToFirstNum = {};

    Object.keys(sourcesMap)
      .sort(function(a, b) { return parseInt(a) - parseInt(b); })
      .forEach(function(num) {
        var url = getUrl(num);
        var itemId = getItemId(num);
        var groupKey = getGroupKey(num);

        if (groupKey && groupToFirstNum[groupKey] === undefined) {
          groupToFirstNum[groupKey] = num;
        }

        if (itemId) {
          if (itemIdToFirstNum[itemId] === undefined) {
            itemIdToFirstNum[itemId] = num;
          }
        } else if (url) {
          if (urlToFirstNum[url] === undefined) {
            urlToFirstNum[url] = num;
          }
        }
      });

    var renderedKeys = {};

    cleanText = cleanText.replace(/\[(\d+)\]/g, function(match, num) {
      var url = getUrl(num);
      var groupKey = getGroupKey(num);

      if (!groupKey) return '';

      if (renderedKeys[groupKey] !== undefined) {
        return '';
      }

      renderedKeys[groupKey] = num;

      var canonical = groupToFirstNum[groupKey] || urlToFirstNum[url] || num;

      return '<span class="mindweco-citation-badge"' +
        (url ? ' data-url="' + escapeAttr(url) + '"' : '') +
        ' data-num="' + canonical + '"' +
        '>' + canonical + '</span>';
    });

    if (!options.preserveMarkdown) {
      cleanText = cleanText.replace(/\n/g, '<br>');
    }

    return cleanText;
  }

  function getDocumentInfo(u) {
    var fileName = u.split('/').pop() || 'Untitled';
    var extension = fileName.split('.').pop().toLowerCase();
    var docType = 'Document';
    switch (extension) {
      case 'pdf':
        docType = 'PDF Document';
        break;
      case 'doc':
      case 'docx':
        docType = 'Word Document';
        break;
      case 'xls':
      case 'xlsx':
        docType = 'Excel Document';
        break;
      case 'ppt':
      case 'pptx':
        docType = 'PowerPoint Document';
        break;
    }
    return {
      fileName,
      docType
    };
  }

  function init() {

    if (!document.getElementById('mwc-spin-style')) {
      var style = document.createElement('style');
      style.id = 'mwc-spin-style';
      style.textContent = '@keyframes mwc-spin { to { transform: rotate(360deg); } }';
      document.head.appendChild(style);
    }

    $(document).on('click', '.mwc-add-to-cart-btn', function(e) {
      e.preventDefault();
      e.stopPropagation();
      var $btn = $(this);
      var productId = $btn.data('product-id');
      if (!productId) return;
      ajaxAddToCart($btn, productId);
    });

    $(document).on('click', '.mindweco-citation-badge', function(e) {
      e.stopPropagation();
      var $badge = $(this);
      var url = $badge.data('url');
      var popup = $('#citation-popup');
      if (!url) return;

      if (popup.is(':visible') && activeBadge === this) {
        closePopup();
        return;
      }
      activeBadge = this;

      if (url.includes('https://spaces.smartmind.services')) {
        var file = getDocumentInfo(url);
        $('#citation-popup-content').html(`
            <div class="citation-document-space">
                <span>The information is taken from <strong>${file.docType}</strong> in Mind Spaces:</span>
                <div style="margin-top:4px;"><strong>${file.fileName}</strong></div>
            </div>
        `);
        showPopup(this);
        return;
      }

      if (!url.startsWith('http')) {
        $('#citation-popup-content').html(
          '<div class="citation-document-space"><span>The information is taken from: <strong>' + url + '</strong></span></div>'
        );
        showPopup(this);
        return;
      }

      var wp = $badge.data('wp');
      if (wp) {
        renderPopupWP(wp, url);
        showPopup(this);
      } else {
        renderPopupLoading();
        showPopup(this);
        var self = this;
        fetchWPPostData(url).then(function(data) {
          if (activeBadge !== self) return;
          if (data) {
            $badge.data('wp', data);
            renderPopupWP(data, url);
          } else {
            renderPopupFallback(url);
          }
          positionPopup(self);
        });
      }
    });

    $(document).on('click', '.citation-link', closePopup);
    $(document).on('click', '#close-citation', function(e) {
      e.preventDefault();
      e.stopPropagation();
      closePopup();
    });
    $(document).on('click', function(e) {
      if (!$(e.target).closest('.mindweco-citation-badge, #citation-popup').length) closePopup();
    });
    $('#mindweco-messages').on('scroll', closePopup);

    $(document).on('click', '#mindweco-calendly-close', function() {
      var $panel = $('#mindweco-calendly-panel');
      var $root = $('#mindweb-mindweco-root');
      var $closeBtn = $('.mindweco-close');
      var $chatPanel = $('#mindweco-container');
      var isMobileView = window.matchMedia('(max-width: 768px)').matches;
      var hasCalendly = !!mindwecoData?.show_calendly &&
        mindwecoData.calendly_url;

      if (hasCalendly) {
        if (window.MindwecoUI && window.MindwecoUI.closeCalendly) {
          window.MindwecoUI.closeCalendly();
        }
        return;
      }

      $panel.removeClass('mwc-entering').addClass('mwc-leaving');
      var done = false;

      function finish() {
        if (done) return;
        done = true;
        $panel.css('display', 'none').removeClass('mwc-leaving');
        $root.removeClass('calendly-open');
        $closeBtn.show();
        if (isMobileView) $chatPanel.css('display', 'flex');
      }
      $panel.one('animationend webkitAnimationEnd', finish);
      setTimeout(finish, 420);
    });

    $(document).on('click', '#confirmNewChatBtn', function() {
      var isMobileView = window.matchMedia('(max-width: 768px)').matches;
      var $chatPanel = $('#mindweco-container');
      var hasCalendly = !!mindwecoData?.show_calendly &&
        mindwecoData.calendly_url;

      panelSources = {};
      $('#mwc-sources-body').empty();
      closePopup();

      if (!hasCalendly) {
        $('#mindweco-calendly-panel').css('display', 'none');
        $('#mindweb-mindweco-root').removeClass('calendly-open');
        $('.mindweco-close').show();
        if (isMobileView) $chatPanel.css('display', 'flex');
      }
    });
  }

  window.MindwecoCitations = {
    init: init,
    render: renderWithCitations,
    enrich: enrichMessageBadges,
    switchToCalendly: switchPanelToCalendly,
    switchToSources: switchPanelToSources,
    clearPanel: clearSourcesPanel,
    _fetchWP: fetchWPPostData
  };

})(jQuery);
