// Content script that runs on the Mining Wars game page
// Listens for WebSocket events and forwards them to the side panel

// Console Interceptor - capture all console output
const CONTENT_CONSOLE_LOG_KEY = 'mw_content_console_log';
const MAX_CONTENT_LOG_SIZE = 100000;

let contentConsoleBuffer = '';

function appendContentConsoleLog(level, args) {
  const timestamp = new Date().toISOString();
  const message = args.map(arg => {
    if (typeof arg === 'object') {
      try {
        return JSON.stringify(arg, null, 2);
      } catch (e) {
        return String(arg);
      }
    }
    return String(arg);
  }).join(' ');

  const logLine = `[${timestamp}] [CONTENT/${level.toUpperCase()}] ${message}\n`;
  contentConsoleBuffer += logLine;

  if (contentConsoleBuffer.length > MAX_CONTENT_LOG_SIZE) {
    contentConsoleBuffer = contentConsoleBuffer.slice(-MAX_CONTENT_LOG_SIZE);
  }

  // Store in chrome.storage.local for cross-context access
  try {
    chrome.storage.local.set({ [CONTENT_CONSOLE_LOG_KEY]: contentConsoleBuffer });
  } catch (e) {
    // Silently fail to avoid infinite loops
  }
}

const originalContentConsole = {
  log: console.log,
  error: console.error,
  warn: console.warn,
  info: console.info,
  debug: console.debug
};

console.log = function(...args) {
  try {
    appendContentConsoleLog('log', args);
  } catch (e) {
    // Silently ignore logging errors
  }
  return originalContentConsole.log.apply(console, args);
};

console.error = function(...args) {
  try {
    appendContentConsoleLog('error', args);
  } catch (e) {
    // Silently ignore logging errors
  }
  return originalContentConsole.error.apply(console, args);
};

console.warn = function(...args) {
  try {
    appendContentConsoleLog('warn', args);
  } catch (e) {
    // Silently ignore logging errors
  }
  return originalContentConsole.warn.apply(console, args);
};

console.info = function(...args) {
  try {
    appendContentConsoleLog('info', args);
  } catch (e) {
    // Silently ignore logging errors
  }
  return originalContentConsole.info.apply(console, args);
};

console.debug = function(...args) {
  try {
    appendContentConsoleLog('debug', args);
  } catch (e) {
    // Silently ignore logging errors
  }
  return originalContentConsole.debug.apply(console, args);
};

// Clear content logs on startup
chrome.storage.local.set({ [CONTENT_CONSOLE_LOG_KEY]: '' });
contentConsoleBuffer = '';

console.log('[MW Redesign] Content script loaded - VERSION 2.0');

// Inject the page hook script into the page context to intercept WebSocket messages
(function injectPageHook() {
  try {
    console.log('[MW Redesign] Starting page hook injection...');
    const script = document.createElement('script');
    const hookUrl = chrome.runtime.getURL('page-hook.js');
    console.log('[MW Redesign] Hook URL:', hookUrl);
    script.src = hookUrl;
    script.onload = function () {
      console.log('[MW Redesign] Page hook script loaded successfully');
      this.remove();
    };
    script.onerror = function (err) {
      console.error('[MW Redesign] Page hook script failed to load:', err);
    };
    const target = document.head || document.documentElement;
    console.log('[MW Redesign] Injecting into:', target.tagName);
    target.appendChild(script);
    console.log('[MW Redesign] Script tag appended');
  } catch (err) {
    console.error('[MW Redesign] Failed to inject page hook:', err);
  }
})();

// Small dedupe cache to avoid forwarding the same page event twice
const _recentForwarded = new Map();

// In-memory forward queue for short service-worker / extension restarts
const FORWARD_QUEUE_MAX = 200;
const FORWARD_QUEUE_FLUSH_INTERVAL = 2000; // ms
const FORWARD_QUEUE = []; // entries: { key, message, ts, attempts }
const FORWARD_QUEUE_KEYS = new Set();

const SESSION_KEY = 'mw_forward_queue_v1';

