import "./_virtual_wxt-html-plugins.js";
import { g as getPerformanceSettingsAsync, a as applyPerformanceSettingsToBody, b as applyHardwareAcceleration } from "./performance-helper.js";
import { buildSupportedGatewaysMarkup, renderOnce } from "./src/options1/bootstrap-render.js";
import { attachBinLibraryManagerToWindow, createBinLibraryManager } from "./src/options1/bin-library.js";
import { getLicenseElements, isLicenseKeyFormatValid, maskLicenseKey, normalizeLicenseKey } from "./src/options1/license.js";
import { buildLibraryItemMarkup, getLibraryModalElements } from "./src/options1/library-modal.js";
import { getNotificationElements } from "./src/options1/notifications.js";
import {
  DEFAULT_GATEWAY_MATCHERS,
  computeLocalRiskSummary,
  createRiskEvaluationState,
  formatRiskBandLabel,
  getRelativeTimeLabel,
  getRiskBandFromScore,
  normalizeRiskLevel
} from "./src/options1/risk-evaluation.js";
import { applyTelegramLinks } from "./src/options1/telegram-links.js";
const appRoot = document.getElementById("app");
const binLibraryManager = createBinLibraryManager();
attachBinLibraryManagerToWindow(binLibraryManager);
renderOnce(appRoot, () => {
    const joinedText2 = buildSupportedGatewaysMarkup();
    return "\n  <div class=\"app-container\">\n    <header class=\"app-header\">\n      <div class=\"header-left\">\n        <div class=\"logo\">\n          <img src=\"../assets/icons/icon48.png\" alt=\"Naruto Bypasser Logo\">\n        </div>\n        <div class=\"header-info\">\n          <h1>Naruto Bypasser</h1>\n          <p class=\"version\">v2.7</p>\n        </div>\n      </div>\n      <div class=\"header-actions\">\n        <a id=\"telegramHeaderLink\" target=\"_blank\" class=\"action-icon telegram-link\" title=\"Telegram\" aria-label=\"Telegram\">\n          <svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"currentColor\">\n            <path d=\"M9.993 15.674L9.594 19.4c.572 0 .82-.246 1.12-.54l2.684-2.56 5.56 4.06c1.02.564 1.748.27 2-.95L23.98 4.83c.33-1.52-.55-2.12-1.55-1.74L1.9 10.38c-1.48.58-1.46 1.4-.27 1.77l5.53 1.72L19.95 6.2c.64-.4 1.23-.18.75.25L9.993 15.674z\" />\n          </svg>\n        </a>\n        <button class=\"action-icon notification-bell\" id=\"notificationIcon\" title=\"Notifications\">\n          <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n            <path d=\"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9\" />\n            <path d=\"M13.73 21a2 2 0 0 1-3.46 0\" />\n          </svg>\n          <span class=\"notif-badge\" id=\"notifBadge\" style=\"display:none;\">0</span>\n        </button>\n        <button class=\"action-icon\" id=\"licenseKeyIcon\" title=\"License Key\">\n          <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n            <path d=\"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4\" />\n          </svg>\n        </button>\n        <button class=\"action-icon\" id=\"supportedGatewaysIcon\" title=\"Supported Gateways\">\n          <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n            <rect x=\"3\" y=\"4\" width=\"18\" height=\"18\" rx=\"2\" ry=\"2\" />\n            <line x1=\"16\" y1=\"2\" x2=\"16\" y2=\"6\" />\n            <line x1=\"8\" y1=\"2\" x2=\"8\" y2=\"6\" />\n            <line x1=\"3\" y1=\"10\" x2=\"21\" y2=\"10\" />\n            <path d=\"M8 14h.01M12 14h.01M16 14h.01M8 18h.01M12 18h.01M16 18h.01\" />\n          </svg>\n        </button>\n        <button class=\"action-icon\" id=\"settingsIcon\" title=\"Settings\">\n          <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n            <circle cx=\"12\" cy=\"12\" r=\"3\" />\n            <path d=\"M12 1v6m0 6v6m11-7h-6m-6 0H1m18.364-6.364l-4.243 4.243M6.879 17.121l-4.243 4.243m14.728 0l-4.243-4.243M6.879 6.879L2.636 2.636\" />\n          </svg>\n        </button>\n      </div>\n    </header>\n\n    <div class=\"notif-panel\" id=\"notifPanel\" style=\"display:none;\">\n      <div class=\"notif-panel-header\">\n        <span class=\"notif-panel-title\">Notifications</span>\n        <div class=\"notif-panel-actions\">\n          <button class=\"notif-clear-btn\" id=\"notifClearBtn\" title=\"Clear all\">\n            <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"3 6 5 6 21 6\" /><path d=\"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2\" /></svg>\n            Clear\n          </button>\n          <button class=\"notif-close-btn\" id=\"notifCloseBtn\" title=\"Close\">\n            <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" /><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" /></svg>\n          </button>\n        </div>\n      </div>\n      <div class=\"notif-panel-body\" id=\"notifPanelBody\">\n        <div class=\"notif-empty\" id=\"notifEmpty\">\n          <svg width=\"32\" height=\"32\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" opacity=\"0.3\"><path d=\"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9\" /><path d=\"M13.73 21a2 2 0 0 1-3.46 0\" /></svg>\n          <span>No notifications yet</span>\n        </div>\n      </div>\n    </div>\n\n    <div id=\"updateBanner\" class=\"update-banner\" style=\"display:none;\">\n      <div class=\"update-banner-content\">\n        <div class=\"update-banner-icon\">\n          <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n            <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" />\n            <polyline points=\"7 10 12 15 17 10\" />\n            <line x1=\"12\" y1=\"15\" x2=\"12\" y2=\"3\" />\n          </svg>\n        </div>\n        <div class=\"update-banner-text\"><strong>Update Available!</strong><span id=\"updateBannerMsg\">A new version is available.</span></div>\n        <a id=\"updateBannerLink\" href=\"#\" target=\"_blank\" class=\"update-banner-btn\" style=\"display:none;\">Download</a>\n        <button id=\"updateBannerDismiss\" class=\"update-banner-dismiss\" title=\"Dismiss\">\n          <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" /><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" /></svg>\n        </button>\n      </div>\n    </div>\n\n    <div id=\"notifBanner\" class=\"notif-banner\" style=\"display:none;\">\n      <div class=\"notif-banner-content\">\n        <div class=\"notif-banner-icon\" id=\"notifBannerIcon\">\n          <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n            <path d=\"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9\" />\n            <path d=\"M13.73 21a2 2 0 0 1-3.46 0\" />\n          </svg>\n        </div>\n        <div class=\"notif-banner-text\"><strong id=\"notifBannerTitle\"></strong><span id=\"notifBannerMsg\"></span></div>\n        <a id=\"notifBannerLink\" href=\"#\" target=\"_blank\" class=\"notif-banner-btn\" style=\"display:none;\"></a>\n        <button id=\"notifBannerDismiss\" class=\"notif-banner-dismiss\" title=\"Dismiss\">\n          <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" /><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" /></svg>\n        </button>\n      </div>\n    </div>\n\n    <main class=\"main-content\">\n      <div class=\"panel-left\">\n        <div class=\"config-section\">\n          <div class=\"section-header\"><span class=\"section-label\">Status</span><label class=\"toggle\"><input type=\"checkbox\" id=\"statusToggle\" checked><span class=\"slider\"></span></label></div>\n          <div class=\"status-context\" id=\"statusContext\">\n            <div class=\"status-state\"><span class=\"status-dot\" id=\"statusStateDot\"></span><div><p class=\"status-state-label\" id=\"statusStateText\">Active</p><p class=\"status-state-subtext\" id=\"statusStateSubtext\">Automation ready</p></div></div>\n            <div class=\"status-meta\">\n              <div class=\"status-meta-item\"><span class=\"meta-label\">Last Sync</span><span class=\"meta-value\" id=\"statusLastSync\">--</span></div>\n              <div class=\"status-meta-item\"><span class=\"meta-label\">Proxy</span><span class=\"meta-value muted\" id=\"statusProxyState\">Not configured</span></div>\n            </div>\n          </div>\n        </div>\n\n        <div class=\"config-section\">\n          <div class=\"section-header\">\n            <span class=\"section-label\">Configuration</span>\n            <div class=\"header-buttons\">\n              <button class=\"icon-btn-small\" id=\"createLibraryBtnQuick\" title=\"Create New Library\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><line x1=\"12\" y1=\"5\" x2=\"12\" y2=\"19\" /><line x1=\"5\" y1=\"12\" x2=\"19\" y2=\"12\" /></svg></button>\n              <button class=\"icon-btn-small\" id=\"manageLibrariesBtn\" title=\"Manage Libraries\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\" ry=\"2\" /><line x1=\"9\" y1=\"3\" x2=\"9\" y2=\"21\" /><line x1=\"15\" y1=\"3\" x2=\"15\" y2=\"21\" /><line x1=\"3\" y1=\"9\" x2=\"21\" y2=\"9\" /><line x1=\"3\" y1=\"15\" x2=\"21\" y2=\"15\" /></svg></button>\n              <button class=\"icon-btn-small\" id=\"pasteBtn\" title=\"Paste from clipboard\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2\" /><rect x=\"8\" y=\"2\" width=\"8\" height=\"4\" rx=\"1\" ry=\"1\" /></svg></button>\n            </div>\n          </div>\n          <div class=\"bin-input-container\">\n            <label class=\"input-label\">Enter BINs (Default Library)</label>\n            <textarea id=\"binInput\" placeholder=\"Enter BIN or Full Card (one per line)\nExamples:\n451286\n625967xxxxxxxxxx\n6259689260838573|06|27|765\" rows=\"4\"></textarea>\n          </div>\n          <div class=\"advanced-section\">\n            <div class=\"advanced-header\" id=\"advancedToggle\"><span>Advanced</span><svg class=\"chevron\" width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M3 4.5L6 7.5L9 4.5\" /></svg></div>\n            <div class=\"advanced-content\" id=\"advancedContent\"><div class=\"form-group\"><label>Proxy (Optional)</label><input type=\"text\" id=\"proxyInput\" placeholder=\"http://proxy:port or socks5://proxy:port\"></div></div>\n          </div>\n        </div>\n\n        <footer class=\"app-footer\">\n          <a id=\"telegramFooterLink1\" target=\"_blank\" class=\"telegram-footer-link telegram-footer-link-red\" title=\"Telegram Channel\"><svg viewBox=\"0 0 24 24\" width=\"20\" height=\"20\" fill=\"currentColor\"><path d=\"M9.993 15.674L9.594 19.4c.572 0 .82-.246 1.12-.54l2.684-2.56 5.56 4.06c1.02.564 1.748.27 2-.95L23.98 4.83c.33-1.52-.55-2.12-1.55-1.74L1.9 10.38c-1.48.58-1.46 1.4-.27 1.77l5.53 1.72L19.95 6.2c.64-.4 1.23-.18.75.25L9.993 15.674z\" /></svg><span>【Bв™】Bin Bhai</span></a>\n          <a id=\"telegramFooterLink2\" target=\"_blank\" class=\"telegram-footer-link telegram-footer-link-yellow\" title=\"Telegram Backup\"><svg viewBox=\"0 0 24 24\" width=\"20\" height=\"20\" fill=\"currentColor\"><path d=\"M9.993 15.674L9.594 19.4c.572 0 .82-.246 1.12-.54l2.684-2.56 5.56 4.06c1.02.564 1.748.27 2-.95L23.98 4.83c.33-1.52-.55-2.12-1.55-1.74L1.9 10.38c-1.48.58-1.46 1.4-.27 1.77l5.53 1.72L19.95 6.2c.64-.4 1.23-.18.75.25L9.993 15.674z\" /></svg><span>BACKUP</span></a>\n        </footer>\n      </div>\n\n      <button class=\"panel-toggle-btn\" id=\"panelToggleBtn\" title=\"Toggle panel\">\n        <svg class=\"panel-toggle-icon panel-toggle-up\" viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"18 15 12 9 6 15\" /></svg>\n        <span class=\"panel-toggle-label\" id=\"panelToggleLabel\">Hide Settings</span>\n        <svg class=\"panel-toggle-icon panel-toggle-down\" viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"display:none\"><polyline points=\"6 9 12 15 18 9\" /></svg>\n      </button>\n\n      <div class=\"panel-right\">\n        <div class=\"logs-header\">\n          <div class=\"logs-title-group\">\n            <span class=\"logs-title\">Logs</span>\n            <span class=\"risk-badge risk-low\" id=\"logsRiskBadge\" title=\"Risk: Low\">\n              <span class=\"risk-badge-icon\" aria-hidden=\"true\">●</span>\n              <span class=\"risk-badge-label\" id=\"logsRiskLabel\">Risk: Low</span>\n            </span>\n            <span class=\"risk-value-chip\" id=\"logsRiskValue\" title=\"Server Risk Value\">Value: --</span>\n            <button class=\"risk-reload-btn\" id=\"logsRiskReloadBtn\" title=\"Reload Risk Score\" aria-label=\"Reload risk score\">\n              <svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n                <polyline points=\"23 4 23 10 17 10\"></polyline>\n                <polyline points=\"1 20 1 14 7 14\"></polyline>\n                <path d=\"M3.51 9a9 9 0 0 1 14.13-3.36L23 10M1 14l5.36 4.36A9 9 0 0 0 20.49 15\"></path>\n              </svg>\n            </button>\n            <span class=\"risk-meta-text\" id=\"logsRiskMeta\" title=\"Risk status\">Awaiting server refresh</span>\n          </div>\n          <div class=\"logs-actions\">\n            <button class=\"log-icon-btn\" id=\"exportLogsBtn\" title=\"Export logs\"><svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" /><polyline points=\"7 10 12 15 17 10\" /><line x1=\"12\" y1=\"15\" x2=\"12\" y2=\"3\" /></svg></button>\n            <button class=\"log-icon-btn\" id=\"copyLogsBtn\" title=\"Copy logs\"><svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\" /><path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\" /></svg></button>\n            <button class=\"log-icon-btn\" id=\"clearLogsBtn\" title=\"Clear logs\"><svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><polyline points=\"3 6 5 6 21 6\" /><path d=\"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2\" /></svg></button>\n          </div>\n        </div>\n\n        <div class=\"live-stats-grid\" id=\"liveStatsGrid\">\n          <div class=\"live-stat-card success-rate\"><div class=\"live-stat-label\">Success Rate</div><div class=\"live-stat-value\" id=\"liveSuccessRate\">0%</div><div class=\"live-stat-subtext\" id=\"liveSuccessSummary\">0 / 0 events</div></div>\n          <div class=\"live-stat-card cards-count\"><div class=\"live-stat-label\">Cards Logged</div><div class=\"live-stat-value\" id=\"liveCardsCount\">0</div><div class=\"live-stat-subtext\" id=\"liveCardsSummary\">Awaiting activity</div></div>\n          <div class=\"live-stat-card top-gateway\"><div class=\"live-stat-label\">Top Gateway</div><div class=\"live-stat-value\" id=\"liveTopGateway\">—</div><div class=\"live-stat-subtext\" id=\"liveTopGatewaySummary\">No data yet</div></div>\n        </div>\n\n        <div class=\"logs-stats-bar\">" + [{
      label: "Total",
      id: "totalLogsCount",
      cls: ""
    }, {
      label: "3DS",
      id: "threeDSLogsCount",
      cls: "stat-3ds"
    }, {
      label: "Cards",
      id: "cardLogsCount",
      cls: "stat-cards"
    }, {
      label: "Success",
      id: "successLogsCount",
      cls: "stat-success"
    }, {
      label: "Errors",
      id: "errorLogsCount",
      cls: "stat-error"
    }].map(item => "<div class=\"stat-item\"><span class=\"stat-label\">" + item.label + "</span><span class=\"stat-value " + item.cls + "\" id=\"" + item.id + "\">0</span></div>").join("") + "</div>\n\n        <div class=\"logs-filter-bar\">\n          <div class=\"search-container\">\n            <svg class=\"search-icon\" width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"11\" cy=\"11\" r=\"8\" /><path d=\"m21 21-4.35-4.35\" /></svg>\n            <input type=\"text\" id=\"logSearchInput\" placeholder=\"Search logs...\" class=\"search-input\">\n            <button class=\"clear-search-btn\" id=\"clearSearchBtn\" title=\"Clear search\" style=\"display: none;\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" /><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" /></svg></button>\n          </div>\n          <div class=\"filter-buttons\">\n            <button class=\"filter-btn active\" data-filter=\"all\" title=\"All logs\">All</button>\n            <button class=\"filter-btn\" data-filter=\"3ds\" title=\"3DS bypass logs\">3DS</button>\n            <button class=\"filter-btn\" data-filter=\"cards\" title=\"Card generation logs\">Cards</button>\n            <button class=\"filter-btn\" data-filter=\"success\" title=\"Success logs\">Success</button>\n            <button class=\"filter-btn\" data-filter=\"error\" title=\"Error logs\">Errors</button>\n          </div>\n        </div>\n\n        <div class=\"logs-container\">\n          <div class=\"logs-content\" id=\"logsContent\">\n            <div class=\"log-entry-placeholder\">\n              <svg width=\"48\" height=\"48\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" opacity=\"0.3\"><path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\" /><polyline points=\"14 2 14 8 20 8\" /><line x1=\"16\" y1=\"13\" x2=\"8\" y2=\"13\" /><line x1=\"16\" y1=\"17\" x2=\"8\" y2=\"17\" /><polyline points=\"10 9 9 9 8 9\" /></svg>\n              <p>Welcome to Deep Bypasser v2.7!</p>\n              <p class=\"placeholder-subtitle\">Logs will appear here as events occur</p>\n            </div>\n          </div>\n        </div>\n      </div>\n    </main>\n  </div>\n\n  <div class=\"notification\" id=\"notification\"></div>\n\n  <div id=\"supportedGatewaysPopup\" class=\"gateways-popup\" style=\"display: none;\">\n    <div class=\"gateways-popup-content\">\n      <div class=\"gateways-popup-header\"><h3>Supported Payment Gateways</h3><button class=\"gateways-popup-close\" id=\"closeGatewaysPopup\">&times;</button></div>\n      <div class=\"gateways-popup-body\">" + joinedText2 + "</div>\n    </div>\n  </div>\n\n  <div id=\"licenseKeyPopup\" class=\"license-popup\" style=\"display: none;\">\n    <div class=\"license-popup-content\">\n      <div class=\"license-popup-header\"><div class=\"license-header-icon\"><svg width=\"28\" height=\"28\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4\" /></svg></div><h3>License Key</h3><button class=\"license-popup-close\" id=\"closeLicensePopup\">&times;</button></div>\n      <div class=\"license-popup-body\">\n        <div class=\"license-status-card\" id=\"licenseStatusCard\"><div class=\"license-status-icon\" id=\"licenseStatusIcon\"><svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"12\" cy=\"12\" r=\"10\" /><path d=\"M12 8v4m0 4h.01\" /></svg></div><div class=\"license-status-info\"><span class=\"license-status-label\" id=\"licenseStatusLabel\">No License</span><span class=\"license-status-detail\" id=\"licenseStatusDetail\">Enter key to verify fingerprint and unlock premium features</span></div></div>\n        <div class=\"license-input-group\">\n          <label class=\"license-input-label\">License Key</label>\n          <div class=\"license-input-wrapper\">\n            <input type=\"text\" id=\"licenseKeyInput\" class=\"license-input\" placeholder=\"DB-XXXX-XXXX-XXXX-XXXX\" maxlength=\"24\" spellcheck=\"false\" autocomplete=\"off\">\n            <button class=\"license-validate-btn\" id=\"validateLicenseBtn\"><span class=\"license-btn-text\">Verify & Activate</span><span class=\"license-btn-spinner\" style=\"display: none;\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M12 2v4m0 12v4m10-10h-4M6 12H2m15.07-5.07l-2.83 2.83M9.76 14.24l-2.83 2.83m11.14 0l-2.83-2.83M9.76 9.76L6.93 6.93\" /></svg></span></button>\n          </div>\n          <div class=\"license-message\" id=\"licenseMessage\" style=\"display: none;\"></div>\n        </div>\n        <div class=\"license-deactivate-row\" id=\"licenseDeactivateRow\" style=\"display: none;\"><button class=\"license-deactivate-btn\" id=\"deactivateLicenseBtn\">Deactivate License</button></div>\n        <div class=\"license-deactivate-row\"><button class=\"license-deactivate-btn\" id=\"copyFingerprintBtn\">Copy Device Fingerprint</button></div>\n      </div>\n    </div>\n  </div>\n\n  <div id=\"settingsOverlay\" class=\"settings-overlay\" style=\"display: none;\"><iframe id=\"settingsFrame\" src=\"settings.html\" class=\"settings-iframe\"></iframe></div>\n  <div id=\"disclaimerOverlay\" class=\"settings-overlay\" style=\"display: none;\"><iframe id=\"disclaimerFrame\" src=\"disclaimer.html\" class=\"settings-iframe\"></iframe></div>\n\n  <div id=\"libraryManagementModal\" class=\"modal-overlay\" style=\"display: none;\">\n    <div class=\"modal-content library-modal\">\n      <div class=\"modal-header\"><h2>BIN Library Management</h2><button class=\"modal-close\" id=\"closeLibraryModal\">&times;</button></div>\n      <div class=\"modal-body\">\n        <div class=\"library-tabs\"><button class=\"tab-btn active\" data-tab=\"libraries\">Libraries</button><button class=\"tab-btn\" data-tab=\"create\">Create New</button><button class=\"tab-btn\" data-tab=\"import\">Import</button></div>\n        <div class=\"tab-content active\" id=\"tab-libraries\"><div class=\"library-list\" id=\"libraryList\"></div></div>\n        <div class=\"tab-content\" id=\"tab-create\">\n          <div class=\"form-group\"><label>Library Name</label><input type=\"text\" id=\"newLibraryName\" placeholder=\"Enter library name\"></div>\n          <div class=\"form-group\"><label>BINs (one per line)</label><textarea id=\"newLibraryBins\" rows=\"8\" placeholder=\"Enter BINs, one per line\nExamples:\n451286\n625967xxxxxxxxxx\"></textarea></div>\n          <button class=\"btn-primary\" id=\"createLibraryBtn\">Create Library</button>\n        </div>\n        <div class=\"tab-content\" id=\"tab-import\">\n          <div class=\"form-group\">\n            <label>Import Library File</label>\n            <div class=\"file-input-wrapper\">\n              <label for=\"importLibraryFile\" class=\"file-input-label\" id=\"fileInputLabel\"><span class=\"file-input-button\">Choose File</span><span class=\"file-input-text\" id=\"fileInputText\">No file chosen</span></label>\n              <input type=\"file\" id=\"importLibraryFile\" accept=\".binlib,.txt\">\n            </div>\n            <p class=\"help-text\">Select an encrypted BIN library file to import</p>\n          </div>\n          <button class=\"btn-primary\" id=\"importLibraryBtn\" disabled>Import Library</button>\n        </div>\n      </div>\n    </div>\n  </div>\n\n  <div id=\"libraryEditModal\" class=\"modal-overlay\" style=\"display: none;\">\n    <div class=\"modal-content library-modal\">\n      <div class=\"modal-header\"><h2 id=\"editModalTitle\">Edit Library</h2><button class=\"modal-close\" id=\"closeEditModal\">&times;</button></div>\n      <div class=\"modal-body\">\n        <div class=\"form-group\"><label>Library Name</label><input type=\"text\" id=\"editLibraryName\" placeholder=\"Enter library name\"></div>\n        <div class=\"form-group\"><label>BINs (one per line)</label><textarea id=\"editLibraryBins\" rows=\"10\" placeholder=\"Enter BINs, one per line\"></textarea></div>\n        <div class=\"modal-actions\"><button class=\"btn-secondary\" id=\"cancelEditBtn\">Cancel</button><button class=\"btn-primary\" id=\"saveEditBtn\">Save Changes</button></div>\n      </div>\n    </div>\n  </div>\n";
  });
