(() => {
  if (window.__PULSE_CHAT_BALANCE_CONTENT__) return;
  window.__PULSE_CHAT_BALANCE_CONTENT__ = true;

  let messagePricesData = new Map();
  let paidMessageIds = new Set();
  let isChatBalanceEnabled = true;

  const CHAT_BODY_SELECTOR = '[data-testid="chat-body"]';
  const PRICE_INJECT_DEBOUNCE_MS = 500;
  const SUMMARY_CONTAINER_STYLE = [
    'margin-left: 8px',
    'display: inline-flex',
    'align-items: center',
    'gap: 6px',
    'padding: 2px 8px',
    'border-radius: 999px',
    'font-size: 11px',
    'font-weight: 600',
    'line-height: 1.2',
    "font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
    'background: rgba(73, 89, 113, 0.08)',
    'border: 1px solid rgba(90, 108, 134, 0.16)',
    'color: #5c6a80',
    'vertical-align: middle',
    'white-space: nowrap'
  ].join(';');
  const SUMMARY_VALUE_BASE_STYLE = [
    'font-weight: 700',
    'letter-spacing: .01em'
  ].join(';');
  const PAID_BADGE_STYLE = [
    'margin-left: 8px',
    'display: inline-flex',
    'align-items: center',
    'padding: 2px 8px',
    'border-radius: 999px',
    'font-size: 11px',
    'font-weight: 700',
    'line-height: 1.2',
    "font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
    'color: #c2410c',
    'background: rgba(251, 191, 36, 0.16)',
    'border: 1px solid rgba(245, 158, 11, 0.24)',
    'vertical-align: middle',
    'white-space: nowrap'
  ].join(';');

  function removeInjectedBalanceUi() {
    try {
      document.querySelectorAll('.alpha-finder-message-price-container, .alpha-finder-message-paid').forEach((node) => node.remove());
    } catch {}
  }

  function isCreditsValuePresent(val) {
    return val !== void 0 && val !== null && val !== '';
  }

  function formatNumericValue(val) {
    if (!isCreditsValuePresent(val)) return '—';
    const numeric = Number(val);
    if (Number.isFinite(numeric)) {
      if (Number.isInteger(numeric)) return String(numeric);
      return numeric.toFixed(2).replace(/\.00$/, '').replace(/(\.\d)0$/, '$1');
    }
    return String(val);
  }

  function formatCreditsValue(val) {
    return `${formatNumericValue(val)} cr`;
  }

  function ensurePart(container, className, labelText, valueText, valueStyle = '') {
    let part = container.querySelector(`.${className}`);
    if (!part) {
      part = document.createElement('span');
      part.className = className;
      part.style.cssText = 'display:inline-flex;align-items:center;gap:3px;';

      const label = document.createElement('span');
      label.className = `${className}-label`;
      label.textContent = labelText;
      label.style.cssText = 'opacity:.72;';
      part.appendChild(label);

      const value = document.createElement('span');
      value.className = `${className}-value`;
      value.style.cssText = `${SUMMARY_VALUE_BASE_STYLE};${valueStyle}`;
      part.appendChild(value);

      container.appendChild(part);
    }

    const labelEl = part.querySelector(`.${className}-label`);
    const valueEl = part.querySelector(`.${className}-value`);
    if (labelEl) labelEl.textContent = labelText;
    if (valueEl) {
      valueEl.textContent = valueText;
      valueEl.style.cssText = `${SUMMARY_VALUE_BASE_STYLE};${valueStyle}`;
    }
    return part;
  }

  function ensureDot(container, className) {
    let dot = container.querySelector(`.${className}`);
    if (!dot) {
      dot = document.createElement('span');
      dot.className = className;
      dot.textContent = '·';
      dot.style.cssText = 'opacity:.38;';
      container.appendChild(dot);
    }
    return dot;
  }

  function buildSummaryTitle(price, spendActive, spendAll) {
    return `Credits: ${formatNumericValue(price)} | Chat spend: ${formatNumericValue(spendActive)} | Total spend: ${formatNumericValue(spendAll)}`;
  }

  function updateCreditsBadges(container, price, spendActive, spendAll) {
    container.style.cssText = SUMMARY_CONTAINER_STYLE;
    container.title = buildSummaryTitle(price, spendActive, spendAll);

    ensurePart(container, 'alpha-finder-message-price', '💰', formatCreditsValue(price), 'color:#8a5a14;');
    ensureDot(container, 'alpha-finder-message-dot-1');
    ensurePart(container, 'alpha-finder-message-spend-active', 'chat', formatNumericValue(spendActive), 'color:#2563eb;');
    ensureDot(container, 'alpha-finder-message-dot-2');
    ensurePart(container, 'alpha-finder-message-spend-all', 'total', formatNumericValue(spendAll), 'color:#7c3aed;');
  }

  const injectPriceIntoMessage = (messageId, data) => {
    if (!isChatBalanceEnabled) return false;

    const messageElement = document.getElementById(`mess-${messageId}`);
    if (!messageElement) return false;

    const messageInfoElement = messageElement.querySelector('[data-testid="message-date"]');
    if (!messageInfoElement) return false;

    const { price, spend_active_credits, spend_all_credits } = data;
    let container = messageElement.querySelector('.alpha-finder-message-price-container');
    if (!container) {
      container = document.createElement('span');
      container.className = 'alpha-finder-message-price-container';
      messageInfoElement.appendChild(container);
    }

    updateCreditsBadges(container, price, spend_active_credits, spend_all_credits);
    return true;
  };

  const injectPaidLabelIntoMessage = (messageId) => {
    if (!isChatBalanceEnabled) return false;

    const messageElement = document.getElementById(`mess-${messageId}`);
    if (!messageElement) return false;

    const messageInfoElement = messageElement.querySelector('[data-testid="message-date"]');
    if (!messageInfoElement) return false;

    let paidSpan = messageElement.querySelector('.alpha-finder-message-paid');
    if (!paidSpan) {
      paidSpan = document.createElement('span');
      paidSpan.className = 'alpha-finder-message-paid';
      messageInfoElement.appendChild(paidSpan);
    }

    paidSpan.textContent = 'Paid';
    paidSpan.style.cssText = PAID_BADGE_STYLE;
    return true;
  };

  const processStoredPrices = () => {
    let injectedCount = 0;
    let notFoundCount = 0;
    messagePricesData.forEach((data, messageId) => {
      if (injectPriceIntoMessage(messageId, data)) injectedCount++;
      else notFoundCount++;
    });
    return { injected: injectedCount, notFound: notFoundCount };
  };

  const processStoredPaidMessages = () => {
    let injectedCount = 0;
    let notFoundCount = 0;
    paidMessageIds.forEach((messageId) => {
      if (injectPaidLabelIntoMessage(messageId)) injectedCount++;
      else notFoundCount++;
    });
    return { injected: injectedCount, notFound: notFoundCount };
  };

  const watchForMessageElements = () => {
    let processedMessages = new Set();
    let processedPaidMessages = new Set();
    let debounceTimer = null;

    const tryInjectPrices = () => {
      if (!isChatBalanceEnabled) return;
      if (messagePricesData.size === 0 && paidMessageIds.size === 0) return;

      const pendingPrices = [...messagePricesData.keys()].filter((id) => !processedMessages.has(id));
      const pendingPaid = [...paidMessageIds].filter((id) => !processedPaidMessages.has(id));
      if (pendingPrices.length === 0 && pendingPaid.length === 0) return;

      for (const messageId of pendingPrices) {
        const data = messagePricesData.get(messageId);
        if (data && injectPriceIntoMessage(messageId, data)) processedMessages.add(messageId);
      }
      for (const messageId of pendingPaid) {
        if (injectPaidLabelIntoMessage(messageId)) processedPaidMessages.add(messageId);
      }
    };

    const scheduleTryInject = () => {
      if (debounceTimer) clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => {
        debounceTimer = null;
        tryInjectPrices();
      }, PRICE_INJECT_DEBOUNCE_MS);
    };

    tryInjectPrices();
    setTimeout(tryInjectPrices, 10000);
    setTimeout(tryInjectPrices, 15000);

    const target = document.querySelector(CHAT_BODY_SELECTOR) || document.body;
    const observer = new MutationObserver(() => {
      scheduleTryInject();
    });
    observer.observe(target, { childList: true, subtree: true });
    return observer;
  };

  const setupMessageListener = () => {
    window.addEventListener('message', (event) => {
      if (event.source !== window) return;

      if (event.data && event.data.type === 'CHAT_HISTORY_PRICE_DATA') {
        const messagePrices = event.data.messagePrices;
        if (Array.isArray(messagePrices) && messagePrices.length > 0) {
          messagePrices.forEach((msg) => {
            if (msg.id && msg.price !== void 0) {
              messagePricesData.set(msg.id, {
                price: msg.price,
                spend_active_credits: msg.spend_active_credits,
                spend_all_credits: msg.spend_all_credits
              });
            }
          });
          if (isChatBalanceEnabled) setTimeout(() => processStoredPrices(), 500);
        }
      }

      if (event.data && event.data.type === 'CHAT_HISTORY_PAID_DATA') {
        const paidMessageIdsArray = event.data.paidMessageIds;
        if (Array.isArray(paidMessageIdsArray) && paidMessageIdsArray.length > 0) {
          paidMessageIdsArray.forEach((messageId) => {
            if (messageId) paidMessageIds.add(messageId);
          });
          if (isChatBalanceEnabled) setTimeout(() => processStoredPaidMessages(), 500);
        }
      }
    });
  };

  function requestStoredData() {
    try {
      window.postMessage({ type: 'REQUEST_CHAT_HISTORY_BALANCE_DATA' }, location.origin);
    } catch {
      try {
        window.postMessage({ type: 'REQUEST_CHAT_HISTORY_BALANCE_DATA' }, '*');
      } catch {}
    }
  }

  function applyEnabledState(nextValue) {
    isChatBalanceEnabled = !!nextValue;
    if (!isChatBalanceEnabled) {
      removeInjectedBalanceUi();
      return;
    }
    processStoredPrices();
    processStoredPaidMessages();
    requestStoredData();
  }

  function refreshEnabledState() {
    try {
      chrome.storage.local.get(['enableChatBalance', 'pulsarAuth'], (result) => {
        const authData = result && result.pulsarAuth;
        const isAuthed = !!(authData && authData.authenticated && authData.token);
        const enabled = isAuthed && result && result.enableChatBalance !== undefined ? result.enableChatBalance === true : isAuthed;
        applyEnabledState(enabled);
      });
    } catch {
      applyEnabledState(true);
    }
  }

  function init() {
    if (!window.location.href.includes('alpha.date')) return;
    setupMessageListener();
    watchForMessageElements();
    refreshEnabledState();

    try {
      chrome.storage.onChanged.addListener((changes, areaName) => {
        if (areaName !== 'local') return;
        if (!changes.enableChatBalance && !changes.pulsarAuth) return;
        refreshEnabledState();
      });
    } catch {}
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init, { once: true });
  } else {
    init();
  }
})();