function safeStringifyMessage(msg) {
  try {
    return JSON.stringify(msg);
  } catch (err) {
    try {
      const minimal = { type: msg?.type ?? null, payload: msg?.payload ?? null, source: msg?.source ?? null };
      return JSON.stringify(minimal);
    } catch (e) {
      return String(msg);
    }
  }
}

function persistForwardQueue() {
  try {
    const payload = FORWARD_QUEUE.map(e => ({ key: e.key, message: safeStringifyMessage(e.message), ts: e.ts, attempts: e.attempts || 0 }));
    sessionStorage.setItem(SESSION_KEY, JSON.stringify(payload));
  } catch (err) {
    console.warn('[MW] persistForwardQueue failed', err);
  }
}

function restoreForwardQueue() {
  try {
    const raw = sessionStorage.getItem(SESSION_KEY);
    if (!raw) return;
    const arr = JSON.parse(raw);
    if (!Array.isArray(arr)) return;
    FORWARD_QUEUE.length = 0; FORWARD_QUEUE_KEYS.clear();
    for (const e of arr.slice(0, FORWARD_QUEUE_MAX)) {
      let msg;
      try {
        msg = JSON.parse(e.message);
      } catch (err) {
        msg = e.message;
      }
      const entry = { key: e.key, message: msg, ts: e.ts || Date.now(), attempts: e.attempts || 0 };
      FORWARD_QUEUE.push(entry);
      FORWARD_QUEUE_KEYS.add(e.key);
    }
    console.log('[MW] Restored forward queue count', FORWARD_QUEUE.length);
  } catch (err) {
    console.warn('[MW] restoreForwardQueue failed', err);
  }
}

window.__persistForwardQueue = persistForwardQueue;
window.__restoreForwardQueue = restoreForwardQueue;

function enqueueForwardMessage(key, message) {
  try {
    if (!key) return false;
    if (FORWARD_QUEUE_KEYS.has(key)) return false; // already queued
    if (FORWARD_QUEUE.length >= FORWARD_QUEUE_MAX) {
      const removed = FORWARD_QUEUE.shift();
      if (removed && removed.key) FORWARD_QUEUE_KEYS.delete(removed.key);
    }
    const entry = { key, message, ts: Date.now(), attempts: 0 };
    FORWARD_QUEUE.push(entry);
    FORWARD_QUEUE_KEYS.add(key);
    persistForwardQueue();
    return true;
  } catch (err) {
    console.warn('[MW Redesign] enqueueForwardMessage failed', err);
    return false;
  }
}

function dequeueForwardMessage() {
  const entry = FORWARD_QUEUE.shift();
  if (entry && entry.key) FORWARD_QUEUE_KEYS.delete(entry.key);
  persistForwardQueue();
  return entry || null;
}

function dumpForwardQueue(limit = 50) {
  return FORWARD_QUEUE.slice(0, limit).map(e => ({ key: e.key, ts: new Date(e.ts).toISOString(), attempts: e.attempts }));
}

window.__dumpForwardQueue = (limit = 50) => { const d = dumpForwardQueue(limit); console.table(d); return d; };
window.__clearForwardQueue = () => { FORWARD_QUEUE.length = 0; FORWARD_QUEUE_KEYS.clear(); persistForwardQueue(); console.log('[MW] Cleared forward queue'); };
window.__flushForwardQueue = () => { flushForwardQueue(); };
function _makeForwardKey(message) {
  const type = message?.type;
  const payload = message.payload ?? message.eventData ?? message.data ?? message;
  if (!payload) return JSON.stringify(message);

  // If this is an ability/boost event, prefer explicit ids to avoid collapsing distinct boosts
  if (type === 'MW_ABILITY_USAGE' || type === 'MW_BOOST_USAGE' || (type === 'MW_WS_EVENT' && typeof message.eventName === 'string' && message.eventName.toLowerCase().includes('ability'))) {
    // Check common id fields at various nesting levels
    const candidates = [
      payload.id,
      payload.eventId,
      payload.abilityId,
      payload.ability_id,
      payload.abilityIdValue,
      payload.timestamp,
      payload.data && (payload.data.id ?? payload.data.eventId ?? payload.data.abilityId)
    ];
    for (const c of candidates) {
      if (c != null) return String(c);
    }
  }

  // Generic fallback for other messages
  const id = payload.id ?? payload.abilityId ?? payload.eventId ?? payload.timestamp ?? payload.roundId;
  if (id != null) return String(id);
  try {
    return JSON.stringify(payload).slice(0, 300);
  } catch (err) {
    return String(payload);
  }
}