function trimTrailingSlashes(trim) {
  if (trim && typeof trim == "string") {
    return trim.trim().replace(/\/+$/, "");
  } else {
    return "";
  }
}
function resolveRelayServerCandidates(settingsSnapshot) {
  const advancedRelayServerUrl = settingsSnapshot?.bypasserAdvancedSettings?.relayServerUrl;
  const bypasserRelayServerUrl = settingsSnapshot?.bypasserSettings?.relayServerUrl;
  const preferredRelayServerUrl =
    typeof advancedRelayServerUrl == "string" && advancedRelayServerUrl.trim()
      ? advancedRelayServerUrl
      : bypasserRelayServerUrl;
  const filteredItems = [
    trimTrailingSlashes(preferredRelayServerUrl),
    "https://db-auth-svc-v2.testdeep.workers.dev",
    ...["https://db-auth-svc-v2.testdeep.workers.dev"]
  ]
    .map(trimTrailingSlashes)
    .filter(Boolean);
  return Array.from(new Set(filteredItems));
}
const uiElements = {
  statusToggle: document.getElementById("statusToggle"),
  binInput: document.getElementById("binInput"),
  proxyInput: document.getElementById("proxyInput"),
  proxyStatus: document.getElementById("proxyStatus"),
  testProxyBtn: document.getElementById("testProxyBtn"),
  autoCvcToggle: document.getElementById("autoCvcToggle"),
  screenshotToggle: document.getElementById("screenshotToggle"),
  advancedToggle: document.getElementById("advancedToggle"),
  advancedContent: document.getElementById("advancedContent"),
  pasteBtn: document.getElementById("pasteBtn"),
  logsOutput: document.getElementById("logsOutput"),
  logsContent: document.getElementById("logsContent"),
  copyLogsBtn: document.getElementById("copyLogsBtn"),
  clearLogsBtn: document.getElementById("clearLogsBtn"),
  exportLogsBtn: document.getElementById("exportLogsBtn"),
  logSearchInput: document.getElementById("logSearchInput"),
  clearSearchBtn: document.getElementById("clearSearchBtn"),
  filterButtons: document.querySelectorAll(".filter-btn"),
  totalLogsCount: document.getElementById("totalLogsCount"),
  threeDSLogsCount: document.getElementById("threeDSLogsCount"),
  cardLogsCount: document.getElementById("cardLogsCount"),
  successLogsCount: document.getElementById("successLogsCount"),
  errorLogsCount: document.getElementById("errorLogsCount"),
  statusStateText: document.getElementById("statusStateText"),
  statusStateSubtext: document.getElementById("statusStateSubtext"),
  statusStateDot: document.getElementById("statusStateDot"),
  statusLastSync: document.getElementById("statusLastSync"),
  statusProxyState: document.getElementById("statusProxyState"),
  liveSuccessRate: document.getElementById("liveSuccessRate"),
  liveSuccessSummary: document.getElementById("liveSuccessSummary"),
  liveCardsCount: document.getElementById("liveCardsCount"),
  liveCardsSummary: document.getElementById("liveCardsSummary"),
  liveTopGateway: document.getElementById("liveTopGateway"),
  liveTopGatewaySummary: document.getElementById("liveTopGatewaySummary"),
  logsRiskBadge: document.getElementById("logsRiskBadge"),
  logsRiskLabel: document.getElementById("logsRiskLabel"),
  logsRiskValue: document.getElementById("logsRiskValue"),
  logsRiskReloadBtn: document.getElementById("logsRiskReloadBtn"),
  logsRiskMeta: document.getElementById("logsRiskMeta")
};
const riskEvaluationState = createRiskEvaluationState();
function getServerRiskEvaluation() {
  const lastEvaluation = riskEvaluationState.lastEvaluation;
  if (lastEvaluation && typeof lastEvaluation == "object") {
    return lastEvaluation;
  } else {
    return null;
  }
}
function renderRiskBadge(riskSummary) {
  if (!uiElements.logsRiskBadge || !uiElements.logsRiskLabel) {
    return;
  }
  const serverRiskEvaluation = getServerRiskEvaluation();
  const overallRisk = riskSummary?.overallRisk || "low";
  const serverRiskLevel = normalizeRiskLevel(serverRiskEvaluation?.riskLevel);
  const serverRiskBand = getRiskBandFromScore(serverRiskEvaluation?.riskScore);
  const badgeRiskClass = serverRiskBand === "dangerous" ? "high" : serverRiskBand;
  const hasServerRiskScore = !!serverRiskEvaluation && Number.isFinite(Number(serverRiskEvaluation.riskScore));
  const displayedRiskClass = hasServerRiskScore ? badgeRiskClass : overallRisk;
  const displayedRiskLabel = hasServerRiskScore ? formatRiskBandLabel(serverRiskBand) : displayedRiskClass.charAt(0).toUpperCase() + displayedRiskClass.slice(1);
  uiElements.logsRiskBadge.classList.remove("risk-low", "risk-medium", "risk-high");
  uiElements.logsRiskBadge.classList.add("risk-" + displayedRiskClass);
  uiElements.logsRiskLabel.textContent = hasServerRiskScore ? "Premium: " + displayedRiskLabel : "Free: " + displayedRiskLabel;
  const stripeRisk = riskSummary.stripe;
  const airwallexRisk = riskSummary.airwallex;
  const logLines = ["Risk: " + displayedRiskLabel, "Airwallex Risk: " + (airwallexRisk.riskLevel.charAt(0).toUpperCase() + airwallexRisk.riskLevel.slice(1)), "Stripe Risk: " + (stripeRisk.riskLevel.charAt(0).toUpperCase() + stripeRisk.riskLevel.slice(1)), "Risk Total Transactions: " + stripeRisk.totalTransactions, "Generic Decline %: " + stripeRisk.genericDeclinePct.toFixed(1) + "%", "Payment Intent Failed %: " + stripeRisk.paymentIntentFailedPct.toFixed(1) + "%", "Other Declines %: " + stripeRisk.otherDeclinePct.toFixed(1) + "%", "Success %: " + stripeRisk.successPct.toFixed(1) + "%", "Other Gateways Risk: " + (riskSummary.otherGateways.riskLevel.charAt(0).toUpperCase() + riskSummary.otherGateways.riskLevel.slice(1))];
  if (hasServerRiskScore) {
    logLines.unshift("Premium: Score " + formatRiskBandLabel(serverRiskBand));
    logLines.unshift("Free: response-based");
    logLines.unshift("Displayed Risk Source: Server");
    logLines.push("Server Risk Score: " + Number(serverRiskEvaluation.riskScore));
    logLines.push("Server Raw Level: " + (serverRiskLevel ? serverRiskLevel.charAt(0).toUpperCase() + serverRiskLevel.slice(1) : "N/A"));
    logLines.push("Local Log Risk: " + (overallRisk.charAt(0).toUpperCase() + overallRisk.slice(1)));
  } else {
    logLines.unshift("Premium: Score Low | Medium | High | Dangerous");
    logLines.unshift("Free: response-based");
    logLines.unshift("Displayed Risk Source: Local Logs");
  }
  uiElements.logsRiskBadge.title = logLines.join("\n");
}
function renderRiskMeta() {
  if (!uiElements.logsRiskMeta) {
    return;
  }
  if (riskEvaluationState.lastError) {
    uiElements.logsRiskMeta.textContent = riskEvaluationState.lastError;
    uiElements.logsRiskMeta.style.color = "rgba(248, 113, 113, 0.9)";
    return;
  }
  const serverRiskEvaluation = getServerRiskEvaluation();
  if (!serverRiskEvaluation || !Number.isFinite(Number(serverRiskEvaluation.riskScore))) {
    uiElements.logsRiskMeta.textContent = "Awaiting server refresh";
    uiElements.logsRiskMeta.style.color = "rgba(255, 255, 255, 0.52)";
    return;
  }
  const relativeTimeLabel = getRelativeTimeLabel(serverRiskEvaluation.ts);
  const rateLimit = serverRiskEvaluation.rateLimit || riskEvaluationState.rateLimit;
  const remainingAttempts = Number(rateLimit?.remaining);
  const maxAttempts = Number(rateLimit?.limit);
  const rateLimitText = Number.isFinite(remainingAttempts) && Number.isFinite(maxAttempts) ? " | " + remainingAttempts + "/" + maxAttempts + " left" : "";
  const isLowConfidence = Array.isArray(serverRiskEvaluation.reasons) && serverRiskEvaluation.reasons.some(item => String(item?.code || "") === "intel_unavailable");
  uiElements.logsRiskMeta.textContent = "Premium: score-based | Free: response-based | Updated " + relativeTimeLabel + rateLimitText + (isLowConfidence ? " | low confidence" : "");
  uiElements.logsRiskMeta.style.color = isLowConfidence ? "rgba(251, 191, 36, 0.95)" : "rgba(255, 255, 255, 0.62)";
}
function renderRiskValueChip() {
  if (!uiElements.logsRiskValue) {
    return;
  }
  const serverRiskEvaluation = getServerRiskEvaluation();
  if (!serverRiskEvaluation || !Number.isFinite(Number(serverRiskEvaluation.riskScore))) {
    uiElements.logsRiskValue.textContent = "Value: Premium";
    uiElements.logsRiskValue.title = "Server risk value is available for premium sessions only.";
    renderRiskMeta();
    return;
  }
  const lowerText = String(serverRiskEvaluation.riskLevel || "").toLowerCase();
  const toUpperCase = lowerText ? lowerText.charAt(0).toUpperCase() + lowerText.slice(1) : "Unknown";
  uiElements.logsRiskValue.textContent = "Value: " + serverRiskEvaluation.riskScore;
  uiElements.logsRiskValue.title = ["Risk Value: " + serverRiskEvaluation.riskScore, "Server Risk: " + toUpperCase, "Score Band: " + formatRiskBandLabel(getRiskBandFromScore(serverRiskEvaluation.riskScore)), "Action: " + String(serverRiskEvaluation.recommendedAction || "allow"), serverRiskEvaluation.rateLimit && Number.isFinite(Number(serverRiskEvaluation.rateLimit.remaining)) && Number.isFinite(Number(serverRiskEvaluation.rateLimit.limit)) ? "Remaining Tries: " + serverRiskEvaluation.rateLimit.remaining + "/" + serverRiskEvaluation.rateLimit.limit : "", serverRiskEvaluation.evaluationId ? "Evaluation ID: " + serverRiskEvaluation.evaluationId : ""].filter(Boolean).join("\n");
  renderRiskMeta();
}
function isLanguageTimezoneMismatch(language, timezone) {
  if (!language || !timezone) {
    return false;
  }
  const primaryLanguage = String(language).toLowerCase().split("-")[0];
  return !String(timezone).toLowerCase().includes(primaryLanguage);
}
function getIpReputationScore(ipAddress, hasProxy) {
  if (hasProxy) {
    return 72;
  }
  const normalizedIp = String(ipAddress || "");
  if (normalizedIp) {
    if (normalizedIp.startsWith("10.") || normalizedIp.startsWith("192.168.") || normalizedIp.startsWith("172.16.")) {
      return 55;
    } else {
      return 14;
    }
  } else {
    return 42;
  }
}
function copyTextWithFeedback(textToCopy, feedbackTarget) {
  const tempTextArea = document.createElement("textarea");
  tempTextArea.value = textToCopy;
  tempTextArea.style.position = "fixed";
  tempTextArea.style.left = "-9999px";
  tempTextArea.style.top = "-9999px";
  document.body.appendChild(tempTextArea);
  tempTextArea.select();
  tempTextArea.setSelectionRange(0, 99999);
  try {
    if (document.execCommand("copy") && feedbackTarget) {
      const originalFeedbackMarkup = feedbackTarget.innerHTML;
      feedbackTarget.innerHTML = "<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><polyline points=\"20 6 9 17 4 12\"></polyline></svg>";
      feedbackTarget.style.color = "#4ade80";
      setTimeout(() => {
        feedbackTarget.innerHTML = originalFeedbackMarkup;
        feedbackTarget.style.color = "";
      }, 1000);
    }
  } catch (error) {
    console.warn("Fallback copy failed:", error);
  } finally {
    document.body.removeChild(tempTextArea);
  }
}
function resolveGatewayLabelFromLogMessage(messageText) {
  if (!messageText) {
    return null;
  }
  const gatewayMatcher = DEFAULT_GATEWAY_MATCHERS.find(item => messageText.includes(item.key));
  return gatewayMatcher ? gatewayMatcher.label : null;
}
function getStoredLogLines(storageResult) {
  const storedEntries = Array.isArray(storageResult?.dbLogEntries)
    ? storageResult.dbLogEntries.filter(item => typeof item === "string" && item.trim())
    : [];
  if (storedEntries.length > 0) {
    return storedEntries;
  }
  const rawLogText = typeof storageResult?.bypasserLogs === "string"
    ? storageResult.bypasserLogs
    : "";
  return rawLogText.split("\n").filter(item => item.trim());
}const updateLiveStats = {
  currentFilter: "all",
  searchQuery: "",
  logs: [],
  parseFailures: [],
  parseLogLine(trim) {
    const raw = trim.trim();
    if (!raw) {
      return null;
    }
    const matchResult = raw.match(/^\[(\d{1,2}:\d{2}:\d{2}(?:\s+(AM|PM))?)\]\s*(?:(❌|✅|⚠️|ℹ️|âŒ|âœ…|âš ï¸|â„¹ï¸)\s*)?(.+)$/);
    if (!matchResult) {
      return null;
    }
    let [, timestamp,, iconSymbol, messageText] = matchResult;
    let logType = "info";
    let category = "other";
    if (iconSymbol === "âŒ" || iconSymbol === "❌") {
      logType = "error";
    } else if (iconSymbol === "âœ…" || iconSymbol === "✅") {
      logType = "success";
    } else if (iconSymbol === "âš ï¸" || iconSymbol === "⚠️") {
      logType = "warn";
    } else if (iconSymbol === "â„¹ï¸" || iconSymbol === "ℹ️") {
      logType = "info";
    }
    let cardInfo = null;
    if ((messageText.includes("Stripe:") || messageText.includes("Airwallex:") || messageText.includes("Steam:") || messageText.includes("GOG:") || messageText.includes("Adyen:") || messageText.includes("Paddle:") || messageText.includes("Square:") || messageText.includes("NordPay:") || messageText.includes("Braintree:") || messageText.includes("Xsolla:") || messageText.includes("Checkout:") || messageText.includes("Checkout.com:") || messageText.includes("Smart Glocal:") || messageText.includes("EdfaPay:")) && /\d{13,19}\|/.test(messageText)) {
      category = "cards";
      const fullCardMatch = messageText.match(/(\d{13,19}\|\d{1,2}\|\d{2,4}\|\d{3,4})/);
      const maskedCardMatch = messageText.match(/(\d{13,19}\|\d{1,2}\|\d{2,4})(?:\s*\([^)]+\))?/);
      if (fullCardMatch) {
        cardInfo = fullCardMatch[1];
      } else if (maskedCardMatch) {
        cardInfo = maskedCardMatch[1];
      }
    } else if (messageText.includes("Payment Succeeded") || messageText.includes("Checkout Completed") || messageText.includes("Payment Paid")) {
      category = "success";
      logType = "success";
      const fullCardMatch = messageText.match(/(\d{13,19}\|\d{1,2}\|\d{2,4}\|\d{3,4})/);
      const maskedCardMatch = messageText.match(/(\d{13,19}\|\d{1,2}\|\d{2,4})(?:\s*\([^)]+\))?/);
      if (fullCardMatch) {
        cardInfo = fullCardMatch[1];
      } else if (maskedCardMatch) {
        cardInfo = maskedCardMatch[1];
      }
    } else if (messageText.includes("3DS Bypass:")) {
      category = "3ds";
      logType = messageText.includes("Bypassed") ? "success" : "error";
      if (logType === "success") {
        iconSymbol = "✅";
      } else if (iconSymbol !== "âŒ" && iconSymbol !== "❌") {
        iconSymbol = "❌";
      }
    } else if (messageText.includes("Decline Code:") || messageText.includes("Card Declined:") || messageText.includes("Payment Failed") || messageText.includes("Error") && logType === "error") {
      category = "error";
      logType = "error";
      const fullCardMatch = messageText.match(/(\d{13,19}\|\d{1,2}\|\d{2,4}\|\d{3,4})/);
      const maskedCardMatch = messageText.match(/(\d{13,19}\|\d{1,2}\|\d{2,4})(?:\s*\([^)]+\))?/);
      if (fullCardMatch) {
        cardInfo = fullCardMatch[1];
      } else if (maskedCardMatch) {
        cardInfo = maskedCardMatch[1];
      }
    }
    return {
      timestamp: timestamp,
      icon: iconSymbol || "ℹ️",
      message: messageText,
      logType: logType,
      category: category,
      cardInfo: cardInfo,
      raw: raw
    };
  },  renderLogs() {
    if (uiElements.logsContent) {
      requestAnimationFrame(() => {
        const filteredItems = updateLiveStats.logs.filter(item => {
          if (updateLiveStats.currentFilter !== "all") {
            if (updateLiveStats.currentFilter === "cards" && item.category !== "cards") {
              return false;
            }
            if (updateLiveStats.currentFilter === "3ds" && item.category !== "3ds") {
              return false;
            }
            if (updateLiveStats.currentFilter === "success" && item.logType !== "success") {
              return false;
            }
            if (updateLiveStats.currentFilter === "error" && item.logType !== "error") {
              return false;
            }
          }
          if (updateLiveStats.searchQuery) {
            const lowerText = updateLiveStats.searchQuery.toLowerCase();
            if (!item.message.toLowerCase().includes(lowerText) && !item.timestamp.toLowerCase().includes(lowerText)) {
              return false;
            }
          }
          return true;
        });
        filteredItems.sort((left, right) => {
          const parseTimeToSeconds = match => {
            const matchResult = match.match(/^(\d{1,2}):(\d{2}):(\d{2})(?:\s+(AM|PM))?$/);
            if (!matchResult) {
              return 0;
            }
            const [, numericText, numericText2, numericText3, meridiem] = matchResult;
            let parsedNumber = parseInt(numericText);
            if (meridiem === "PM" && parsedNumber !== 12) {
              parsedNumber += 12;
            }
            if (meridiem === "AM" && parsedNumber === 12) {
              parsedNumber = 0;
            }
            return parsedNumber * 3600 + parseInt(numericText2) * 60 + parseInt(numericText3);
          };
          return parseTimeToSeconds(left.timestamp) - parseTimeToSeconds(right.timestamp);
        });
        updateLiveStats.updateStatistics();
        const maxItemsToDisplay = window.innerWidth <= 768 || "ontouchstart" in window ? 50 : 100;
        const logsToRender = filteredItems.length > maxItemsToDisplay ? filteredItems.slice(-maxItemsToDisplay) : filteredItems;
        if (filteredItems.length === 0) {
          uiElements.logsContent.innerHTML = "\n            <div class=\"log-entry-placeholder\">\n              <svg width=\"48\" height=\"48\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" opacity=\"0.3\">\n                <circle cx=\"11\" cy=\"11\" r=\"8\"></circle>\n                <path d=\"m21 21-4.35-4.35\"></path>\n              </svg>\n              <p>No logs found</p>\n              <p class=\"placeholder-subtitle\">" + (updateLiveStats.searchQuery ? "Try adjusting your search or filter" : "Logs will appear here as events occur") + "</p>\n            </div>\n          ";
          return;
        }
        const documentFragment = document.createDocumentFragment();
        const logListContainer = document.createElement("div");
        logsToRender.forEach(item => {
          const className = ["log-entry", "log-type-" + item.logType, "log-type-" + item.category].join(" ");
          const message = item.cardInfo || item.message.includes("Stripe:") || item.message.includes("Airwallex:") || item.message.includes("Steam:") || item.message.includes("GOG:") || item.message.includes("Adyen:") || item.message.includes("Checkout:") || item.message.includes("Checkout.com:") ? "\n                <button class=\"copy-log-btn\" title=\"Copy card\" data-log=\"" + updateLiveStats.escapeHtml(item.message) + "\" data-card=\"" + (item.cardInfo ? updateLiveStats.escapeHtml(item.cardInfo) : "") + "\">\n                  <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n                    <rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect>\n                    <path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"></path>\n                  </svg>\n                </button>\n          " : "";
          const logEntryElement = document.createElement("div");
          logEntryElement.className = className;
          logEntryElement.setAttribute("data-category", item.category);
          logEntryElement.setAttribute("data-type", item.logType);
          logEntryElement.innerHTML = "\n            <div class=\"log-main-content\">\n              <span class=\"log-timestamp\">[" + item.timestamp + "]</span>\n              <span class=\"log-icon\">" + item.icon + "</span>\n              <span class=\"log-message\">" + updateLiveStats.escapeHtml(item.message) + "</span>\n              " + message + "\n            </div>\n          ";
          logListContainer.appendChild(logEntryElement);
        });
        documentFragment.appendChild(logListContainer);
        uiElements.logsContent.innerHTML = "";
        uiElements.logsContent.appendChild(documentFragment);
        if (uiElements.logsContent._delegatedClickHandler) {
          uiElements.logsContent.removeEventListener("click", uiElements.logsContent._delegatedClickHandler);
        }
        uiElements.logsContent._delegatedClickHandler = event => {
          const closestResult = event.target.closest(".copy-log-btn");
          if (closestResult) {
            event.stopPropagation();
            const logMessage = closestResult.dataset.log || "";
            let card = closestResult.dataset.card || "";
            if (!card && (logMessage.includes("Stripe:") || logMessage.includes("Airwallex:") || logMessage.includes("Steam:") || logMessage.includes("GOG:") || logMessage.includes("Adyen:") || logMessage.includes("Checkout:") || logMessage.includes("Checkout.com:"))) {
              const fullCardMatch = logMessage.match(/(\d{13,19}\|\d{1,2}\|\d{2,4}\|\d{3,4})/);
              const maskedCardMatch = logMessage.match(/(\d{13,19}\|\d{1,2}\|\d{2,4})(?:\s*\([^)]+\))?/);
              if (fullCardMatch) {
                card = fullCardMatch[1];
              } else if (maskedCardMatch) {
                card = maskedCardMatch[1];
              }
            }
            const card2 = card || logMessage;
            if (navigator.clipboard && navigator.clipboard.writeText) {
              navigator.clipboard.writeText(card2).then(() => {
                const innerHtml = closestResult.innerHTML;
                closestResult.innerHTML = "<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><polyline points=\"20 6 9 17 4 12\"></polyline></svg>";
                closestResult.style.color = "#4ade80";
                setTimeout(() => {
                  closestResult.innerHTML = innerHtml;
                  closestResult.style.color = "";
                }, 1000);
              }).catch(error => {
                copyTextWithFeedback(card2, closestResult);
              });
            } else {
              copyTextWithFeedback(card2, closestResult);
            }
          }
        };
        uiElements.logsContent.addEventListener("click", uiElements.logsContent._delegatedClickHandler);
        if (!updateLiveStats.searchQuery && updateLiveStats.currentFilter === "all") {
          uiElements.logsContent.scrollTop = uiElements.logsContent.scrollHeight;
        }
      });
    }
  },
  updateStatistics() {
    const statsSummary = {
      total: updateLiveStats.logs.length,
      threeDS: updateLiveStats.logs.filter(item => item.category === "3ds").length,
      cards: updateLiveStats.logs.filter(item => item.category === "cards").length,
      success: updateLiveStats.logs.filter(item => item.logType === "success").length,
      error: updateLiveStats.logs.filter(item => item.logType === "error").length
    };
    if (uiElements.totalLogsCount) {
      uiElements.totalLogsCount.textContent = statsSummary.total.toLocaleString();
    }
    if (uiElements.threeDSLogsCount) {
      uiElements.threeDSLogsCount.textContent = statsSummary.threeDS.toLocaleString();
    }
    if (uiElements.cardLogsCount) {
      uiElements.cardLogsCount.textContent = statsSummary.cards.toLocaleString();
    }
    if (uiElements.successLogsCount) {
      uiElements.successLogsCount.textContent = statsSummary.success.toLocaleString();
    }
    if (uiElements.errorLogsCount) {
      uiElements.errorLogsCount.textContent = statsSummary.error.toLocaleString();
    }
    renderRiskBadge(computeLocalRiskSummary(updateLiveStats.logs));
    renderRiskValueChip();
    updateLiveStats.updateLiveStats(statsSummary);
  },
  updateLiveStats(statsSummary) {
    if (!uiElements.liveSuccessRate) {
      return;
    }
    const totalEvents = statsSummary.total || 0;
    const successCount = statsSummary.success || 0;
    const cardsCount = statsSummary.cards || 0;
    const successPercentage = totalEvents > 0 ? Math.round(successCount / totalEvents * 100) : 0;
    uiElements.liveSuccessRate.textContent = successPercentage + "%";
    if (uiElements.liveSuccessSummary) {
      uiElements.liveSuccessSummary.textContent = totalEvents ? successCount.toLocaleString() + " / " + totalEvents.toLocaleString() + " events" : "No data yet";
    }
    if (uiElements.liveCardsCount) {
      uiElements.liveCardsCount.textContent = cardsCount.toLocaleString();
    }
    if (uiElements.liveCardsSummary) {
      const timestamp = updateLiveStats.logs.length ? [...updateLiveStats.logs].reverse().find(item => item.category === "cards") : null;
      uiElements.liveCardsSummary.textContent = timestamp ? "Last · " + timestamp.timestamp : "Awaiting activity";
    }
    if (uiElements.liveTopGateway && uiElements.liveTopGatewaySummary) {
      const gatewayCounters = {};
      let topGatewayLabel = "—";
      let topGatewayCount = 0;
      updateLiveStats.logs.forEach(item => {
        const gatewayLabel = resolveGatewayLabelFromLogMessage(item.message);
        if (gatewayLabel) {
          gatewayCounters[gatewayLabel] = (gatewayCounters[gatewayLabel] || 0) + 1;
          if (gatewayCounters[gatewayLabel] > topGatewayCount) {
            topGatewayLabel = gatewayLabel;
            topGatewayCount = gatewayCounters[gatewayLabel];
          }
        }
      });
      if (topGatewayCount === 0) {
        uiElements.liveTopGateway.textContent = "—";
        uiElements.liveTopGatewaySummary.textContent = "No data yet";
      } else {
        uiElements.liveTopGateway.textContent = topGatewayLabel;
        uiElements.liveTopGatewaySummary.textContent = topGatewayCount.toLocaleString() + " log" + (topGatewayCount === 1 ? "" : "s");
      }
    }
  },
  loadLogs() {
    chrome.storage.local.get(["bypasserLogs", "dbLogEntries"], storedLogs => {
      const filteredItems = getStoredLogLines(storedLogs);
      if (filteredItems.length > 0) {
        const logs = [];
        const parseFailures = [];
        filteredItems.forEach((item, index) => {
          const parsedLogLine = updateLiveStats.parseLogLine(item);
          if (parsedLogLine) {
            logs.push(parsedLogLine);
          } else {
            parseFailures.push({
              index: index,
              line: item.substring(0, 100)
            });
          }
        });
        updateLiveStats.logs = logs;
        updateLiveStats.parseFailures = parseFailures;
        updateLiveStats.renderLogs();
      } else {
        updateLiveStats.logs = [];
        updateLiveStats.parseFailures = [];
        updateLiveStats.renderLogs();
      }
    });
  },  addLog(rawMessage, logType = "info") {
    updateLiveStats.loadLogs();
  },
  clearLogs() {
    if (confirm("Are you sure you want to clear all logs?")) {
      chrome.storage.local.set({
        bypasserLogs: "",
        dbLogEntries: [],
        dbLastLogPersistAt: null
      }, () => {
        if (chrome.runtime.lastError) {
          showNotification("Failed to clear logs: " + chrome.runtime.lastError.message, "error");
        } else {
          updateLiveStats.logs = [];
          updateLiveStats.renderLogs();
          showNotification("Logs cleared successfully", "success");
        }
      });
    }
  },  async copyLogs() {
    try {
      const lines = updateLiveStats.logs.map(item => item.raw).join("\n");
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(lines);
      } else {
        copyTextWithFeedback(lines, null);
      }
      if (uiElements.copyLogsBtn) {
        const innerHtml = uiElements.copyLogsBtn.innerHTML;
        uiElements.copyLogsBtn.innerHTML = "<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><polyline points=\"20 6 9 17 4 12\"></polyline></svg>";
        setTimeout(() => {
          if (uiElements.copyLogsBtn) {
            uiElements.copyLogsBtn.innerHTML = innerHtml;
          }
        }, 1000);
      }
      showNotification("Logs copied to clipboard", "success");
    } catch (error) {
      showNotification("Failed to copy logs: " + error.message, "error");
    }
  },
  exportLogs() {
    try {
      const lines = updateLiveStats.logs.map(item => item.raw).join("\n");
      const blobRef = new Blob([lines], {
        type: "text/plain"
      });
      const downloadUrl = URL.createObjectURL(blobRef);
      const downloadLink = document.createElement("a");
      downloadLink.href = downloadUrl;
      downloadLink.download = "deep-bypasser-logs-" + new Date().toISOString().split("T")[0] + ".txt";
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
      URL.revokeObjectURL(downloadUrl);
      showNotification("Logs exported successfully", "success");
    } catch (error) {
      showNotification("Failed to export logs: " + error.message, "error");
    }
  },
  escapeHtml(textContent) {
    const escapeContainer = document.createElement("div");
    escapeContainer.textContent = textContent;
    return escapeContainer.innerHTML;
  },
  setFilter(currentFilter) {
    updateLiveStats.currentFilter = currentFilter;
    if (uiElements.filterButtons && uiElements.filterButtons.length > 0) {
      uiElements.filterButtons.forEach(item => {
        item.classList.toggle("active", item.dataset.filter === currentFilter);
      });
    }
    updateLiveStats._renderLogsThrottled();
  },
  setSearch(searchQuery) {
    updateLiveStats.searchQuery = searchQuery;
    if (uiElements.clearSearchBtn) {
      uiElements.clearSearchBtn.style.display = searchQuery ? "flex" : "none";
    }
    updateLiveStats._renderLogsThrottled();
  }
};
let timeoutResult;
let requestAnimationFrameResult;
function showNotification(textContent, notificationType = "success") {
  const notificationElement = document.getElementById("notification");
  if (!notificationElement) {
    return;
  }
  const statusIcon = notificationType === "success" ? "✓" : notificationType === "error" ? "✕" : "ℹ";
  notificationElement.textContent = "";
  const iconElement = document.createElement("span");
  iconElement.className = "notification-icon";
  iconElement.textContent = statusIcon;
  const messageElement = document.createElement("span");
  messageElement.className = "notification-text";
  messageElement.textContent = textContent;
  notificationElement.appendChild(iconElement);
  notificationElement.appendChild(messageElement);
  notificationElement.className = "notification notification-" + notificationType;
  notificationElement.style.display = "flex";
  notificationElement.classList.remove("show");
  notificationElement.offsetWidth;
  setTimeout(() => {
    notificationElement.classList.add("show");
  }, 10);
  setTimeout(() => {
    notificationElement.classList.remove("show");
    setTimeout(() => {
      notificationElement.style.display = "none";
    }, 300);
  }, 3000);
}
updateLiveStats._renderLogsThrottled = function (call) {
  let timestamp = 0;
  let renderLogsThrottleTimeoutId = null;
  return function () {
    const currentTimestamp = Date.now();
    if (currentTimestamp - timestamp >= 150 || timestamp === 0) {
      if (renderLogsThrottleTimeoutId) {
        clearTimeout(renderLogsThrottleTimeoutId);
      }
      renderLogsThrottleTimeoutId = null;
      timestamp = currentTimestamp;
      call.call(this);
    } else {
      renderLogsThrottleTimeoutId ||= setTimeout(() => {
        renderLogsThrottleTimeoutId = null;
        timestamp = Date.now();
        call.call(this);
      }, 150 - (currentTimestamp - timestamp));
    }
  };
}(() => updateLiveStats.renderLogs());
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === "PAYMENT_LOG") {
    updateLiveStats.addLog(message.message, message.logType || "info");
  }
});
chrome.storage.onChanged.addListener((bypasserLogs, areaName) => {
  if (areaName === "local") {
    if (bypasserLogs.bypasserLogs || bypasserLogs.dbLogEntries) {
      updateLiveStats.loadLogs();
    }
    if (bypasserLogs.dbLastRiskEvaluation) {
      const lastEvaluation2 = bypasserLogs.dbLastRiskEvaluation.newValue || null;
      riskEvaluationState.lastEvaluation = lastEvaluation2;
      riskEvaluationState.lastError = "";
      renderRiskBadge(computeLocalRiskSummary(updateLiveStats.logs));
      renderRiskValueChip();
    }
    if (bypasserLogs.bypasserSettings) {
      const bypasserSettings = bypasserLogs.bypasserSettings.newValue || {};
      const cvcMode = bypasserSettings.cvcMode || (bypasserSettings.autoCvc === false ? "remove" : "generate");
      currentSettings.cvcMode = cvcMode;
      currentSettings.customCvc = bypasserSettings.customCvc || "";
      currentSettings.autoCvc = cvcMode === "generate";
      currentSettings.enabled = bypasserSettings.enabled !== false;
      currentSettings.proxy = bypasserSettings.proxy || "";
      currentSettings.autoScreenshot = bypasserSettings.autoScreenshot !== false;
      currentSettings.lastUpdated = bypasserSettings.lastUpdated || currentSettings.lastUpdated;
      renderStatusPanel();
    }
  }
});
if (uiElements.logSearchInput) {
  uiElements.logSearchInput.addEventListener("input", event => {
    clearTimeout(timeoutResult);
    if (requestAnimationFrameResult) {
      cancelAnimationFrame(requestAnimationFrameResult);
    }
    timeoutResult = setTimeout(() => {
      requestAnimationFrameResult = requestAnimationFrame(() => {
        updateLiveStats.setSearch(event.target.value);
      });
    }, 200);
  });
}
if (uiElements.clearSearchBtn) {
  uiElements.clearSearchBtn.addEventListener("click", () => {
    if (uiElements.logSearchInput) {
      uiElements.logSearchInput.value = "";
    }
    updateLiveStats.setSearch("");
  });
}
if (uiElements.filterButtons && uiElements.filterButtons.length > 0) {
  uiElements.filterButtons.forEach(item => {
    item.addEventListener("click", () => {
      updateLiveStats.setFilter(item.dataset.filter);
    });
  });
}
if (uiElements.exportLogsBtn) {
  uiElements.exportLogsBtn.addEventListener("click", () => {
    updateLiveStats.exportLogs();
  });
}
if (uiElements.logsRiskReloadBtn) {
  uiElements.logsRiskReloadBtn.addEventListener("click", () => {
    var requestRiskEvaluation;
    {
      riskEvaluationState.loading = true;
      riskEvaluationState.lastError = "";
      renderRiskMeta();
      if (uiElements.logsRiskReloadBtn) {
        uiElements.logsRiskReloadBtn.style.opacity = "0.65";
        uiElements.logsRiskReloadBtn.style.pointerEvents = "none";
      }
      requestRiskEvaluation = publicIpInfo => {
        const payload = function (providerUnavailableInfo) {
          const timestamp = Date.now();
          const sessionId = function () {
            try {
              const existingSessionId = localStorage.getItem("__db_risk_ui_session_id");
              if (existingSessionId && existingSessionId.trim()) {
                return existingSessionId.trim();
              }
              const nextSessionId = "risk_ui_" + Date.now().toString(36) + "_" + Math.random().toString(36).slice(2, 10);
              localStorage.setItem("__db_risk_ui_session_id", nextSessionId);
              return nextSessionId;
            } catch (error) {
              return "risk_ui_" + Date.now().toString(36);
            }
          }();
          const idempotencyKey = "manual_risk_refresh_" + timestamp;
          const language = navigator.language || "";
          const timezone = (() => {
            try {
              return Intl.DateTimeFormat().resolvedOptions().timeZone || "";
            } catch (error) {
              return "";
            }
          })();
          const isProxy = Boolean(currentSettings && currentSettings.proxy && String(currentSettings.proxy).trim());
          const failedCount = Array.isArray(updateLiveStats.logs) ? updateLiveStats.logs.filter(item => item && item.logType === "error").length : 0;
          const successCount = Array.isArray(updateLiveStats.logs) ? updateLiveStats.logs.filter(item => item && item.logType === "success").length : 0;
          const repeatedDeclines = Array.isArray(updateLiveStats.logs) ? updateLiveStats.logs.filter(item => item && item.message && String(item.message).toLowerCase().includes("decline code")).length : 0;
          const session = {
            id: sessionId
          };
          const historical = {
            successCount: successCount,
            failedCount: failedCount,
            chargebackCount: 0,
            disputeCount: 0,
            accountAgeDays: 30,
            repeatedDeclines: repeatedDeclines
          };
          return {
            idempotencyKey: idempotencyKey,
            session: session,
            event: {
              id: idempotencyKey,
              type: "manual_risk_refresh",
              transactionId: "ui_" + timestamp
            },
            account: {
              id: "acct_" + (location.hostname || "unknown")
            },
            source: "options_ui_manual",
            ipIntel: {
              ip: publicIpInfo && publicIpInfo.ip ? publicIpInfo.ip : "",
              providerUnavailable: !!providerUnavailableInfo && !!providerUnavailableInfo.providerUnavailable,
              reputationScore: getIpReputationScore(publicIpInfo && publicIpInfo.ip ? publicIpInfo.ip : "", isProxy),
              isProxy: isProxy,
              isVpn: false,
              isTor: false,
              isHosting: false
            },
            network: {
              ipVelocityPerHour: 1,
              subnetVelocityPerHour: 1
            },
            footprint: {
              language: language,
              timezone: timezone,
              timezoneLanguageMismatch: isLanguageTimezoneMismatch(language, timezone),
              userAgentConsistency: 100,
              deviceProfileConsistency: 100,
              screenProfileConsistency: 100,
              headerEntropyScore: 0,
              requestVelocityPerMin: 1,
              behaviorVelocityPerMin: 1
            },
            historical: historical,
            context: {
              mode: "ip_footprint_refresh",
              hasProxy: isProxy
            }
          };
        }(publicIpInfo);
        const type = {
          type: "RISK_EVALUATE",
          idempotencyKey: payload.idempotencyKey,
          payload: payload
        };
        chrome.runtime.sendMessage(type, result => {
          riskEvaluationState.loading = false;
          if (uiElements.logsRiskReloadBtn) {
            uiElements.logsRiskReloadBtn.style.opacity = "";
            uiElements.logsRiskReloadBtn.style.pointerEvents = "";
          }
          if (chrome.runtime.lastError) {
            riskEvaluationState.lastError = "Risk refresh failed";
            renderRiskMeta();
            showNotification("Risk refresh failed: " + chrome.runtime.lastError.message, "error");
            return;
          }
          if (!result || !result.success) {
            const error = result?.data || {};
            if (String(error.code || "") === "rate_limited") {
              const numberResult = Number(error.remaining || 0);
              const numberResult2 = Number(error.limit || 5);
              const maxResult = Math.max(1, Math.ceil(Number(error.resetInSec || 3600) / 60));
              riskEvaluationState.lastError = "Rate limit " + numberResult + "/" + numberResult2 + " left | retry in " + maxResult + "m";
            } else if (String(error.code || "") === "plan_restricted" || String(error.code || "") === "invalid_session") {
              riskEvaluationState.lastError = "Premium session required";
            } else {
              riskEvaluationState.lastError = "Risk refresh failed";
            }
            renderRiskMeta();
            showNotification(error?.error || result?.error || "Risk refresh failed", "error");
            return;
          }
          const evaluationId = result.data || {};
          riskEvaluationState.lastEvaluation = {
            ts: new Date().toISOString(),
            evaluationId: evaluationId.evaluationId || null,
            riskScore: evaluationId.riskScore,
            riskLevel: evaluationId.riskLevel,
            recommendedAction: evaluationId.recommendedAction,
            reasons: Array.isArray(evaluationId.reasons) ? evaluationId.reasons : [],
            rateLimit: evaluationId.rateLimit || null
          };
          riskEvaluationState.rateLimit = evaluationId.rateLimit || null;
          riskEvaluationState.lastError = "";
          renderRiskBadge(computeLocalRiskSummary(updateLiveStats.logs));
          renderRiskValueChip();
          showNotification("Risk score updated: " + evaluationId.riskScore, "success");
        });
      };
      chrome.runtime.sendMessage({
        type: "GET_PUBLIC_IP"
      }, result => {
        if (chrome.runtime.lastError) {
          requestRiskEvaluation({
            ip: "",
            providerUnavailable: true
          });
        } else if (result && result.success && result.ip) {
          requestRiskEvaluation({
            ip: String(result.ip),
            providerUnavailable: false
          });
        } else {
          requestRiskEvaluation({
            ip: "",
            providerUnavailable: true
          });
        }
      });
    }
  });
}
const defaultSettings = {
  enabled: true,
  bin: [],
  proxy: "",
  cvcMode: "generate",
  customCvc: "",
  autoCvc: true,
  autoScreenshot: true,
  lastUpdated: null,
  _proxyApplied: false,
  _proxyError: ""
};
let currentSettings = defaultSettings;
function formatElapsedLabelFromTimestamp(timestampMs) {
  if (!timestampMs) {
    return "Never";
  }
  const elapsedMs = Date.now() - timestampMs;
  if (elapsedMs < 0) {
    return "Just now";
  }
  const elapsedMinutes = Math.floor(elapsedMs / 60000);
  if (elapsedMinutes < 1) {
    return "Just now";
  }
  if (elapsedMinutes < 60) {
    return elapsedMinutes + "m ago";
  }
  const elapsedHours = Math.floor(elapsedMinutes / 60);
  if (elapsedHours < 24) {
    return elapsedHours + "h ago";
  }
  return Math.floor(elapsedHours / 24) + "d ago";
}
function formatNotificationTimeLabel(sentAt) {
  if (!sentAt) {
    return "";
  }
  const elapsedSeconds = Math.floor((Date.now() - new Date(sentAt).getTime()) / 1000);
  if (elapsedSeconds < 60) {
    return "just now";
  }
  const elapsedMinutes = Math.floor(elapsedSeconds / 60);
  if (elapsedMinutes < 60) {
    return elapsedMinutes + "m ago";
  }
  const elapsedHours = Math.floor(elapsedMinutes / 60);
  if (elapsedHours < 24) {
    return elapsedHours + "h ago";
  }
  return Math.floor(elapsedHours / 24) + "d ago";
}
function renderStatusPanel() {
  if (!uiElements.statusStateText) {
    return;
  }
  const isBypasserEnabled = currentSettings.enabled !== false;
  uiElements.statusStateText.textContent = isBypasserEnabled ? "Active" : "Paused";
  if (uiElements.statusStateSubtext) {
    uiElements.statusStateSubtext.textContent = isBypasserEnabled ? "Automation ready" : "Bypasser is paused";
  }
  if (uiElements.statusStateDot) {
    uiElements.statusStateDot.classList.toggle("offline", !isBypasserEnabled);
  }
  if (uiElements.statusLastSync) {
    if (currentSettings.lastUpdated) {
      uiElements.statusLastSync.textContent = formatElapsedLabelFromTimestamp(currentSettings.lastUpdated);
      uiElements.statusLastSync.setAttribute("title", new Date(currentSettings.lastUpdated).toLocaleString());
    } else {
      uiElements.statusLastSync.textContent = "Never";
      uiElements.statusLastSync.removeAttribute("title");
    }
  }
  if (uiElements.statusProxyState) {
    if (currentSettings.proxy && currentSettings.proxy.trim()) {
      var textContent = "Custom proxy";
      if (currentSettings._proxyApplied) {
        textContent = "Connected";
        uiElements.statusProxyState.style.color = "#4ade80";
      } else if (currentSettings._proxyError) {
        textContent = "Error";
        uiElements.statusProxyState.style.color = "#f87171";
      } else {
        uiElements.statusProxyState.style.color = "";
      }
      uiElements.statusProxyState.textContent = textContent;
      uiElements.statusProxyState.classList.remove("muted");
    } else {
      uiElements.statusProxyState.textContent = "Not configured";
      uiElements.statusProxyState.style.color = "";
      uiElements.statusProxyState.classList.add("muted");
    }
  }
}
function renderProxyStatus(statusType, statusMessage) {
  if (uiElements.proxyStatus) {
    if (statusType || statusMessage) {
      if (statusType === "success") {
        uiElements.proxyStatus.textContent = "✓ " + statusMessage;
        uiElements.proxyStatus.style.color = "#4ade80";
      } else if (statusType === "error") {
        uiElements.proxyStatus.textContent = "✕ " + statusMessage;
        uiElements.proxyStatus.style.color = "#f87171";
      } else if (statusType === "validating") {
        uiElements.proxyStatus.textContent = "⟳ " + (statusMessage || "Validating...");
        uiElements.proxyStatus.style.color = "#facc15";
      } else {
        uiElements.proxyStatus.textContent = statusMessage || "";
        uiElements.proxyStatus.style.color = "rgba(255,255,255,0.5)";
      }
      return;
    } else {
      uiElements.proxyStatus.textContent = "";
      uiElements.proxyStatus.style.color = "";
      return;
    }
  }
}
function fetchPublicIp() {
  return new Promise(resolve => {
    try {
      chrome.runtime.sendMessage({
        type: "GET_PUBLIC_IP"
      }, response => {
        if (chrome.runtime.lastError) {
          resolve(null);
        } else if (response && response.success && response.ip) {
          resolve(String(response.ip));
        } else {
          resolve(null);
        }
      });
    } catch (error) {
      resolve(null);
    }
  });
}
renderStatusPanel();
let hasLoadedLogs = false;
function saveSettings(showFeedback = true, successMessage = null) {
  const binInput = uiElements.binInput && uiElements.binInput.value ? uiElements.binInput.value.split("\n").map(item => item.trim()).filter(item => item.length > 0) : [];
  const nextSettings = {
    enabled: uiElements.statusToggle ? uiElements.statusToggle.checked : currentSettings.enabled,
    bin: binInput.length > 0 ? binInput : currentSettings.bin,
    proxy: uiElements.proxyInput && uiElements.proxyInput.value.trim() || currentSettings.proxy,
    cvcMode: currentSettings.cvcMode || "generate",
    customCvc: currentSettings.customCvc || "",
    autoCvc: currentSettings.autoCvc !== false,
    autoScreenshot: uiElements.screenshotToggle ? uiElements.screenshotToggle.checked : currentSettings.autoScreenshot,
    lastUpdated: Date.now()
  };
  const previousSettingsSnapshot = {
    ...currentSettings,
    lastUpdated: undefined
  };
  const nextSettingsSnapshot = {
    ...nextSettings,
    lastUpdated: undefined
  };
  const hasSettingsChanged = JSON.stringify(previousSettingsSnapshot) !== JSON.stringify(nextSettingsSnapshot);
  currentSettings = nextSettings;
  renderStatusPanel();
  if (hasSettingsChanged || showFeedback) {
    if (!hasLoadedLogs) {
      hasLoadedLogs = true;
      chrome.storage.local.set({
        bypasserSettings: nextSettings
      }, () => {
        hasLoadedLogs = false;
        if (chrome.runtime.lastError) {
          if (showFeedback) {
            showNotification("Failed to save configuration", "error");
          }
        } else {
          if (showFeedback) {
            const feedbackMessage = successMessage || "Configuration saved successfully!";
            showNotification(feedbackMessage, "success");
            chrome.runtime.sendMessage({
              type: "SHOW_NOTIFICATION",
              text: feedbackMessage,
              notificationType: "success"
            }, response => {
              if (chrome.runtime.lastError) {
                const messageText = chrome.runtime.lastError.message;
                if (messageText && !messageText.includes("message channel closed") && !messageText.includes("background page")) {
                  messageText.includes("Extension context invalidated");
                }
              }
            });
          }
          const settingsUpdatedMessage = {
            type: "SETTINGS_UPDATED",
            settings: nextSettings
          };
          chrome.runtime.sendMessage(settingsUpdatedMessage, response => {
            if (chrome.runtime.lastError) {
              const messageText = chrome.runtime.lastError.message;
              if (messageText && !messageText.includes("message channel closed") && !messageText.includes("background page")) {
                messageText.includes("Extension context invalidated");
              }
            }
          });
          if (nextSettings.proxy && nextSettings.proxy.trim()) {
            chrome.runtime.sendMessage({
              type: "APPLY_PROXY",
              proxy: nextSettings.proxy
            }, result => {
              if (chrome.runtime.lastError) {
                currentSettings._proxyApplied = false;
                currentSettings._proxyError = chrome.runtime.lastError.message || "Message failed";
                renderProxyStatus("error", currentSettings._proxyError);
                renderStatusPanel();
                return;
              }
              if (result && result.success && result.applied) {
                currentSettings._proxyApplied = true;
                currentSettings._proxyError = "";
                var proxy = result.proxy ? result.proxy.scheme + "://" + result.proxy.host + ":" + result.proxy.port : "Connected";
                fetchPublicIp().then(publicIp => {
                  renderProxyStatus("success", publicIp ? proxy + " · IP: " + publicIp : proxy);
                });
              } else if (result && !result.success) {
                currentSettings._proxyApplied = false;
                currentSettings._proxyError = result.error || "Unknown error";
                renderProxyStatus("error", currentSettings._proxyError);
              } else {
                currentSettings._proxyApplied = false;
                currentSettings._proxyError = "";
                renderProxyStatus("", "");
              }
              renderStatusPanel();
            });
          } else {
            chrome.runtime.sendMessage({
              type: "CLEAR_PROXY"
            }, response => {
              currentSettings._proxyApplied = false;
              currentSettings._proxyError = "";
              renderProxyStatus("", "");
              renderStatusPanel();
              chrome.runtime.lastError;
            });
          }
        }
      });
    }
  }
}
if (uiElements.advancedToggle && uiElements.advancedContent) {
  uiElements.advancedToggle.addEventListener("click", () => {
    if (uiElements.advancedContent.classList.contains("show")) {
      uiElements.advancedContent.classList.remove("show");
      uiElements.advancedToggle.classList.remove("active");
    } else {
      uiElements.advancedContent.classList.add("show");
      uiElements.advancedToggle.classList.add("active");
    }
  }, {
    once: false
  });
}
if (uiElements.pasteBtn && uiElements.binInput) {
  uiElements.pasteBtn.addEventListener("click", async () => {
    try {
      const readTextResult = await navigator.clipboard.readText();
      uiElements.binInput.value = readTextResult;
      showNotification("Pasted from clipboard", "success");
      scheduleSettingsSave(true, "Configuration saved successfully!");
    } catch (error) {
      showNotification("Failed to paste from clipboard", "error");
    }
  });
}
let settingsSaveTimeoutId = null;
let settingsSaveAnimationFrameId = null;
function scheduleSettingsSave(showFeedback = false, successMessage = null) {
  if (settingsSaveTimeoutId) {
    clearTimeout(settingsSaveTimeoutId);
  }
  if (settingsSaveAnimationFrameId) {
    cancelAnimationFrame(settingsSaveAnimationFrameId);
  }
  settingsSaveTimeoutId = setTimeout(() => {
    settingsSaveAnimationFrameId = requestAnimationFrame(() => {
      saveSettings(showFeedback, successMessage);
    });
  }, 600);
}
let toggleSaveTimeoutId = null;
let toggleSaveAnimationFrameId = null;
function scheduleToggleSave(showFeedback = true, successMessage = null) {
  if (toggleSaveTimeoutId) {
    clearTimeout(toggleSaveTimeoutId);
  }
  if (toggleSaveAnimationFrameId) {
    cancelAnimationFrame(toggleSaveAnimationFrameId);
  }
  if (uiElements.statusToggle) {
    currentSettings.enabled = uiElements.statusToggle.checked;
  }
  if (uiElements.screenshotToggle) {
    currentSettings.autoScreenshot = uiElements.screenshotToggle.checked;
  }
  renderStatusPanel();
  toggleSaveTimeoutId = setTimeout(() => {
    toggleSaveAnimationFrameId = requestAnimationFrame(() => {
      saveSettings(showFeedback, successMessage);
    });
  }, 200);
}
function applyThemeColor(themeHex) {
  if (!themeHex) {
    return;
  }
  const normalizedHex = themeHex.replace("#", "");
  const r = parseInt(normalizedHex.substring(0, 2), 16);
  const g = parseInt(normalizedHex.substring(2, 4), 16);
  const b = parseInt(normalizedHex.substring(4, 6), 16);
  const lighterRgb = "rgb(" + Math.min(255, r + 30) + ", " + Math.min(255, g + 30) + ", " + Math.min(255, b + 30) + ")";
  const accentR = Math.min(255, Math.max(0, r - 20));
  const accentG = Math.min(255, Math.max(0, g - 10));
  const accentB = Math.min(255, b + 30);
  const accentRgb = "rgb(" + accentR + ", " + accentG + ", " + accentB + ")";
  document.documentElement.style.setProperty("--theme-primary", themeHex);
  document.documentElement.style.setProperty("--theme-secondary", lighterRgb);
  document.documentElement.style.setProperty("--theme-accent", accentRgb);
  document.documentElement.style.setProperty("--theme-primary-rgb", r + ", " + g + ", " + b);
  document.documentElement.style.setProperty("--theme-accent-rgb", accentR + ", " + accentG + ", " + accentB);
  let dynamicThemeStyles = document.getElementById("dynamic-theme-styles");
  if (!dynamicThemeStyles) {
    dynamicThemeStyles = document.createElement("style");
    dynamicThemeStyles.id = "dynamic-theme-styles";
    document.head.appendChild(dynamicThemeStyles);
  }
  dynamicThemeStyles.textContent = "\n      body::before {\n        background: \n          radial-gradient(circle at 0% 0%, rgba(" + r + ", " + g + ", " + b + ", 0.25) 0%, transparent 70%),\n          radial-gradient(circle at 100% 100%, rgba(" + accentR + ", " + accentG + ", " + accentB + ", 0.25) 0%, transparent 70%),\n          radial-gradient(circle at 50% 50%, rgba(" + r + ", " + g + ", " + b + ", 0.15) 0%, transparent 80%) !important;\n      }\n    ";
}
if (uiElements.statusToggle) {
  uiElements.statusToggle.addEventListener("change", () => {
    scheduleToggleSave(true, uiElements.statusToggle.checked ? "Bypasser enabled" : "Bypasser disabled");
  }, {
    once: false
  });
}
if (uiElements.autoCvcToggle) {
  uiElements.autoCvcToggle.addEventListener("change", () => {
    scheduleToggleSave(true, uiElements.autoCvcToggle.checked ? "Auto-generate CVC enabled" : "Auto-generate CVC disabled");
  }, {
    once: false
  });
}
if (uiElements.screenshotToggle) {
  uiElements.screenshotToggle.addEventListener("change", () => {
    scheduleToggleSave(true, uiElements.screenshotToggle.checked ? "Auto Screenshot enabled" : "Auto Screenshot disabled");
  }, {
    once: false
  });
}
if (uiElements.binInput) {
  uiElements.binInput.addEventListener("input", () => {
    const currentBins = uiElements.binInput.value.split("\n").map(item => item.trim()).filter(item => item.length > 0);
    currentSettings.bin = currentBins;
    scheduleSettingsSave(true, "BIN configuration saved");
  }, {
    once: false
  });
}
if (uiElements.proxyInput) {
  uiElements.proxyInput.addEventListener("input", () => {
    currentSettings.proxy = uiElements.proxyInput.value.trim();
    currentSettings._proxyApplied = false;
    currentSettings._proxyError = "";
    if (currentSettings.proxy) {
      renderProxyStatus("validating", "Validating...");
      chrome.runtime.sendMessage({
        type: "VALIDATE_PROXY",
        proxy: currentSettings.proxy
      }, proxyValidation => {
        if (chrome.runtime.lastError) {
          renderProxyStatus("error", "Cannot reach background");
        } else if (proxyValidation && proxyValidation.valid) {
          var proxy = proxyValidation.proxy;
          renderProxyStatus("info", proxy.scheme + "://" + proxy.host + ":" + proxy.port + (proxy.hasAuth ? " (auth)" : ""));
        } else if (proxyValidation && !proxyValidation.valid) {
          renderProxyStatus("error", proxyValidation.error || "Invalid format");
        }
      });
    } else {
      renderProxyStatus("", "");
    }
    renderStatusPanel();
    scheduleSettingsSave(true, "Proxy configuration saved");
  }, {
    once: false
  });
}
if (uiElements.testProxyBtn) {
  uiElements.testProxyBtn.addEventListener("click", () => {
    var proxyAddress = uiElements.proxyInput && uiElements.proxyInput.value.trim() || "";
    if (!proxyAddress) {
      renderProxyStatus("error", "Enter a proxy first");
      showNotification("Enter a proxy address to test", "error");
      return;
    }
    uiElements.testProxyBtn.disabled = true;
    renderProxyStatus("validating", "Applying proxy...");
    chrome.runtime.sendMessage({
      type: "APPLY_PROXY",
      proxy: proxyAddress
    }, result => {
      uiElements.testProxyBtn.disabled = false;
      if (chrome.runtime.lastError) {
        currentSettings._proxyApplied = false;
        currentSettings._proxyError = chrome.runtime.lastError.message || "Connection failed";
        renderProxyStatus("error", currentSettings._proxyError);
        showNotification("Proxy test failed: " + currentSettings._proxyError, "error");
        renderStatusPanel();
        return;
      }
      if (result && result.success && result.applied) {
        currentSettings._proxyApplied = true;
        currentSettings._proxyError = "";
        var appliedProxyLabel = result.proxy ? result.proxy.scheme + "://" + result.proxy.host + ":" + result.proxy.port : "Applied";
        fetchPublicIp().then(publicIp => {
          if (publicIp) {
            renderProxyStatus("success", appliedProxyLabel + " — IP: " + publicIp);
            showNotification("Proxy applied. Current IP: " + publicIp, "success");
          } else {
            renderProxyStatus("success", appliedProxyLabel + " — proxy set in Chrome");
            showNotification("Proxy applied successfully!", "success");
          }
        });
      } else if (result && !result.success) {
        currentSettings._proxyApplied = false;
        currentSettings._proxyError = result.error || "Unknown error";
        renderProxyStatus("error", currentSettings._proxyError);
        showNotification("Proxy failed: " + currentSettings._proxyError, "error");
      } else {
        renderProxyStatus("", "No proxy applied");
      }
      renderStatusPanel();
    });
  });
}
if (uiElements.copyLogsBtn) {
  uiElements.copyLogsBtn.addEventListener("click", () => {
    updateLiveStats.copyLogs();
  });
}
if (uiElements.clearLogsBtn) {
  uiElements.clearLogsBtn.addEventListener("click", () => {
    updateLiveStats.clearLogs();
  });
}
chrome.storage.onChanged.addListener((bypasserAdvancedSettings, areaName) => {
  if (areaName === "local" && bypasserAdvancedSettings.bypasserAdvancedSettings) {
    const bypasserAdvancedSettings2 = bypasserAdvancedSettings.bypasserAdvancedSettings.newValue || {};
    if (bypasserAdvancedSettings2.themeColor) {
      applyThemeColor(bypasserAdvancedSettings2.themeColor);
    }
  }
});
const supportedGatewaysButton = document.getElementById("supportedGatewaysIcon");
const supportedGatewaysPopup = document.getElementById("supportedGatewaysPopup");
const closeSupportedGatewaysPopupButton = document.getElementById("closeGatewaysPopup");
if (supportedGatewaysButton && supportedGatewaysPopup) {
  supportedGatewaysButton.addEventListener("click", event => {
    event.stopPropagation();
    supportedGatewaysPopup.style.display = "flex";
  });
  if (closeSupportedGatewaysPopupButton) {
    closeSupportedGatewaysPopupButton.addEventListener("click", () => {
      supportedGatewaysPopup.style.display = "none";
    });
  }
  supportedGatewaysPopup.addEventListener("click", event => {
    if (event.target === supportedGatewaysPopup) {
      supportedGatewaysPopup.style.display = "none";
    }
  });
  document.addEventListener("keydown", key => {
    if (key.key === "Escape" && supportedGatewaysPopup.style.display === "flex") {
      supportedGatewaysPopup.style.display = "none";
    }
  });
}
const {
  licenseKeyIcon: licenseKeyButton,
  licenseKeyPopup,
  closeLicensePopup: closeLicensePopupButton,
  licenseKeyInput,
  validateLicenseBtn: validateLicenseButton,
  licenseMessage: licenseMessageElement,
  licenseStatusCard,
  licenseStatusIcon,
  licenseStatusLabel,
  licenseStatusDetail,
  licenseDeactivateRow,
  deactivateLicenseBtn: deactivateLicenseButton,
  copyFingerprintBtn: copyFingerprintButton
} = getLicenseElements(document);
function renderLicenseState(expiresAt) {
  if (licenseStatusCard) {
    if (expiresAt && expiresAt.valid) {
      licenseStatusCard.className = "license-status-card active";
      if (licenseStatusIcon) {
        licenseStatusIcon.innerHTML = "<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M22 11.08V12a10 10 0 1 1-5.93-9.14\"></path><polyline points=\"22 4 12 14.01 9 11.01\"></polyline></svg>";
      }
      if (licenseStatusLabel) {
        licenseStatusLabel.textContent = (expiresAt.plan ? expiresAt.plan.charAt(0).toUpperCase() + expiresAt.plan.slice(1) : "Pro") + " License";
      }
      if (licenseStatusDetail) {
        const key = expiresAt.key ? expiresAt.key.substring(0, 7) + "••••-••••-••••" : "";
        const expiresAt2 = expiresAt.expiresAt ? " · Expires " + new Date(expiresAt.expiresAt).toLocaleDateString() : " · Lifetime";
        licenseStatusDetail.textContent = key + expiresAt2;
      }
      if (licenseDeactivateRow) {
        licenseDeactivateRow.style.display = "flex";
      }
      if (licenseKeyInput) {
        licenseKeyInput.value = maskLicenseKey(expiresAt.key || "");
        licenseKeyInput.disabled = true;
      }
      if (validateLicenseButton) {
        validateLicenseButton.querySelector(".license-btn-text").textContent = "Verified";
        validateLicenseButton.disabled = true;
      }
      if (licenseKeyButton) {
        licenseKeyButton.style.color = "#34d399";
      }
    } else {
      licenseStatusCard.className = "license-status-card";
      if (licenseStatusIcon) {
        licenseStatusIcon.innerHTML = "<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"12\" cy=\"12\" r=\"10\"></circle><path d=\"M12 8v4m0 4h.01\"></path></svg>";
      }
      if (licenseStatusLabel) {
        licenseStatusLabel.textContent = "No License";
      }
      if (licenseStatusDetail) {
        licenseStatusDetail.textContent = "Enter key to verify fingerprint and unlock protected features";
      }
      if (licenseDeactivateRow) {
        licenseDeactivateRow.style.display = "none";
      }
      if (licenseKeyInput) {
        licenseKeyInput.value = "";
        licenseKeyInput.disabled = false;
      }
      if (validateLicenseButton) {
        validateLicenseButton.querySelector(".license-btn-text").textContent = "Verify & Activate";
        validateLicenseButton.disabled = false;
      }
      if (licenseKeyButton) {
        licenseKeyButton.style.color = "";
      }
    }
  }
}
function showLicenseMessage(messageText, messageType) {
  if (licenseMessageElement) {
    licenseMessageElement.textContent = messageText;
    licenseMessageElement.className = "license-message " + messageType;
    licenseMessageElement.style.display = "block";
    setTimeout(() => {
      licenseMessageElement.style.display = "none";
    }, 5000);
  }
}
function resetLicenseForm() {
  if (licenseKeyInput) {
    licenseKeyInput.value = "";
    licenseKeyInput.disabled = false;
  }
  if (validateLicenseButton) {
    const licenseButtonText = validateLicenseButton.querySelector(".license-btn-text");
    const licenseButtonSpinner = validateLicenseButton.querySelector(".license-btn-spinner");
    if (licenseButtonText) {
      licenseButtonText.style.display = "inline";
    }
    if (licenseButtonSpinner) {
      licenseButtonSpinner.style.display = "none";
    }
    validateLicenseButton.disabled = false;
  }
}
function respondOnce(requestPayload, delayMs = 3000) {
  return new Promise((resolve, reject) => {
    let hasResponded = false;
    const validationTimeoutId = setTimeout(() => {
      if (!hasResponded) {
        hasResponded = true;
        reject(new Error("Validation timeout"));
      }
    }, delayMs);
    chrome.runtime.sendMessage(requestPayload, responsePayload => {
      if (!hasResponded) {
        hasResponded = true;
        clearTimeout(validationTimeoutId);
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else {
          resolve(responsePayload || {});
        }
      }
    });
  });
}
function formatPastedLicenseKey(pastedText) {
  const normalizedText = String(pastedText || "").toUpperCase().replace(/[^A-Z0-9]/g, "");
  if (!normalizedText.startsWith("DB")) {
    return "";
  }
  return ["DB", ...(normalizedText.substring(2).slice(0, 16).match(/.{1,4}/g) || [])].join("-").slice(0, 24);
}
async function validateLicenseKey() {
  const normalizedLicenseKey = licenseKeyInput ? normalizeLicenseKey(licenseKeyInput.value) : "";
  if (!normalizedLicenseKey) {
    showLicenseMessage("Paste a license key to continue", "error");
    return;
  }
  if (!isLicenseKeyFormatValid(normalizedLicenseKey)) {
    resetLicenseForm();
    showLicenseMessage("Invalid format. Use DB-XXXX-XXXX-XXXX-XXXX", "error");
    return;
  }
  const licenseButtonText = validateLicenseButton.querySelector(".license-btn-text");
  const licenseButtonSpinner = validateLicenseButton.querySelector(".license-btn-spinner");
  licenseButtonText.style.display = "none";
  licenseButtonSpinner.style.display = "inline-flex";
  validateLicenseButton.disabled = true;
  try {
    const activationResponse = await respondOnce({
      type: "LICENSE_ACTIVATE",
      key: normalizedLicenseKey
    }, 20000);
    if (activationResponse.valid) {
      const dbLicenseSession = await chrome.storage.local.get(["dbLicense", "dbLicenseSession"]);
      const dbLicense = dbLicenseSession.dbLicense;
      const dbLicenseSession2 = dbLicenseSession.dbLicenseSession;
      const sessionId = !!dbLicenseSession2 && !!dbLicenseSession2.sessionId && !!dbLicenseSession2.accessToken;
      if (!dbLicense || !dbLicense.valid || dbLicense.key !== normalizedLicenseKey || !sessionId) {
        await chrome.storage.local.remove(["dbLicense", "dbLicenseSession"]);
        renderLicenseState(null);
        showLicenseMessage("Activation integrity check failed. Please try again.", "error");
        licenseButtonText.style.display = "inline";
        licenseButtonSpinner.style.display = "none";
        validateLicenseButton.disabled = false;
        return;
      }
      renderLicenseState(dbLicense);
      showLicenseMessage("Key verified and activated. Premium protection features are now enabled.", "success");
    } else {
      resetLicenseForm();
      if (activationResponse && activationResponse.status === "telegram_verification_required") {
        showLicenseMessage("Verify in Telegram first: /activate <LICENSE_KEY> then /fp <FINGERPRINT_HASH>", "error");
      } else if (activationResponse && activationResponse.status === "pair_required") {
        const pairCode = activationResponse.pairCode ? " Approve in Telegram: /pair " + activationResponse.pairCode : " Approve this install in Telegram with /pair <code>.";
        showLicenseMessage((activationResponse.error || "Install pairing required.") + pairCode, "error");
      } else if (activationResponse && activationResponse.status === "fingerprint_not_verified") {
        showLicenseMessage("Fingerprint not linked. Run /fp <FINGERPRINT_HASH> in Telegram for this key.", "error");
      } else if (activationResponse && activationResponse.status === "revoked") {
        showLicenseMessage("This key is banned/revoked. Contact admin.", "error");
      } else {
        showLicenseMessage(activationResponse.error || "Invalid license key", "error");
      }
    }
  } catch (error) {
    resetLicenseForm();
    const message = error && error.message ? error.message : "Check connection";
    if (String(message).toLowerCase().includes("timeout")) {
      showLicenseMessage("Verification is taking longer than expected. Please wait a few seconds and reopen the popup to confirm status.", "error");
    } else {
      showLicenseMessage("Validation failed: " + message, "error");
    }
  }
}
if (licenseKeyInput) {
  licenseKeyInput.addEventListener("keydown", event => {
    const ctrlKey = (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "v";
    const hasMatch = ["Tab", "Escape", "Enter"].includes(event.key);
    if (!ctrlKey && !hasMatch) {
      event.preventDefault();
    }
  });
  licenseKeyInput.addEventListener("paste", async event => {
    event.preventDefault();
    try {
      const pastedText = event.clipboardData && event.clipboardData.getData("text") || "";
      const formattedLicenseKey = formatPastedLicenseKey(pastedText);
      if (!formattedLicenseKey) {
        resetLicenseForm();
        showLicenseMessage("Invalid key format. Paste DB-XXXX-XXXX-XXXX-XXXX", "error");
        return;
      }
      licenseKeyInput.value = formattedLicenseKey;
      await validateLicenseKey();
    } catch {
      resetLicenseForm();
    }
  });
}
(async function () {
  try {
    const dbLicense = await chrome.storage.local.get(["dbLicense", "dbLicenseSession"]);
    if (dbLicense.dbLicense && dbLicense.dbLicense.valid) {
      const dbLicenseSession = await chrome.storage.local.get(["dbLicenseSession"]);
      if (!dbLicenseSession.dbLicenseSession || !dbLicenseSession.dbLicenseSession.sessionId || !dbLicenseSession.dbLicenseSession.accessToken) {
        await chrome.storage.local.remove(["dbLicense", "dbLicenseSession", "dbActiveLicenseKey"]);
        renderLicenseState(null);
        showLicenseMessage("License session missing. Please activate again.", "error");
        return;
      }
      renderLicenseState(dbLicense.dbLicense);
      try {
        const revalidationResponse = await new Promise((resolve, reject) => {
          chrome.runtime.sendMessage({
            type: "LICENSE_REVALIDATE"
          }, response => {
            if (chrome.runtime.lastError) {
              reject(new Error(chrome.runtime.lastError.message));
            } else {
              resolve(response || {
                valid: false,
                fromCache: false
              });
            }
          });
        });
        if (revalidationResponse.fromCache) {
          showLicenseMessage("License server unreachable. Using cached status temporarily.", "warning");
        } else if (!revalidationResponse.valid) {
          await chrome.storage.local.remove(["dbLicense", "dbLicenseSession", "dbActiveLicenseKey"]);
          renderLicenseState(null);
          showLicenseMessage(revalidationResponse.error || "License has been revoked or expired.", "error");
        }
      } catch {
        showLicenseMessage("Could not reach validation server. Status may be outdated.", "warning");
      }
    } else {
      renderLicenseState(null);
    }
  } catch {}
})();
if (licenseKeyButton && licenseKeyPopup) {
  licenseKeyButton.addEventListener("click", event => {
    event.stopPropagation();
    licenseKeyPopup.style.display = "flex";
  });
  if (closeLicensePopupButton) {
    closeLicensePopupButton.addEventListener("click", () => {
      licenseKeyPopup.style.display = "none";
    });
  }
  licenseKeyPopup.addEventListener("click", event => {
    if (event.target === licenseKeyPopup) {
      licenseKeyPopup.style.display = "none";
    }
  });
  document.addEventListener("keydown", key => {
    if (key.key === "Escape" && licenseKeyPopup.style.display === "flex") {
      licenseKeyPopup.style.display = "none";
    }
  });
}
if (validateLicenseButton) {
  validateLicenseButton.addEventListener("click", validateLicenseKey);
}
if (licenseKeyInput) {
  licenseKeyInput.addEventListener("keydown", key => {
    if (key.key === "Enter") {
      validateLicenseKey();
    }
  });
}
if (deactivateLicenseButton) {
  deactivateLicenseButton.addEventListener("click", async function () {
    try {
      await new Promise(resolve => {
        chrome.runtime.sendMessage({
          type: "LICENSE_DEACTIVATE"
        }, () => resolve(true));
      });
    } catch {}
    await chrome.storage.local.remove(["dbLicense", "dbLicenseSession", "dbActiveLicenseKey"]);
    renderLicenseState(null);
    showLicenseMessage("License deactivated", "success");
  });
}
if (copyFingerprintButton) {
  copyFingerprintButton.addEventListener("click", async () => {
    try {
      const fingerprintResponse = await respondOnce({
        type: "GET_DEVICE_FINGERPRINT"
      }, 3000);
      if (!fingerprintResponse || !fingerprintResponse.success || !fingerprintResponse.fingerprint) {
        throw new Error(fingerprintResponse?.error || "Fingerprint unavailable");
      }
      const fingerprintText = String(fingerprintResponse.fingerprint);
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(fingerprintText);
      } else {
        copyTextWithFeedback(fingerprintText, copyFingerprintButton);
      }
      showLicenseMessage("Device fingerprint copied. Send: /fp " + fingerprintText, "success");
    } catch (error) {
      showLicenseMessage("Failed to copy fingerprint: " + (error && error.message ? error.message : "unknown"), "error");
    }
  });
}
const settingsButton = document.getElementById("settingsIcon");
const settingsOverlay = document.getElementById("settingsOverlay");
document.getElementById("settingsFrame");
if (settingsButton && settingsOverlay) {
  settingsButton.addEventListener("click", () => {
    if (settingsOverlay.style.display !== "none" && settingsOverlay.style.display) {
      settingsOverlay.style.display = "none";
    } else {
      settingsOverlay.style.display = "block";
    }
  });
  window.addEventListener("message", event => {
    if (event.data && event.data.type === "CLOSE_SETTINGS") {
      settingsOverlay.style.display = "none";
    }
    if (event.data && event.data.type === "CLOSE_DISCLAIMER") {
      const disclaimerOverlay = document.getElementById("disclaimerOverlay");
      if (disclaimerOverlay) {
        disclaimerOverlay.style.display = "none";
      }
    }
  });
}
let editingLibraryId = null;
const libraryModalElements = getLibraryModalElements(document);
async function getLibraryById(libraryId) {
  return (await window.BinLibraryManager.getAllLibraries()).find(item => item.id === libraryId) || null;
}
async function loadLibraryIntoBinInput(libraryId) {
  const library = await getLibraryById(libraryId);
  if (!library) {
    throw new Error("Library not found");
  }
  if (uiElements.binInput) {
    uiElements.binInput.value = library.bins.join("\n");
    saveSettings(false);
    showNotification("Loaded " + library.bins.length + " BIN" + (library.bins.length !== 1 ? "s" : "") + " from " + library.name, "success");
    if (libraryModalElements.libraryManagementModal) {
      libraryModalElements.libraryManagementModal.style.display = "none";
    }
  }
}
async function openLibraryEditModal(libraryId) {
  const library = await getLibraryById(libraryId);
  if (!library || library.isReadOnly) {
    throw new Error("Cannot edit this library");
  }
  editingLibraryId = libraryId;
  libraryModalElements.editModalTitle.textContent = "Edit: " + library.name;
  libraryModalElements.editLibraryName.value = library.name;
  libraryModalElements.editLibraryBins.value = library.bins.join("\n");
  libraryModalElements.libraryEditModal.style.display = "flex";
}
async function copyLibraryWithPrompt(libraryId) {
  const library = await getLibraryById(libraryId);
  if (!library) {
    throw new Error("Library not found");
  }
  const copiedLibraryName = prompt("Enter name for the copy:", library.name + " (Copy)");
  if (!copiedLibraryName) {
    return;
  }
  await window.BinLibraryManager.copyLibrary(libraryId, copiedLibraryName);
  await renderLibraryManagementModal();
  showNotification("Library copied successfully", "success");
}
async function exportLibraryToFile(libraryId) {
  const exportedLibrary = await window.BinLibraryManager.exportLibrary(libraryId);
  const library = await getLibraryById(libraryId);
  const blobRef = new Blob([exportedLibrary], {
    type: "application/json"
  });
  const downloadUrl = URL.createObjectURL(blobRef);
  const downloadLink = document.createElement("a");
  downloadLink.href = downloadUrl;
  downloadLink.download = library.name.replace(/[^a-z0-9]/gi, "_") + "_library.binlib";
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
  URL.revokeObjectURL(downloadUrl);
  showNotification("Library exported successfully", "success");
}
async function deleteLibraryWithConfirmation(libraryId) {
  if (!confirm("Are you sure you want to delete this library?")) {
    return;
  }
  await window.BinLibraryManager.deleteLibrary(libraryId);
  await renderLibraryManagementModal();
  showNotification("Library deleted", "success");
}
async function renderLibraryManagementModal() {
  if (window.BinLibraryManager) {
    try {
      const allLibraries = await window.BinLibraryManager.getAllLibraries();
      if (libraryModalElements.libraryList) {
        if (allLibraries.length !== 0) {
          libraryModalElements.libraryList.innerHTML = allLibraries.map(item => buildLibraryItemMarkup(item)).join("");
          libraryModalElements.libraryList.querySelectorAll("[data-action]").forEach(item => {
            item.addEventListener("click", async () => {
              const action = item.dataset.action;
              const libraryId = item.dataset.libraryId;
              try {
                switch (action) {
                  case "load":
                    await loadLibraryIntoBinInput(libraryId);
                    break;
                  case "edit":
                    await openLibraryEditModal(libraryId);
                    break;
                  case "copy":
                    await copyLibraryWithPrompt(libraryId);
                    break;
                  case "export":
                    await exportLibraryToFile(libraryId);
                    break;
                  case "delete":
                    await deleteLibraryWithConfirmation(libraryId);
                }
              } catch (error) {
                showNotification(error.message || "Operation failed", "error");
              }
            });
          });
        } else {
          libraryModalElements.libraryList.innerHTML = "\n        <div class=\"empty-state\">\n          <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n            <rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\" ry=\"2\"></rect>\n            <line x1=\"9\" y1=\"3\" x2=\"9\" y2=\"21\"></line>\n            <line x1=\"15\" y1=\"3\" x2=\"15\" y2=\"21\"></line>\n          </svg>\n          <p>No libraries found</p>\n          <p>Create your first library to get started</p>\n        </div>\n      ";
        }
      }
    } catch (error) {
      console.error("Error loading libraries:", error);
    }
  } else {
    console.error("BinLibraryManager not available");
  }
}
document.querySelectorAll(".tab-btn").forEach(item => {
  item.addEventListener("click", () => {
    const tab = item.dataset.tab;
    document.querySelectorAll(".tab-btn").forEach(item2 => item2.classList.remove("active"));
    document.querySelectorAll(".tab-content").forEach(item2 => item2.classList.remove("active"));
    item.classList.add("active");
    document.getElementById("tab-" + tab).classList.add("active");
  });
});
if (libraryModalElements.createLibraryBtnQuick) {
  libraryModalElements.createLibraryBtnQuick.addEventListener("click", async () => {
    const promptResult = prompt("Enter library name:");
    if (promptResult && promptResult.trim()) {
      try {
        const binInput = uiElements.binInput && uiElements.binInput.value ? uiElements.binInput.value.split("\n").map(item => item.trim()).filter(item => item.length > 0) : [];
        await window.BinLibraryManager.createLibrary(promptResult.trim(), binInput);
        showNotification("Library created successfully", "success");
        await renderLibraryManagementModal();
      } catch (error) {
        showNotification(error.message || "Failed to create library", "error");
      }
    }
  });
}
if (libraryModalElements.manageLibrariesBtn) {
  libraryModalElements.manageLibrariesBtn.addEventListener("click", async () => {
    if (libraryModalElements.libraryManagementModal) {
      libraryModalElements.libraryManagementModal.style.display = "flex";
      await renderLibraryManagementModal();
    }
  });
}
if (libraryModalElements.closeLibraryModal) {
  libraryModalElements.closeLibraryModal.addEventListener("click", () => {
    if (libraryModalElements.libraryManagementModal) {
      libraryModalElements.libraryManagementModal.style.display = "none";
    }
  });
}
if (libraryModalElements.createLibraryBtn) {
  libraryModalElements.createLibraryBtn.addEventListener("click", async () => {
    const newLibraryName = libraryModalElements.newLibraryName.value.trim();
    const newLibraryBinsText = libraryModalElements.newLibraryBins.value.trim();
    const libraryBins = newLibraryBinsText ? newLibraryBinsText.split("\n").map(item => item.trim()).filter(item => item) : [];
    if (newLibraryName) {
      try {
        await window.BinLibraryManager.createLibrary(newLibraryName, libraryBins);
        libraryModalElements.newLibraryName.value = "";
        libraryModalElements.newLibraryBins.value = "";
        await renderLibraryManagementModal();
        showNotification("Library created successfully", "success");
      } catch (error) {
        showNotification(error.message || "Failed to create library", "error");
      }
    } else {
      showNotification("Please enter a library name", "error");
    }
  });
}
if (libraryModalElements.importLibraryFile) {
  const fileInputLabel = document.getElementById("fileInputLabel");
  const fileInputText = document.getElementById("fileInputText");
  libraryModalElements.importLibraryFile.addEventListener("change", event => {
    const hasSelectedFile = event.target.files && event.target.files.length > 0;
    libraryModalElements.importLibraryBtn.disabled = !hasSelectedFile;
    if (hasSelectedFile) {
      const fileName = event.target.files[0].name;
      if (fileInputText) {
        fileInputText.textContent = fileName;
        fileInputText.classList.add("has-file");
      }
      if (fileInputLabel) {
        fileInputLabel.classList.add("has-file");
      }
    } else {
      if (fileInputText) {
        fileInputText.textContent = "No file chosen";
        fileInputText.classList.remove("has-file");
      }
      if (fileInputLabel) {
        fileInputLabel.classList.remove("has-file");
      }
    }
  });
  libraryModalElements.importLibraryBtn.addEventListener("click", async () => {
    const importLibraryFile = libraryModalElements.importLibraryFile;
    if (!importLibraryFile.files || importLibraryFile.files.length === 0) {
      showNotification("Please select a file to import", "error");
      return;
    }
    const selectedFile = importLibraryFile.files[0];
    const fileReaderRef = new FileReader();
    fileReaderRef.onload = async event => {
      try {
        const result = event.target.result;
        await window.BinLibraryManager.importLibrary(result);
        importLibraryFile.value = "";
        libraryModalElements.importLibraryBtn.disabled = true;
        if (fileInputText) {
          fileInputText.textContent = "No file chosen";
          fileInputText.classList.remove("has-file");
        }
        if (fileInputLabel) {
          fileInputLabel.classList.remove("has-file");
        }
        await renderLibraryManagementModal();
        showNotification("Library imported successfully", "success");
      } catch (error) {
        showNotification(error.message || "Failed to import library", "error");
      }
    };
    fileReaderRef.readAsText(selectedFile);
  });
}
const initializeBootstrapLinks = () => {
  applyTelegramLinks(document);
};
if (libraryModalElements.closeEditModal) {
  libraryModalElements.closeEditModal.addEventListener("click", () => {
    libraryModalElements.libraryEditModal.style.display = "none";
    editingLibraryId = null;
  });
}
if (libraryModalElements.cancelEditBtn) {
  libraryModalElements.cancelEditBtn.addEventListener("click", () => {
    libraryModalElements.libraryEditModal.style.display = "none";
    editingLibraryId = null;
  });
}
if (libraryModalElements.saveEditBtn) {
  libraryModalElements.saveEditBtn.addEventListener("click", async () => {
    if (!editingLibraryId) {
      return;
    }
    const updatedLibraryName = libraryModalElements.editLibraryName.value.trim();
    const updatedLibraryBinsText = libraryModalElements.editLibraryBins.value.trim();
    const updatedLibraryBins = updatedLibraryBinsText ? updatedLibraryBinsText.split("\n").map(item => item.trim()).filter(item => item) : [];
    if (updatedLibraryName) {
      try {
        const updatedLibraryPayload = {
          name: updatedLibraryName,
          bins: updatedLibraryBins
        };
        await window.BinLibraryManager.updateLibrary(editingLibraryId, updatedLibraryPayload);
        libraryModalElements.libraryEditModal.style.display = "none";
        editingLibraryId = null;
        await renderLibraryManagementModal();
        showNotification("Library updated successfully", "success");
      } catch (error) {
        showNotification(error.message || "Failed to update library", "error");
      }
    } else {
      showNotification("Please enter a library name", "error");
    }
  });
}
(async () => {
  try {
    await getPerformanceSettingsAsync();
    applyPerformanceSettingsToBody();
    [uiElements.statusToggle, uiElements.binInput, uiElements.proxyInput, uiElements.autoCvcToggle, uiElements.screenshotToggle, uiElements.advancedToggle, uiElements.pasteBtn, uiElements.copyLogsBtn, uiElements.clearLogsBtn, uiElements.exportLogsBtn, uiElements.logSearchInput, uiElements.clearSearchBtn, ...Array.from(uiElements.filterButtons || [])].filter(Boolean).forEach(item => {
      applyHardwareAcceleration(item);
    });
  } catch (error) {
    console.warn("[Options] Failed to load performance settings:", error);
  }
})();
updateLiveStats.loadLogs();
chrome.storage.local.get(["dbLastRiskEvaluation"], dbLastRiskEvaluation => {
  const lastEvaluation2 = dbLastRiskEvaluation && dbLastRiskEvaluation.dbLastRiskEvaluation ? dbLastRiskEvaluation.dbLastRiskEvaluation : null;
  if (lastEvaluation2 && typeof lastEvaluation2.riskScore == "number") {
    riskEvaluationState.lastEvaluation = lastEvaluation2;
  }
  renderRiskBadge(computeLocalRiskSummary(updateLiveStats.logs));
  renderRiskValueChip();
});
setInterval(() => {
  renderRiskMeta();
}, 30000);
(function () {
  var {
    notificationIcon: notificationButton,
    notifPanel: notificationPanel,
    notifBadge: notificationBadge,
    notifPanelBody: notificationPanelBody,
    notifEmpty: notificationEmptyState,
    notifClearBtn: clearNotificationsButton,
    notifCloseBtn: closeNotificationsButton
  } = getNotificationElements(document);
  if (notificationButton && notificationPanel) {
    var isPanelOpen = false;
    window.__dbPushAdminNotification = function (message) {
      if (message && message.id && message.message) {
        withStoredNotifications(function (notifications) {
          if (!notifications.some(function (item) {
            return item.id === message.id;
          })) {
            notifications.push({
              id: message.id,
              type: message.type || "info",
              title: message.title || null,
              message: message.message,
              link: message.link || null,
              linkText: message.linkText || null,
              sentAt: message.sentAt || new Date().toISOString(),
              read: false
            });
            if (notifications.length > 50) {
              notifications.splice(0, notifications.length - 50);
            }
            persistNotifications(notifications, function () {
              updateNotificationBadge(notifications);
              if (isPanelOpen) {
                renderNotifications(notifications);
              }
            });
          }
        });
      }
    };
    notificationButton.addEventListener("click", function (event) {
      event.stopPropagation();
      if (isPanelOpen) {
        closeNotificationPanel();
      } else {
        isPanelOpen = true;
        notificationPanel.style.display = "";
        withStoredNotifications(function (notifications) {
          renderNotifications(notifications);
          updateNotificationBadge(notifications);
          setTimeout(markNotificationsAsRead, 800);
        });
      }
    });
    if (closeNotificationsButton) {
      closeNotificationsButton.addEventListener("click", closeNotificationPanel);
    }
    if (clearNotificationsButton) {
      clearNotificationsButton.addEventListener("click", function () {
        persistNotifications([]);
        renderNotifications([]);
        updateNotificationBadge([]);
      });
    }
    document.addEventListener("click", function (event) {
      if (!!isPanelOpen && !notificationPanel.contains(event.target) && !notificationButton.contains(event.target)) {
        closeNotificationPanel();
      }
    });
    withStoredNotifications(updateNotificationBadge);
    chrome.storage.onChanged.addListener(function (dbAdminNotifications, areaName) {
      if (areaName === "local" && dbAdminNotifications.dbAdminNotifications) {
        var nextNotifications = dbAdminNotifications.dbAdminNotifications.newValue || [];
        updateNotificationBadge(nextNotifications);
        if (isPanelOpen) {
          renderNotifications(nextNotifications);
        }
      }
    });
  }
  function renderNotifications(notifications) {
    while (notificationPanelBody.firstChild && notificationPanelBody.firstChild !== notificationEmptyState) {
      notificationPanelBody.removeChild(notificationPanelBody.firstChild);
    }
    var notificationListFragment = document.createDocumentFragment();
    if (notifications && notifications.length !== 0) {
      notificationEmptyState.style.display = "none";
      notifications.slice().reverse().forEach(function (item) {
        var notificationItem = document.createElement("div");
        notificationItem.className = "notif-item" + (item.read ? "" : " unread");
        var notificationIcon = document.createElement("div");
        notificationIcon.className = "notif-icon " + (item.type || "info");
        notificationIcon.textContent = {
          success: "✅",
          error: "❌",
          warning: "⚠️",
          info: "ℹ️"
        }[item.type] || "ℹ️";
        var notificationContent = document.createElement("div");
        notificationContent.className = "notif-content";
        if (item.title) {
          var notificationTitle = document.createElement("div");
          notificationTitle.className = "notif-title";
          notificationTitle.textContent = item.title;
          notificationContent.appendChild(notificationTitle);
        }
        var notificationText = document.createElement("div");
        notificationText.className = "notif-text";
        notificationText.textContent = item.message || "";
        notificationContent.appendChild(notificationText);
        var notificationTime = document.createElement("div");
        notificationTime.className = "notif-time";
        notificationTime.textContent = function (sentAt) {
          if (!sentAt) {
            return "";
          }
          try {
            return formatNotificationTimeLabel(sentAt);
          } catch (error) {
            return "";
          }
        }(item.sentAt);
        notificationContent.appendChild(notificationTime);
        if (item.link) {
          var notificationLink = document.createElement("a");
          notificationLink.className = "notif-link";
          notificationLink.target = "_blank";
          notificationLink.href = typeof item.link == "string" && item.link.match(/^https?:\/\//i) ? item.link : "#";
          notificationLink.textContent = item.linkText || "Learn More";
          notificationContent.appendChild(notificationLink);
        }
        notificationItem.appendChild(notificationIcon);
        notificationItem.appendChild(notificationContent);
        notificationListFragment.appendChild(notificationItem);
      });
    } else {
      notificationEmptyState.style.display = "";
    }
    notificationPanelBody.insertBefore(notificationListFragment, notificationEmptyState);
  }
  function updateNotificationBadge(notifications) {
    notifications ||= [];
    var notificationCount = notifications.length;
    var unreadCount = notifications.filter(function (item) {
      return !item.read;
    }).length;
    notificationBadge.textContent = notificationCount > 99 ? "99+" : notificationCount;
    notificationBadge.style.display = notificationCount > 0 ? "" : "none";
    notificationBadge.classList.toggle("has-unread", unreadCount > 0);
  }
  function withStoredNotifications(callback) {
    chrome.storage.local.get(["dbAdminNotifications"], function (storedNotificationState) {
      callback(storedNotificationState && storedNotificationState.dbAdminNotifications || []);
    });
  }
  function persistNotifications(notifications, callback) {
    var notificationsPayload = {
      dbAdminNotifications: notifications
    };
    chrome.storage.local.set(notificationsPayload, callback);
  }
  function markNotificationsAsRead() {
    withStoredNotifications(function (notifications) {
      var hasResponded = false;
      notifications.forEach(function (item) {
        if (!item.read) {
          item.read = true;
          hasResponded = true;
        }
      });
      if (hasResponded) {
        persistNotifications(notifications, function () {
          updateNotificationBadge(notifications);
          renderNotifications(notifications);
        });
      }
    });
  }
  function closeNotificationPanel() {
    isPanelOpen = false;
    notificationPanel.style.display = "none";
  }
})();
chrome.storage.local.get(["bypasserSettings"], bypasserSettings => {
  const savedSettings = bypasserSettings.bypasserSettings || {};
  const cvcMode = savedSettings.cvcMode || (savedSettings.autoCvc === false ? "remove" : "generate");
  currentSettings = {
    enabled: savedSettings.enabled !== false,
    bin: Array.isArray(savedSettings.bin) ? savedSettings.bin : savedSettings.bin ? [savedSettings.bin] : [],
    proxy: savedSettings.proxy || "",
    cvcMode: cvcMode,
    customCvc: savedSettings.customCvc || "",
    autoCvc: cvcMode === "generate",
    autoScreenshot: savedSettings.autoScreenshot !== false,
    lastUpdated: savedSettings.lastUpdated || null
  };
  if (uiElements.statusToggle) {
    uiElements.statusToggle.checked = currentSettings.enabled;
  }
  if (uiElements.binInput) {
    uiElements.binInput.value = currentSettings.bin.join("\n");
  }
  if (uiElements.proxyInput) {
    uiElements.proxyInput.value = currentSettings.proxy;
  }
  if (uiElements.autoCvcToggle) {
    uiElements.autoCvcToggle.checked = currentSettings.autoCvc;
  }
  if (uiElements.screenshotToggle) {
    uiElements.screenshotToggle.checked = currentSettings.autoScreenshot;
  }
  renderStatusPanel();
});
chrome.storage.local.get(["bypasserAdvancedSettings"], bypasserAdvancedSettings => {
  applyThemeColor((bypasserAdvancedSettings.bypasserAdvancedSettings || {}).themeColor || "#4a9eff");
});
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initializeBootstrapLinks);
} else {
  initializeBootstrapLinks();
}
(function () {
  var panelToggleButton = document.getElementById("panelToggleBtn");
  var settingsPanel = document.querySelector(".panel-left");
  var panelToggleLabel = document.getElementById("panelToggleLabel");
  var collapseIcon = panelToggleButton ? panelToggleButton.querySelector(".panel-toggle-up") : null;
  var expandIcon = panelToggleButton ? panelToggleButton.querySelector(".panel-toggle-down") : null;
  if (panelToggleButton && settingsPanel) {
    var isActive = false;
    panelToggleButton.addEventListener("click", function () {
      if (isActive = !isActive) {
        settingsPanel.classList.add("panel-collapsed");
        if (panelToggleLabel) {
          panelToggleLabel.textContent = "Show Settings";
        }
        if (collapseIcon) {
          collapseIcon.style.display = "none";
        }
        if (expandIcon) {
          expandIcon.style.display = "";
        }
      } else {
        settingsPanel.classList.remove("panel-collapsed");
        if (panelToggleLabel) {
          panelToggleLabel.textContent = "Hide Settings";
        }
        if (collapseIcon) {
          collapseIcon.style.display = "";
        }
        if (expandIcon) {
          expandIcon.style.display = "none";
        }
      }
    });
  }
})();
chrome.storage.local.get(["disclaimerAccepted"], disclaimerAccepted => {
  if (!disclaimerAccepted.disclaimerAccepted) {
    const disclaimerOverlay = document.getElementById("disclaimerOverlay");
    if (disclaimerOverlay) {
      disclaimerOverlay.style.display = "block";
    }
  }
});
(function () {
  function renderAdminBannerNotification(message) {
    if (!message || !message.message) {
      return;
    }
    const dismissStorageKey = "dbNotifDismissed_" + message.id;
    chrome.storage.local.get([dismissStorageKey], storedDismissState => {
      if (storedDismissState[dismissStorageKey]) {
        return;
      }
      const notificationBanner = document.getElementById("notifBanner");
      const notificationBannerTitle = document.getElementById("notifBannerTitle");
      const notificationBannerMessage = document.getElementById("notifBannerMsg");
      const notificationBannerLink = document.getElementById("notifBannerLink");
      const notificationBannerIcon = document.getElementById("notifBannerIcon");
      const notificationBannerDismissButton = document.getElementById("notifBannerDismiss");
      if (!notificationBanner || !notificationBannerMessage) {
        return;
      }
      const type = message.type || "info";
      notificationBanner.className = "notif-banner notif-" + type;
      if (message.title && notificationBannerTitle) {
        notificationBannerTitle.textContent = message.title;
        notificationBannerTitle.style.display = "";
      } else if (notificationBannerTitle) {
        notificationBannerTitle.style.display = "none";
      }
      notificationBannerMessage.textContent = message.message;
      if (message.link && notificationBannerLink) {
        if (typeof message.link == "string" && message.link.match(/^https?:\/\//i)) {
          notificationBannerLink.href = message.link;
        } else {
          notificationBannerLink.href = "#";
        }
        notificationBannerLink.textContent = message.linkText || "Learn More";
        notificationBannerLink.style.display = "";
      }
      const bannerIconsByType = {
        info: "<svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><line x1=\"12\" y1=\"16\" x2=\"12\" y2=\"12\"/><line x1=\"12\" y1=\"8\" x2=\"12.01\" y2=\"8\"/></svg>",
        warning: "<svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z\"/><line x1=\"12\" y1=\"9\" x2=\"12\" y2=\"13\"/><line x1=\"12\" y1=\"17\" x2=\"12.01\" y2=\"17\"/></svg>",
        success: "<svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M22 11.08V12a10 10 0 1 1-5.93-9.14\"/><polyline points=\"22 4 12 14.01 9 11.01\"/></svg>",
        error: "<svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><line x1=\"15\" y1=\"9\" x2=\"9\" y2=\"15\"/><line x1=\"9\" y1=\"9\" x2=\"15\" y2=\"15\"/></svg>"
      };
      if (notificationBannerIcon && bannerIconsByType[type]) {
        notificationBannerIcon.innerHTML = bannerIconsByType[type];
      }
      notificationBanner.style.display = "";
      if (notificationBannerDismissButton) {
        notificationBannerDismissButton.addEventListener("click", () => {
          const options = {
            [dismissStorageKey]: true
          };
          notificationBanner.style.display = "none";
          chrome.storage.local.set(options);
        });
      }
    });
  }
  if (chrome && chrome.storage) {
    chrome.storage.local.get(["dbNotification"], dbNotification => {
      if (dbNotification.dbNotification) {
        renderAdminBannerNotification(dbNotification.dbNotification);
        if (window.__dbPushAdminNotification) {
          window.__dbPushAdminNotification(dbNotification.dbNotification);
        }
      }
    });
    (async function () {
      try {
        var urlCandidates = ["https://db-auth-svc-v2.testdeep.workers.dev"];
        try {
          urlCandidates = resolveRelayServerCandidates((await chrome.storage.local.get(["bypasserSettings", "bypasserAdvancedSettings"])) || {});
        } catch (error) {}
        var notificationResponse = null;
        for (const urlCandidate of urlCandidates) {
          try {
            const response = await fetch(urlCandidate + "/notification");
            if (response.ok) {
              notificationResponse = response;
              break;
            }
          } catch {}
        }
        if (!notificationResponse || !notificationResponse.ok) {
          return;
        }
        var notificationPayload = await notificationResponse.json();
        if (notificationPayload.notification && notificationPayload.notification.message) {
          await chrome.storage.local.set({
            dbNotification: notificationPayload.notification
          });
          renderAdminBannerNotification(notificationPayload.notification);
          if (window.__dbPushAdminNotification) {
            window.__dbPushAdminNotification(notificationPayload.notification);
          }
        } else {
          await chrome.storage.local.remove("dbNotification");
        }
      } catch (error) {}
    })();
  }
})();
(function () {
  function renderUpdateBanner(updateInfo) {
    if (!updateInfo || !updateInfo.latest) {
      return;
    }
    const dismissStorageKey = "dbUpdateDismissed_" + updateInfo.latest;
    chrome.storage.local.get([dismissStorageKey], storedDismissState => {
      if (storedDismissState[dismissStorageKey]) {
        return;
      }
      const updateBanner = document.getElementById("updateBanner");
      const updateBannerMessage = document.getElementById("updateBannerMsg");
      const updateBannerLink = document.getElementById("updateBannerLink");
      const updateBannerDismissButton = document.getElementById("updateBannerDismiss");
      if (updateBanner && updateBannerMessage) {
        updateBannerMessage.textContent = "v" + updateInfo.latest + " is available (you have v" + updateInfo.current + ")." + (updateInfo.changelog ? " " + updateInfo.changelog : "");
        if (updateInfo.downloadUrl && updateBannerLink) {
          if (typeof updateInfo.downloadUrl == "string" && updateInfo.downloadUrl.match(/^https?:\/\//i)) {
            updateBannerLink.href = updateInfo.downloadUrl;
          } else {
            updateBannerLink.href = "#";
          }
          updateBannerLink.style.display = "";
        }
        updateBanner.style.display = "";
        if (updateBannerDismissButton) {
          updateBannerDismissButton.addEventListener("click", () => {
            const options = {
              [dismissStorageKey]: true
            };
            updateBanner.style.display = "none";
            chrome.storage.local.set(options);
          });
        }
      }
    });
  }
  if (chrome && chrome.storage) {
    chrome.storage.local.get(["dbUpdateInfo"], dbUpdateInfo => {
      if (dbUpdateInfo.dbUpdateInfo) {
        renderUpdateBanner(dbUpdateInfo.dbUpdateInfo);
      }
    });
    (async function () {
      try {
        var urlCandidates = ["https://db-auth-svc-v2.testdeep.workers.dev"];
        try {
          urlCandidates = resolveRelayServerCandidates((await chrome.storage.local.get(["bypasserSettings", "bypasserAdvancedSettings"])) || {});
        } catch (error) {}
        var versionResponse = null;
        for (const urlCandidate of urlCandidates) {
          try {
            const response = await fetch(urlCandidate + "/version?v=2.7");
            if (response.ok) {
              versionResponse = response;
              break;
            }
          } catch {}
        }
        if (!versionResponse || !versionResponse.ok) {
          return;
        }
        var versionInfo = await versionResponse.json();
        if (versionInfo.updateAvailable && versionInfo.latest) {
          var dbUpdateInfo = {
            latest: versionInfo.latest,
            current: "2.7",
            downloadUrl: versionInfo.downloadUrl || null,
            changelog: versionInfo.changelog || null,
            checkedAt: new Date().toISOString()
          };
          await chrome.storage.local.set({
            dbUpdateInfo: dbUpdateInfo
          });
          renderUpdateBanner(dbUpdateInfo);
        } else {
          await chrome.storage.local.remove("dbUpdateInfo");
        }
      } catch (error) {}
    })();
  }
})();
