// Magic 8-Ball for Axiom - Phase 2
// Shows logo initially, click to reveal verdict, click again to re-roll

console.log('[Magic8Ball] Content script loaded');

const CONFIG = {
  PROCESSED_ATTR: 'data-8ball-processed',
  POLL_INTERVAL_MS: 1000,
  LOGO_URL: chrome.runtime.getURL('8ball_logo.jpg'),
  VERDICTS: {
    positive: ['BUY IT', 'LOOKS GOOD', 'SEND IT', 'WAGMI'],
    neutral: ['MAYBE', 'ASK LATER', 'UNCERTAIN', 'DYOR'],
    negative: ['AVOID', 'NOPE', 'RUG ALERT', 'SKETCHY']
  }
};

// Flatten verdicts for random selection
const ALL_VERDICTS = [
  ...CONFIG.VERDICTS.positive.map(v => ({ text: v, type: 'positive' })),
  ...CONFIG.VERDICTS.neutral.map(v => ({ text: v, type: 'neutral' })),
  ...CONFIG.VERDICTS.negative.map(v => ({ text: v, type: 'negative' }))
];

// Selectors for token links
const TOKEN_SELECTORS = [
  'a[href*="/token/"]',
  'a[href*="/meme/"]',
  'a[href*="pump.fun"]',
  'a[href*="bonk.fun"]',
];

let processedCount = 0;

function getRandomVerdict() {
  const index = Math.floor(Math.random() * ALL_VERDICTS.length);
  return ALL_VERDICTS[index];
}

function revealVerdict(badge) {
  const verdict = getRandomVerdict();

  // Clear the image and show text
  badge.innerHTML = '';
  badge.textContent = verdict.text;
  badge.dataset.verdictType = verdict.type;
  badge.dataset.revealed = 'true';
  badge.classList.add('magic8ball-badge--revealed');
}

function handleBadgeClick(e, badge) {
  // Stop the click from navigating
  e.stopPropagation();
  e.preventDefault();

  // Reveal or re-roll
  revealVerdict(badge);
}

function findUnprocessedTokens() {
  const allTokens = [];
  for (const selector of TOKEN_SELECTORS) {
    const elements = document.querySelectorAll(`${selector}:not([${CONFIG.PROCESSED_ATTR}])`);
    allTokens.push(...elements);
  }
  return allTokens;
}

function injectBadge(element) {
  element.setAttribute(CONFIG.PROCESSED_ATTR, 'true');

  // Create badge container
  const badge = document.createElement('span');
  badge.className = 'magic8ball-badge';
  badge.dataset.revealed = 'false';

  // Create logo image
  const img = document.createElement('img');
  img.src = CONFIG.LOGO_URL;
  img.alt = '8ball';
  img.className = 'magic8ball-logo';
  badge.appendChild(img);

  // Click handler - reveal or re-roll
  badge.addEventListener('click', (e) => handleBadgeClick(e, badge));

  // Insert badge
  try {
    element.appendChild(badge);
    processedCount++;
  } catch (e) {
    console.log('[Magic8Ball] Failed to inject:', e);
  }
}

function processNewTokens() {
  const unprocessed = findUnprocessedTokens();
  if (unprocessed.length > 0) {
    console.log(`[Magic8Ball] Found ${unprocessed.length} new tokens, total: ${processedCount}`);
    unprocessed.forEach(el => injectBadge(el));
  }
}

function init() {
  console.log('[Magic8Ball] Starting...');
  processNewTokens();
  setInterval(processNewTokens, CONFIG.POLL_INTERVAL_MS);
}

setTimeout(init, 500);