// Robust forwarding: avoid noisy logs when extension/service worker is restarting.
// Use exponential backoff with full jitter for transient errors like 'Extension context invalidated'.
const MAX_RETRIES_JITTER = 6; // number of attempts before giving up
const BACKOFF_BASE_MS = 200; // base for exponential multiplier
const BACKOFF_MAX_MS = 5000; // cap for max delay

function backoffDelay(attempt) {
  // attempt starts at 1; compute exponential cap then apply full jitter
  const exp = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * Math.pow(2, Math.max(0, attempt - 1)));
  return Math.floor(Math.random() * exp);
}

function forwardMessage(message) {

  try {
    // Safely compute dedupe key; fall back to stringified payload if _makeForwardKey throws
    let key;
    try {
      key = _makeForwardKey(message);
    } catch (e) {
      console.warn('[MW Redesign] _makeForwardKey failed, falling back to JSON', e);
      try { key = JSON.stringify(message?.payload ?? message).slice(0, 300); } catch (err) { key = String(message); }
    }

    const now = Date.now();

    // Use dedupe cache if available and working; if it throws, skip dedupe for this run
    let skipDedupe = false;
    try {
      if (_recentForwarded && typeof _recentForwarded.has === 'function' && _recentForwarded.has(key)) {
        if (message && (message.type === 'MW_ABILITY_USAGE' || message.type === 'MW_BOOST_USAGE')) {
          console.log('[MW Redesign] Suppressing duplicate forward for ability event, key=', key);
        }
        return;
      }
    } catch (err) {
      console.warn('[MW Redesign] Dedupe cache check failed, skipping dedupe this time', err);
      skipDedupe = true;
    }

    if (!skipDedupe) {
      try {
        _recentForwarded.set(key, now);
      } catch (err) {
        console.warn('[MW Redesign] Failed to update dedupe cache, proceeding without cache', err);
      }
    }

    let attempts = 0;
    const trySend = () => {
      attempts += 1;
      try {
        const p = chrome.runtime.sendMessage(message);
        if (p && typeof p.catch === 'function') {
          p.catch(err => handleSendError(err));
        }
      } catch (err) {
        handleSendError(err);
      }
    };

    const handleSendError = (err) => {
      const msg = (err && err.message) || String(err || '');
      // If extension context is temporarily invalidated, retry with exponential backoff + full jitter
      if (/Extension context invalidated/i.test(msg) && attempts < MAX_RETRIES_JITTER) {
        const delay = backoffDelay(attempts);
        if (delay > 0) setTimeout(trySend, delay);
        else trySend();
        return;
      }

      // If we exhausted retries for the 'invalidated' case, queue the message to send later
      if (/Extension context invalidated/i.test(msg)) {
        const queued = enqueueForwardMessage(key, message);
        console.debug('[MW Redesign] forwardMessage: queued message due to extension restart (retries exhausted)', { key, queued, attempts });
        try { window.__lastForwardMessageError = { ts: Date.now(), message: msg, attempts, queued: !!queued }; } catch (e) {}
        return;
      }

      // Otherwise surface the warning so we can investigate unexpected failures
      console.warn('[MW Redesign] forwardMessage send failed', err);
      try { window.__lastForwardMessageError = { ts: Date.now(), message: msg, attempts }; } catch (e) {}
    };

    // initial attempt
    trySend();
  } catch (err) {
    // Record and limit noisy logs for unexpected throw
    try {
      window.__lastForwardMessageError = { ts: Date.now(), message: String(err), count: (window.__lastForwardMessageError?.count || 0) + 1, stack: err?.stack || null };
    } catch (e) { /* ignore */ }

    if (String(err).includes('Extension context invalidated')) {
      console.debug('[MW Redesign] forwardMessage error (context invalidated)', err);
    } else {
      console.warn('[MW Redesign] forwardMessage error', err);
    }
  }
}

// cleanup recent cache occasionally
setInterval(() => {
  const now = Date.now();
  for (const [k, t] of _recentForwarded.entries()) {
    if (now - t > 5000) _recentForwarded.delete(k);
  }
}, 2000);

// XPath selectors for extracting current round data from DOM
const LIVE_SUMMARY_ROUND_ID_XPATHS = [
  '/html/body/app-root/main/miner-wars/div/div/div/miner-wars-main/miner-wars-game/div/div[1]/div/div[1]/a/div[2]/span',
  '/html/body/app-root/main/miner-wars/div/div/div/miner-wars-main/miner-wars-game/div/div[1]/div/div[1]/a/div[2]'
];

const LIVE_SUMMARY_MULTIPLIER_XPATHS = [
  '/html/body/app-root/main/miner-wars/div/div/div/miner-wars-main/miner-wars-game/div/div[1]/div/div[1]/a/div[3]'
];

const LIVE_SUMMARY_TIMER_XPATHS = [
  '/html/body/app-root/main/miner-wars/div/div/div/miner-wars-main/miner-wars-game/div/div[1]/div/div[2]/div/div',
  '/html/body/app-root/main/miner-wars/div/div/div/miner-wars-main/miner-wars-game/div/div[1]/div/div[2]'
];

const LIVE_SUMMARY_LEAGUE_XPATHS = [
  '/html/body/app-root/main/miner-wars/div/div/div/miner-wars-main/miner-wars-game/div/div[1]/div/div[2]/div[2]',
  '/html/body/app-root/main/miner-wars/div/div/div/miner-wars-main/miner-wars-game/div/div[1]/div/div[2]/div[contains(@class,"league")]',
  '/html/body/app-root/main/miner-wars/div/div/div/miner-wars-main/miner-wars-game/div/div[1]/div/div[2]/div[contains(@class,"miner-wars-main__league")]',
  '/html/body/app-root/main/miner-wars/div/div/div/miner-wars-main/miner-wars-game/div/miner-wars-user-panel/div[1]/div[1]/div/span'
];

// Helper function to get text from XPath
function getTextByXPath(xpaths, contextNode = document) {
  for (const xpath of xpaths) {
    try {
      const resolver = contextNode.createNSResolver(contextNode.documentElement);
      const result = contextNode.evaluate(xpath, contextNode, resolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
      if (result.singleNodeValue && result.singleNodeValue.textContent) {
        return result.singleNodeValue.textContent.trim();
      }
    } catch (err) {
      // Try next XPath
    }
  }
  return null;
}

function getTextBySelector(selectors, contextNode = document) {
  for (const selector of selectors) {
    try {
      const node = contextNode.querySelector(selector);
      if (node && node.textContent) {
        return node.textContent.trim();
      }
    } catch (err) {
      // Try next selector
    }
  }
  return null;
}

function findLeagueTextFallback() {
  try {
    const root = document.querySelector('miner-wars-game') || document.querySelector('miner-wars-main') || document.body;
    if (!root) return null;
    const nodes = root.querySelectorAll('div,span,p');
    const blacklist = new Set(['ROUND', 'MY CLAN', 'SHOP', 'BOOST', 'BOOSTS', 'LEAGUE', 'SECURED', 'BLOCKCHAIN', 'MINER', 'WARS']);
    let scanned = 0;
    for (const node of nodes) {
      if (scanned++ > 400) break;
      const text = node.textContent ? node.textContent.trim() : '';
      if (!text || text.length < 3 || text.length > 20) continue;
      if (!/^[A-Z][A-Z\s]+$/.test(text)) continue;
      if (blacklist.has(text)) continue;
      const rect = node.getBoundingClientRect();
      if (rect.width === 0 || rect.height === 0) continue;
      return text;
    }
  } catch (err) {
    // Ignore fallback errors
  }
  return null;
}

// Poll live summary data from the DOM
let lastLiveSummary = null;
function pollLiveSummary() {
  try {
    const blockId = getTextByXPath(LIVE_SUMMARY_ROUND_ID_XPATHS);
    const multiplier = getTextByXPath(LIVE_SUMMARY_MULTIPLIER_XPATHS);
    const timer = getTextByXPath(LIVE_SUMMARY_TIMER_XPATHS);
    const league = getTextByXPath(LIVE_SUMMARY_LEAGUE_XPATHS) || getTextBySelector([
      '.miner-wars-main__league',
      '.miner-wars-main__info--league',
      '.miner-wars-main__info--left .miner-wars-main__league',
      '.miner-wars-main__info--left .league',
      '[class*="league"]',
      '.miner-wars-main__user-stats.badge-game--alert .text-uppercase',
      'miner-wars-user-panel .badge-game--alert span.text-uppercase'
    ]) || findLeagueTextFallback();

    const normalizedLeague = league ? league.replace(/\s+/g, ' ').trim() : null;

    if (!blockId && !timer) return; // No data available

    const summaryData = {
      blockId: blockId || '-',
      multiplier: multiplier || '1x',
      timer: timer || 'N/A',
      league: normalizedLeague || null,
      timestamp: Date.now()
    };

    // Only send if data changed
    const summaryKey = JSON.stringify(summaryData);
    if (summaryKey === lastLiveSummary) return;
    lastLiveSummary = summaryKey;

    console.log('[MW Redesign] Sending live summary:', summaryData);
    forwardMessage({
      type: 'MW_LIVE_SUMMARY',
      data: summaryData
    });
  } catch (err) {
    console.warn('[MW Redesign] Failed to poll live summary:', err);
  }
}

// Start polling every 2 seconds
setInterval(pollLiveSummary, 2000);
// Poll immediately on load
setTimeout(pollLiveSummary, 1000);

// Attempt to flush queued messages periodically and when the page regains focus
function requeueEntry(entry) {
  try {
    if (!entry || !entry.key) return false;
    if (FORWARD_QUEUE_KEYS.has(entry.key)) return false;
    if (FORWARD_QUEUE.length >= FORWARD_QUEUE_MAX) {
      const removed = FORWARD_QUEUE.shift();
      if (removed && removed.key) FORWARD_QUEUE_KEYS.delete(removed.key);
    }
    FORWARD_QUEUE.push(entry);
    FORWARD_QUEUE_KEYS.add(entry.key);
    persistForwardQueue();
    return true;
  } catch (err) { return false; }
}

function attemptSendFromQueue(entry) {
  try {
    const p = chrome.runtime.sendMessage(entry.message);
    if (p && typeof p.catch === 'function') {
      p.catch(err => {
        const msg = (err && err.message) || String(err || '');
        if (/Extension context invalidated/i.test(msg) && entry.attempts < MAX_RETRIES_JITTER) {
          entry.attempts = (entry.attempts || 0) + 1;
          const delay = backoffDelay(entry.attempts);
          setTimeout(() => requeueEntry(entry), delay);
          return;
        }
        if (/Extension context invalidated/i.test(msg)) {
          // Extension reloaded; keep quiet to avoid noisy warnings.
          console.debug('[MW Redesign] queued message send delayed (extension reloading)');
          return;
        }
        // Non-recoverable failure: log and drop
        console.warn('[MW Redesign] queued message send failed', msg);
        try { window.__lastForwardMessageError = { ts: Date.now(), message: msg, key: entry.key, attempts: entry.attempts }; } catch (e) {}
      });
    }
    // If sendMessage didn't provide a promise (older runtimes), assume it was dispatched and flush others
    setTimeout(() => flushForwardQueue(), 200);
  } catch (err) {
    const msg = String(err || '');
    if (msg.includes('Extension context invalidated') && entry.attempts < MAX_RETRIES_JITTER) {
      entry.attempts = (entry.attempts || 0) + 1;
      const delay = backoffDelay(entry.attempts);
      setTimeout(() => requeueEntry(entry), delay);
    } else if (msg.includes('Extension context invalidated')) {
      console.debug('[MW Redesign] queued message send delayed (extension reloading)');
    } else {
      console.warn('[MW Redesign] queued message send failed', err);
      try { window.__lastForwardMessageError = { ts: Date.now(), message: msg, key: entry.key, attempts: entry.attempts }; } catch (e) {}
    }
  }
}

function flushForwardQueue(maxPerRun = 5) {
  if (!FORWARD_QUEUE.length) return;
  const toRun = Math.min(maxPerRun, FORWARD_QUEUE.length);
  for (let i = 0; i < toRun; i++) {
    const entry = dequeueForwardMessage();
    if (!entry) continue;
    attemptSendFromQueue(entry);
  }
  // Persist the queue after attempts
  persistForwardQueue();
}

setInterval(() => flushForwardQueue(), FORWARD_QUEUE_FLUSH_INTERVAL);
window.addEventListener('focus', () => flushForwardQueue());

// Restore queue from sessionStorage on load and attempt an early flush
try { restoreForwardQueue(); setTimeout(() => flushForwardQueue(), 800); } catch (e) { /* ignore */ }

function storePendingRoundEvent(roundEvent, reason) {
  console.log('[MW Redesign] Attempting to store round finished event in chrome.storage.local', reason || '');
  try {
    chrome.storage.local.set({
      mw_pending_round_finished: roundEvent
    }, () => {
      if (chrome.runtime.lastError) {
        console.error('[MW Redesign] Failed to store round finished event:', chrome.runtime.lastError);
      } else {
        console.log('[MW Redesign] Successfully stored round finished event in storage');
      }
    });
  } catch (err) {
    console.error('[MW Redesign] Error calling chrome.storage.local.set:', err);
  }
}

function storePendingClanMatch(clanId, clanName, reason) {
  try {
    chrome.storage.local.get(['mw_pending_clan_match'], (result) => {
      const existing = Array.isArray(result.mw_pending_clan_match) ? result.mw_pending_clan_match : [];
      const next = [...existing, { clanId, clanName, ts: Date.now(), reason: reason || null }];
      const trimmed = next.slice(-50);
      chrome.storage.local.set({ mw_pending_clan_match: trimmed }, () => {
        if (chrome.runtime.lastError) {
          console.warn('[MW Redesign] Failed to store clan match:', chrome.runtime.lastError);
        } else {
          console.log('[MW Redesign] Stored clan match for later upsert:', clanId, clanName);
        }
      });
    });
  } catch (err) {
    console.warn('[MW Redesign] Error storing clan match:', err);
  }
}

function extractClanMatchFromEventData(eventData) {
  if (!eventData || typeof eventData !== 'object') return null;
  const directId = eventData.clanId ?? eventData.clan_id ?? null;
  const directName = eventData.clanName ?? eventData.clan_name ?? null;
  if (directId && directName) return { clanId: directId, clanName: directName };

  const info = eventData.data?.additionalInfo;
  if (info && info.type === 'winner') {
    const infoId = info.clanId ?? info.clan_id ?? info.clan?.id ?? null;
    const infoName = info.clanName ?? info.clan_name ?? info.clan?.name ?? null;
    if (infoId && infoName) return { clanId: infoId, clanName: infoName };
  }

  return null;
}

// Listen for postMessage events from the page hook
window.addEventListener('message', (event) => {
  if (!event?.data) return;

  const { type, payload } = event.data;

  // Forward MW WebSocket events
  if (type === 'MW_WS_EVENT' && payload) {
    const [eventName, eventData] = payload;
    console.log('[MW Redesign] Forwarding WS event:', eventName, eventData);

    // Send to background/side panel (deduped)
    forwardMessage({
      type: 'MW_WS_EVENT',
      eventName,
      eventData
    });

    // Capture clan mapping from winner events
    try {
      const nameLower = typeof eventName === 'string' ? eventName.toLowerCase() : '';
      const extracted = extractClanMatchFromEventData(eventData);
      if (extracted) {
        const source = nameLower.includes('winner') ? 'winner' : `ws:${eventName}`;
        forwardMessage({
          type: 'MW_CLAN_MATCH',
          payload: { clanId: extracted.clanId, clanName: extracted.clanName, source }
        });
        storePendingClanMatch(extracted.clanId, extracted.clanName, source);
      }
    } catch (err) {
      console.warn('[MW Redesign] Failed to process winner clan match:', err);
    }
  }

  // Forward round events
  if (type === 'MW_ROUND_EVENT' && payload) {
    console.log('[MW Redesign] Forwarding round event:', payload.name, payload.data);

    // If this is a roundClosed event, try to extract data from the round finished popup
    if (payload.name === 'roundClosed') {
      console.log('[MW Redesign] Round closed detected, attempting to extract finished round data from DOM');

      // Wait a bit for the popup to render, then extract data
      setTimeout(() => {
        try {
          const finishedPopup = document.querySelector('.modal-round-finished');
          if (finishedPopup) {
            console.log('[MW Redesign] Found round finished popup, extracting data');

            // Send the entire innerHTML of the popup for more robust parsing in the sidepanel
            const extractedData = {
              popupHtml: finishedPopup.innerHTML,
              time_round_finished: new Date().toISOString(),
              roundId: payload.data?.roundId || null
            };

            console.log('[MW Redesign] Extracted round finished HTML');

            const roundEvent = {
              type: 'MW_ROUND_EVENT',
              payload: {
                name: 'roundClosed',
                data: extractedData
              },
              timestamp: Date.now()
            };

            // Send the enhanced payload
            forwardMessage(roundEvent);

            // ALSO store in chrome.storage so sidepanel can pick it up when it opens
            storePendingRoundEvent(roundEvent, 'roundClosed+popup');
          } else {
            console.log('[MW Redesign] Round finished popup not found, sending roundClosed event without extracted data');
            const roundEvent = {
              type: 'MW_ROUND_EVENT',
              payload,
              timestamp: Date.now()
            };
            // Send the original payload
            forwardMessage(roundEvent);
            storePendingRoundEvent(roundEvent, 'roundClosed-no-popup');
          }
        } catch (err) {
          console.error('[MW Redesign] Failed to extract round finished data:', err);
          const roundEvent = {
            type: 'MW_ROUND_EVENT',
            payload,
            timestamp: Date.now()
          };
          // Send the original payload
          forwardMessage(roundEvent);
          storePendingRoundEvent(roundEvent, 'roundClosed-error');
        }
      }, 500); // Wait 500ms for popup to render

      // Don't forward the original event yet
      return;
    }

    const roundEvent = {
      type: 'MW_ROUND_EVENT',
      payload,
      timestamp: Date.now()
    };
    forwardMessage(roundEvent);
    if (payload.name === 'roundEnded') {
      storePendingRoundEvent(roundEvent, 'roundEnded');
    }
  }

  // Forward ability/boost events
  if (type === 'MW_ABILITY_USAGE' && payload) {
    console.log('[MW Redesign] Forwarding ability usage:', payload);

    // Include a simple source marker so sidepanel can know this came from the page (likely a local action)
    forwardMessage({
      type: 'MW_ABILITY_USAGE',
      payload,
      source: 'page'
    });
  }

  // Forward Round API monitoring events
  if (type === 'MW_API_CALL' && payload) {
    const enriched = { ...(payload && typeof payload === 'object' ? payload : { value: payload }), timestamp: Date.now() };
    console.log('[MW Redesign] Forwarding round API call:', enriched);
    forwardMessage({
      type: 'MW_API_CALL',
      payload: enriched
    });
  }

  // Forward clan roster events from page hook
  if (type === 'MW_CLAN_ROSTER' && payload) {
    console.log('[MW Redesign] Forwarding clan roster:', Array.isArray(payload) ? payload.length : 0);
    forwardMessage({
      type: 'MW_CLAN_ROSTER',
      payload
    });
  }

  // Legacy event support
  if (type === 'liveData') {
    forwardMessage({
      type: 'MW_LIVE_DATA',
      payload
    });
  }

  if (type === 'roundFinished') {
    forwardMessage({
      type: 'MW_ROUND_FINISHED',
      payload
    });
  }

  if (type === 'boostUsage') {
    forwardMessage({
      type: 'MW_BOOST_USAGE',
      payload
    });
  }
});

console.log('[MW Redesign] Content script setup complete - listening for events');
