import "./_virtual_wxt-html-plugins.js";
import {
  g as loadPerformanceSettings,
  a as applyPerformanceSettings,
  b as applyPerformanceSettingsToElement
} from "./performance-helper.js";

const DEFAULT_THEME_COLOR = "#4a9eff";

const THEME_PRESETS = [
  {
    color: DEFAULT_THEME_COLOR,
    title: "Blue (Default)"
  },
  {
    color: "#8b5cf6",
    title: "Purple"
  },
  {
    color: "#10b981",
    title: "Green"
  },
  {
    color: "#f59e0b",
    title: "Orange"
  },
  {
    color: "#ef4444",
    title: "Red"
  },
  {
    color: "#ec4899",
    title: "Pink"
  },
  {
    color: "#06b6d4",
    title: "Cyan"
  },
  {
    color: "#6366f1",
    title: "Indigo"
  }
];

const DEVELOPER_SUPPORT_FIELDS = [
  {
    id: "binanceId",
    label: "Binance ID:"
  },
  {
    id: "usdtTrc20",
    label: "USDT TRC20:"
  },
  {
    id: "ltcAddress",
    label: "Litecoin (LTC):"
  }
];

const renderThemePresetButtons = () =>
  THEME_PRESETS.map(
    ({ color, title }) =>
      `<button type="button" class="theme-preset-btn" data-color="${color}" style="background: ${color};" title="${title}"></button>`
  ).join("");

const renderDeveloperSupportFields = () =>
  DEVELOPER_SUPPORT_FIELDS.map(
    ({ id, label }) =>
      `<div class="donate-input-group"><label class="donate-label"><span class="donate-label-text">${label}</span></label><div class="donate-input-wrapper"><input type="text" id="${id}" class="donate-input" value="Loading..." readonly><button type="button" class="donate-copy-btn" data-copy-target="${id}" aria-label="Copy to clipboard"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="copy-icon"><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><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="check-icon" style="display: none;"><polyline points="20 6 9 17 4 12" /></svg></button></div></div>`
  ).join("");

const appRoot = document.getElementById("app");
if (appRoot && !appRoot.dataset.rendered) {
  appRoot.innerHTML = `
  <iframe src="options.html" class="background-iframe" id="backgroundIframe" loading="lazy"></iframe>

  <div class="overlay">
    <div class="settings-popup">
      <div class="settings-popup-header">
        <div class="settings-popup-header-left">
          <h1>
            <img src="../assets/icons/icon48.png" alt="Naruto Bypasser Logo">
            Settings
          </h1>
          <p class="settings-header-subtitle" id="settingsHeaderLicenseStatus">NO License required for 3DS bypass</p>
        </div>
        <button class="close-button" id="closeButton" title="Close" type="button">
          <svg width="20" height="20" 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>
      </div>

      <div class="settings-popup-content">
        <div class="settings-container">
          <div class="settings-section">
            <div class="settings-section-title">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="3" />
                <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" />
              </svg>
              General Settings
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">CVC Mode</div>
                <div class="setting-description">Choose how to handle CVC/Security Code in payment requests</div>
              </div>
              <div class="setting-control">
                <div class="cvc-mode-group">
                  <select id="cvcModeSelect" class="select-input">
                    <option value="generate">Generate</option>
                    <option value="remove">Remove</option>
                    <option value="custom">Custom</option>
                  </select>
                  <input type="text" id="customCvcInput" class="setting-input" placeholder="e.g. 000" maxlength="4" pattern="[0-9]{3,4}" style="display: none; margin-top: 8px; max-width: 80px;">
                </div>
              </div>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">Auto Fill</div>
                <div class="setting-description">Automatically fill payment forms with card and billing information</div>
              </div>
              <div class="setting-control"><label class="toggle small"><input type="checkbox" id="autofillToggle"><span class="slider"></span></label></div>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">Auto Screenshot</div>
                <div class="setting-description">Automatically take screenshot on payment success</div>
              </div>
              <div class="setting-control"><label class="toggle small"><input type="checkbox" id="autoScreenshotToggle"><span class="slider"></span></label></div>
            </div>

            <div class="setting-item" id="threeDSSettingItem">
              <div class="setting-info">
                <div class="setting-label">3DS Bypass <span id="threeDSunLockBadge" class="setting-unlock-badge setting-unlock-badge-3ds" style="display:none;"><svg class="unlock-icon unlock-icon-gold" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg><span class="unlock-text">no Licenses Required</span></span></div>
                <div class="setting-description">Bypass 3D Secure authentication on Stripe payments</div>
              </div>
              <div class="setting-control"><label class="toggle small"><input type="checkbox" id="threeDSBypassToggle"><span class="slider"></span></label></div>
            </div>

            <div class="setting-item" id="analyticsProtectionSettingItem">
              <div class="setting-info">
                <div class="setting-label">Enable Analytics Protection <span id="analyticsProtectionUnlockBadge" style="display:none;font-size:11px;color:#ef4444;margin-left:6px;font-weight:500;vertical-align:middle;">🔓 no License Required</span></div>
                <div class="setting-description">Block analytics and tracking requests in real time across websites</div>
              </div>
              <div class="setting-control"><label class="toggle small"><input type="checkbox" id="analyticsProtectionToggle"><span class="slider"></span></label></div>
            </div>
          </div>

          <div class="settings-section">
            <div class="settings-section-title">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                <path d="M7 11V7a5 5 0 0 1 10 0v4" />
              </svg>
              Captcha Bypass Settings
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">Auto Captcha Bypass</div>
                <div class="setting-description">Automatically solve reCAPTCHA, hCaptcha, and Turnstile</div>
              </div>
              <div class="setting-control"><label class="toggle small"><input type="checkbox" id="autoCaptchaToggle"><span class="slider"></span></label></div>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">Captcha Service</div>
                <div class="setting-description">Choose your captcha solving service</div>
              </div>
              <div class="setting-control">
                <select id="captchaService" class="select-input">
                  <option value="autoclick">Auto-Click (Free - No API Key)</option>
                  <option value="2captcha">2Captcha</option>
                  <option value="anticaptcha">AntiCaptcha</option>
                  <option value="capsolver">CapSolver</option>
                  <option value="nocaptchaai">NoCaptchaAI</option>
                  <option value="nopecha">NopeCHA</option>
                </select>
              </div>
            </div>

            <div class="setting-item" id="apiKeySetting">
              <div class="setting-info"><div class="setting-label">API Key</div><div class="setting-description">Your captcha solving service API key (not required for Auto-Click mode)</div></div>
              <div class="setting-control"><input type="password" id="captchaApiKey" placeholder="Enter API key (optional for Auto-Click)" class="setting-input"></div>
            </div>
          </div>

          <div class="settings-section">
            <div class="settings-section-title" id="autofillSectionToggle" style="cursor: pointer; user-select: none;">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" /></svg>
              Autofill Settings
              <svg class="section-chevron rotated" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; height: 14px; margin-left: auto;"><path d="M3 4.5L6 7.5L9 4.5" /></svg>
            </div>

            <div class="autofill-section-content collapsed" id="autofillSectionContent">
              <div class="setting-item" style="margin-bottom: 20px;"><div class="setting-info" style="width: 100%;"><div class="setting-description" style="color: rgba(255, 255, 255, 0.7); font-size: 13px;">Customize your autofill preferences for payment forms</div></div></div>
              <div class="custom-field-group"><label class="custom-field-label" for="autofillDelay">Auto Fill Delay (seconds)</label><input type="number" id="autofillDelay" class="custom-field-input" placeholder="7" value="7" min="1" max="30"><div class="custom-field-hint">Set the delay before autofill starts (1-30 seconds)</div></div>
              <div class="custom-field-group"><label class="custom-field-label" for="customCardNumber">Card Number (16 digits)</label><input type="text" id="customCardNumber" class="custom-field-input" placeholder="0000000000000000" value="0000000000000000" maxlength="19" pattern="[0-9 ]{13,19}"></div>
              <div class="custom-field-group"><label class="custom-field-label" for="customCardExpiry">Card Expiry (MM/YY)</label><input type="text" id="customCardExpiry" class="custom-field-input" placeholder="08/29" value="08/29" maxlength="5" pattern="[0-9]{2}/[0-9]{2}"></div>
              <div class="custom-field-group"><label class="custom-field-label" for="customCardCvc">Card CVC (3 digits)</label><input type="text" id="customCardCvc" class="custom-field-input" placeholder="000" value="000" maxlength="4" pattern="[0-9]{3,4}"></div>
              <div class="custom-field-group"><label class="custom-field-label" for="customName">Full Name</label><input type="text" id="customName" class="custom-field-input" placeholder="NOT YOURS NARUTO" maxlength="100"></div>
              <div class="custom-field-group"><label class="custom-field-label" for="customAddress1">Street Address 1</label><input type="text" id="customAddress1" class="custom-field-input" placeholder="St 123 Street LN" maxlength="200"></div>
              <div class="custom-field-group"><label class="custom-field-label" for="customAddress2">Street Address 2</label><input type="text" id="customAddress2" class="custom-field-input" placeholder="St 123 Street LN" maxlength="200"></div>
              <div class="custom-field-group"><label class="custom-field-label" for="customLocality">Locality</label><input type="text" id="customLocality" class="custom-field-input" placeholder="New York" maxlength="100"></div>

              <div class="custom-autofill-section" style="margin-top: 24px; padding-top: 20px; border-top: 1px solid rgba(255, 255, 255, 0.1);">
                <div class="setting-item" style="margin-bottom: 16px;"><div class="setting-info" style="width: 100%;"><div class="setting-label">Random Autofill Options</div></div></div>
                <div class="setting-item"><div class="setting-info"><div class="setting-label">Use Random Names</div><div class="setting-description">Generate random names for each checkout</div></div><div class="setting-control"><label class="toggle small"><input type="checkbox" id="useRandomNames"><span class="slider"></span></label></div></div>
                <div class="setting-item"><div class="setting-info"><div class="setting-label">Use Random Addresses</div><div class="setting-description">Generate random addresses for each checkout</div></div><div class="setting-control"><label class="toggle small"><input type="checkbox" id="useRandomAddresses"><span class="slider"></span></label></div></div>
              </div>

              <div class="custom-autofill-section" style="margin-top: 24px; padding-top: 20px; border-top: 1px solid rgba(255, 255, 255, 0.1);">
                <div class="setting-item" style="margin-bottom: 16px;"><div class="setting-info" style="width: 100%;"><div class="setting-label">Custom Email Domain</div><div class="setting-description" style="color: rgba(255, 255, 255, 0.7); font-size: 13px; margin-top: 4px;">Generate email using format: {name}@{domain}</div></div></div>
                <div class="setting-item" style="margin-bottom: 16px;"><div class="setting-info"><div class="setting-label">Enable Custom Email Domain</div><div class="setting-description">Generate email addresses using your custom domain</div></div><div class="setting-control"><label class="toggle small"><input type="checkbox" id="customEmailDomainEnabled"><span class="slider"></span></label></div></div>
                <div class="custom-field-group"><label class="custom-field-label" for="customEmailDomain">Email Domain</label><input type="text" id="customEmailDomain" class="custom-field-input" placeholder="NOT YOURS NARUTO" maxlength="100" pattern="[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"><div class="custom-field-hint">Enter domain (e.g., deepbypasser.net). Email will be generated as: {name}@{domain}</div></div>
              </div>

              <div class="button-group" style="margin-top: 24px; gap: 12px;"><button type="button" id="saveAutofillSettingsBtn" class="btn-primary" style="flex: 1;">Save Autofill Settings</button><button type="button" id="resetAutofillSettingsBtn" class="btn-secondary" style="flex: 1;">Reset to Default</button></div>
            </div>
          </div>

          <div class="settings-section">
            <div class="settings-section-title">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="13.5" cy="6.5" r=".5" /><circle cx="17.5" cy="10.5" r=".5" /><circle cx="8.5" cy="7.5" r=".5" /><circle cx="6.5" cy="12.5" r=".5" /><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z" /></svg>
              Theme Settings
            </div>
            <div class="setting-item"><div class="setting-info"><div class="setting-label">Theme Color</div><div class="setting-description">Choose your preferred theme color</div></div><div class="setting-control"><div style="display: flex; align-items: center; gap: 12px; width: 100%;"><input type="color" id="themeColorPicker" value="${DEFAULT_THEME_COLOR}" style="width: 60px; height: 40px; border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 8px; cursor: pointer; background: transparent;"><button type="button" id="resetThemeColor" class="btn-secondary" style="padding: 8px 16px; font-size: 12px; white-space: nowrap;">Reset</button></div></div></div>
            <div class="setting-item" style="margin-top: 16px;"><div class="setting-info"><div class="setting-label">Preset Colors</div><div class="setting-description">Quick select from popular colors</div></div><div class="setting-control"><div style="display: flex; gap: 8px; flex-wrap: wrap; width: 100%;">${renderThemePresetButtons()}</div></div></div>
          </div>

          <div class="settings-section">
            <div class="settings-section-title"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" /></svg>Telegram Notifications</div>
            <div class="setting-item"><div class="setting-info"><div class="setting-label">Enable</div><div class="setting-description">Send notifications to Telegram when payment events occur</div></div><div class="setting-control"><label class="toggle small"><input type="checkbox" id="telegramEnabled"><span class="slider"></span></label></div></div>
            <div class="telegram-input-group"><label class="telegram-label"><span class="telegram-label-text">Bot Token:</span></label><div class="telegram-input-wrapper"><input type="password" id="telegramBotToken" class="telegram-input" placeholder="Enter bot token from @BotFather" autocomplete="off"><button type="button" class="telegram-toggle-visibility" aria-label="Toggle visibility"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="eye-icon"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" /></svg><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="eye-off-icon" style="display: none;"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" /><line x1="1" y1="1" x2="23" y2="23" /></svg></button></div><div class="telegram-hint">Your Telegram bot token from @BotFather</div></div>
            <div class="telegram-input-group"><label class="telegram-label"><span class="telegram-label-text">Chat ID:</span></label><div class="telegram-input-wrapper"><input type="text" id="telegramChatId" class="telegram-input" placeholder="Enter chat ID (use @userinfobot)" autocomplete="off" inputmode="numeric"></div><div class="telegram-hint">Your Telegram chat ID (use @userinfobot to get your ID)</div></div>
            <div class="telegram-button-group"><button type="button" id="testTelegramConnection" class="telegram-test-btn"><span>Test Connection</span></button></div>
          </div>

          <div class="settings-section">
            <div class="settings-section-title"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3" /><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" /></svg>Performance Settings</div>
            <div class="setting-item"><div class="setting-info"><div class="setting-label">Enable Hardware Acceleration</div><div class="setting-description">Use GPU acceleration for better performance</div></div><div class="setting-control"><label class="toggle small"><input type="checkbox" id="hardwareAcceleration" checked><span class="slider"></span></label></div></div>
            <div class="setting-item"><div class="setting-info"><div class="setting-label">Reduce Animations</div><div class="setting-description">Disable animations for better performance on low-end devices</div></div><div class="setting-control"><label class="toggle small"><input type="checkbox" id="reduceAnimations"><span class="slider"></span></label></div></div>
          </div>

          <div class="settings-section">
            <div class="settings-section-title"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 11l3 3L22 4" /><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" /></svg>Button Auto-Clicker</div>
            <div class="setting-item"><div class="setting-info"><div class="setting-label">Auto-Click Payment Buttons</div><div class="setting-description">Automatically click Pay, Subscribe, Checkout, and other payment buttons</div></div><div class="setting-control"><label class="toggle small"><input type="checkbox" id="autoClickButtons"><span class="slider"></span></label></div></div>
            <div class="setting-item"><div class="setting-info"><div class="setting-label">Click Delay (milliseconds)</div><div class="setting-description">Delay before auto-clicking payment buttons (default: 2000ms)</div></div><div class="setting-control"><input type="number" id="autoClickDelay" class="number-input" placeholder="2000" min="0" max="10000" step="100"></div></div>
          </div>

          <div class="settings-section">
            <div class="settings-section-title"><svg 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>About</div>
            <div class="setting-item"><div class="setting-info"><div class="setting-label">Version</div><div class="setting-description">Naruto Bypasser v99999</div></div></div>
            <div class="setting-item"><div class="setting-info"><div class="setting-label">Build Date</div><div class="setting-description" id="buildDate">Loading...</div></div></div>
          </div>

          <div class="settings-section" style="display: block; visibility: visible;">
            <div class="settings-section-title"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" /></svg>Developer</div>
            <div class="setting-item"><div class="setting-info"><div class="setting-label">Notyoursnaruto</div><div class="setting-description">Developer responsible for the development of the Naruto Bypasser extension.</div></div></div>
            <div class="settings-developer-links" style="margin-top: 16px;"><a href="https://t.me/NotYoursNaruto" target="_blank" rel="noopener noreferrer"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" /></svg>Telegram</a></div>
            <div style="margin-top: 24px; padding-top: 20px; border-top: 1px solid rgba(255, 255, 255, 0.1);"><div class="setting-item" style="margin-bottom: 16px;"><div class="setting-info"><div class="setting-label">Support Developer</div><div class="setting-description">If you find this extension helpful, consider supporting its development.</div></div></div>${renderDeveloperSupportFields()}</div>
          </div>

          <div style="margin-top: 20px; text-align: center;">
            <button class="btn-primary" id="saveSettingsBtn" style="min-width: 200px;">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" /><polyline points="17 21 17 13 7 13 7 21" /><polyline points="7 3 7 8 15 8" /></svg>
              Save Settings
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="notification" id="notification"></div>
`;
  appRoot.dataset.rendered = "true";
}
const settingsUi = {
  cvcModeSelect: document.getElementById("cvcModeSelect"),
  customCvcInput: document.getElementById("customCvcInput"),
  autoScreenshotToggle: document.getElementById("autoScreenshotToggle"),
  autoCaptchaToggle: document.getElementById("autoCaptchaToggle"),
  captchaService: document.getElementById("captchaService"),
  captchaApiKey: document.getElementById("captchaApiKey"),
  autofillToggle: document.getElementById("autofillToggle"),
  autofillCardDataToggle: document.getElementById("autofillCardDataToggle"),
  autofillBillingDataToggle: document.getElementById("autofillBillingDataToggle"),
  autofillDelay: document.getElementById("autofillDelay"),
  customCardNumber: document.getElementById("customCardNumber"),
  customCardExpiry: document.getElementById("customCardExpiry"),
  customCardCvc: document.getElementById("customCardCvc"),
  customName: document.getElementById("customName"),
  customAddress1: document.getElementById("customAddress1"),
  customAddress2: document.getElementById("customAddress2"),
  customLocality: document.getElementById("customLocality"),
  useRandomNames: document.getElementById("useRandomNames"),
  useRandomAddresses: document.getElementById("useRandomAddresses"),
  customEmailDomainEnabled: document.getElementById("customEmailDomainEnabled"),
  customEmailDomain: document.getElementById("customEmailDomain"),
  saveAutofillSettingsBtn: document.getElementById("saveAutofillSettingsBtn"),
  resetAutofillSettingsBtn: document.getElementById("resetAutofillSettingsBtn"),
  hardwareAcceleration: document.getElementById("hardwareAcceleration"),
  reduceAnimations: document.getElementById("reduceAnimations"),
  themeColorPicker: document.getElementById("themeColorPicker"),
  resetThemeColor: document.getElementById("resetThemeColor"),
  telegramEnabled: document.getElementById("telegramEnabled"),
  telegramBotToken: document.getElementById("telegramBotToken"),
  telegramChatId: document.getElementById("telegramChatId"),
  testTelegramConnection: document.getElementById("testTelegramConnection"),
  autoClickButtons: document.getElementById("autoClickButtons"),
  autoClickDelay: document.getElementById("autoClickDelay"),
  threeDSBypassToggle: document.getElementById("threeDSBypassToggle"),
  analyticsProtectionToggle: document.getElementById("analyticsProtectionToggle"),
  relayServerUrl: document.getElementById("relayServerUrl"),
  saveSettingsBtn: document.getElementById("saveSettingsBtn"),
  buildDate: document.getElementById("buildDate"),
  notification: document.getElementById("notification")
};

function setActiveThemePreset(activeColor) {
  document.querySelectorAll(".theme-preset-btn").forEach(presetButton => {
    presetButton.classList.toggle("active", presetButton.dataset.color === activeColor);
  });
}

function applyThemeColor(themeColor) {
  if (!themeColor) {
    return;
  }
  const hexColor = themeColor.replace("#", "");
  const red = parseInt(hexColor.substring(0, 2), 16);
  const green = parseInt(hexColor.substring(2, 4), 16);
  const blue = parseInt(hexColor.substring(4, 6), 16);
  const secondaryColor = `rgb(${Math.min(255, red + 30)}, ${Math.min(255, green + 30)}, ${Math.min(255, blue + 30)})`;
  const accentRed = Math.min(255, Math.max(0, red - 20));
  const accentGreen = Math.min(255, Math.max(0, green - 10));
  const accentBlue = Math.min(255, blue + 30);
  const accentColor = `rgb(${accentRed}, ${accentGreen}, ${accentBlue})`;
  const themePrimaryRgb = `${red}, ${green}, ${blue}`;
  const themeAccentRgb = `${accentRed}, ${accentGreen}, ${accentBlue}`;
  const hueRotation = Math.round((((red + green + blue) / 3) * 60) / 255);
  document.documentElement.style.setProperty("--theme-primary", themeColor);
  document.documentElement.style.setProperty("--theme-secondary", secondaryColor);
  document.documentElement.style.setProperty("--theme-accent", accentColor);
  document.documentElement.style.setProperty("--theme-primary-rgb", themePrimaryRgb);
  document.documentElement.style.setProperty("--theme-accent-rgb", themeAccentRgb);
  let dynamicThemeStyles = document.getElementById("dynamic-theme-styles");
  if (!dynamicThemeStyles) {
    dynamicThemeStyles = document.createElement("style");
    dynamicThemeStyles.id = "dynamic-theme-styles";
    document.head.appendChild(dynamicThemeStyles);
  }
  dynamicThemeStyles.textContent = `
      body {
        background:
          linear-gradient(135deg, rgba(${themePrimaryRgb}, 0.12) 0%, rgba(${themeAccentRgb}, 0.12) 100%),
          #0a0a0f !important;
      }
      body::before {
        background:
          radial-gradient(circle at 0% 0%, rgba(${themePrimaryRgb}, 0.25) 0%, transparent 70%),
          radial-gradient(circle at 100% 100%, rgba(${themeAccentRgb}, 0.25) 0%, transparent 70%),
          radial-gradient(circle at 50% 50%, rgba(${themePrimaryRgb}, 0.15) 0%, transparent 80%) !important;
      }
      body::after {
        background:
          radial-gradient(circle at 0% 0%, rgba(${themePrimaryRgb}, 0.18) 0%, transparent 75%),
          radial-gradient(circle at 100% 100%, rgba(${themeAccentRgb}, 0.18) 0%, transparent 75%) !important;
      }
      .overlay {
        background: rgba(0, 0, 0, 0.4) !important;
      }
      .background-iframe {
        filter: hue-rotate(${hueRotation}deg) saturate(1.4) brightness(0.85) !important;
        -webkit-filter: hue-rotate(${hueRotation}deg) saturate(1.4) brightness(0.85) !important;
      }
    `;
  const backgroundIframe = document.getElementById("backgroundIframe");
  if (backgroundIframe && backgroundIframe.contentDocument) {
    try {
      backgroundIframe.contentDocument.documentElement.style.setProperty(
        "--theme-primary",
        themeColor
      );
      backgroundIframe.contentDocument.documentElement.style.setProperty(
        "--theme-secondary",
        secondaryColor
      );
      backgroundIframe.contentDocument.documentElement.style.setProperty(
        "--theme-accent",
        accentColor
      );
      backgroundIframe.contentDocument.documentElement.style.setProperty(
        "--theme-primary-rgb",
        themePrimaryRgb
      );
      backgroundIframe.contentDocument.documentElement.style.setProperty(
        "--theme-accent-rgb",
        themeAccentRgb
      );
      backgroundIframe.contentWindow.postMessage(
        {
          type: "UPDATE_THEME",
          themeColor: themeColor,
          themePrimaryRgb: themePrimaryRgb,
          themeAccentRgb: themeAccentRgb
        },
        "*"
      );
    } catch (error) {
      console.debug("[Settings] Ignored non-fatal error:", error);
    }
  }
}
function loadSettingsIntoUi() {
  requestAnimationFrame(() => {
    chrome.storage.local.get(["bypasserSettings", "bypasserAdvancedSettings"], storedSettings => {
      if (chrome.runtime.lastError) {
        console.error("Failed to load settings:", chrome.runtime.lastError.message);
        return;
      }
      const bypasserSettings = (storedSettings && storedSettings.bypasserSettings) || {};
      const bypasserAdvancedSettings =
        (storedSettings && storedSettings.bypasserAdvancedSettings) || {};
      settingsState.bypasserSettings = bypasserSettings;
      settingsState.bypasserAdvancedSettings = bypasserAdvancedSettings;
      const cvcMode =
        bypasserSettings.cvcMode || (bypasserSettings.autoCvc === false ? "remove" : "generate");
      if (settingsUi.cvcModeSelect) {
        settingsUi.cvcModeSelect.value = cvcMode;
        updateCustomCvcVisibility();
      }
      if (settingsUi.customCvcInput) {
        settingsUi.customCvcInput.value = bypasserSettings.customCvc || "";
      }
      if (settingsUi.autoScreenshotToggle) {
        const checked =
          bypasserSettings.autoScreenshot !== undefined ? bypasserSettings.autoScreenshot : true;
        if (settingsUi.autoScreenshotToggle.checked !== checked) {
          settingsUi.autoScreenshotToggle.checked = checked;
        }
      }
      if (settingsUi.threeDSBypassToggle) {
        const checked =
          bypasserSettings.threeDSBypass !== undefined ? bypasserSettings.threeDSBypass : true;
        if (settingsUi.threeDSBypassToggle.checked !== checked) {
          settingsUi.threeDSBypassToggle.checked = checked;
        }
      }
      if (settingsUi.analyticsProtectionToggle) {
        const checked =
          bypasserSettings.analyticsProtection !== undefined
            ? bypasserSettings.analyticsProtection
            : false;
        if (settingsUi.analyticsProtectionToggle.checked !== checked) {
          settingsUi.analyticsProtectionToggle.checked = checked;
        }
      }
      (async function () {
        try {
          const licenseStorage = await chrome.storage.local.get(["dbLicense"]);
          let hasValidLicense = false;
          let hasPremiumLicense = false;
          if (licenseStorage.dbLicense && licenseStorage.dbLicense.valid) {
            if (
              licenseStorage.dbLicense.expiresAt &&
              new Date(licenseStorage.dbLicense.expiresAt) < new Date()
            ) {
              hasValidLicense = false;
              hasPremiumLicense = false;
            } else {
              hasValidLicense = true;
              const planName = String(licenseStorage.dbLicense.plan || "")
                .trim()
                .toLowerCase();
              hasPremiumLicense = !["trial", "free", "basic"].includes(planName);
            }
          }
          const updateUnlockedSettingState = (
            toggleElement,
            badgeId,
            settingItemId,
            requiresPremiumLicense
          ) => {
            const unlockBadge = document.getElementById(badgeId);
            const settingItem = document.getElementById(settingItemId);
            if (!(requiresPremiumLicense ? hasPremiumLicense : hasValidLicense)) {
              if (toggleElement) {
                toggleElement.checked = false;
                toggleElement.disabled = true;
              }
              if (unlockBadge) {
                unlockBadge.style.display = "inline-flex";
              }
              if (settingItem) {
                settingItem.style.opacity = "0.5";
              }
              return;
            }
            if (toggleElement) {
              toggleElement.disabled = false;
            }
            if (unlockBadge) {
              unlockBadge.style.display = "none";
            }
            if (settingItem) {
              settingItem.style.opacity = "1";
            }
          };
          updateUnlockedSettingState(
            settingsUi.threeDSBypassToggle,
            "threeDSUnlockBadge",
            "threeDSSettingItem",
            true
          );
          updateUnlockedSettingState(
            settingsUi.analyticsProtectionToggle,
            "analyticsProtectionUnlockBadge",
            "analyticsProtectionSettingItem",
            false
          );
          const licenseStatusLabel = document.getElementById("settingsHeaderLicenseStatus");
          if (licenseStatusLabel) {
            if (hasValidLicense) {
              licenseStatusLabel.textContent = hasPremiumLicense
                ? "License: Active — 3DS bypass available"
                : "License: Active";
              licenseStatusLabel.classList.add("license-active");
            } else {
              licenseStatusLabel.textContent = "NO License required for 3DS bypass";
              licenseStatusLabel.classList.remove("license-active");
            }
          }
        } catch (error) {
          console.debug("[Settings] Ignored non-fatal error:", error);
        }
      })();
      if (settingsUi.autoCaptchaToggle) {
        settingsUi.autoCaptchaToggle.checked =
          bypasserAdvancedSettings.autoCaptcha !== undefined
            ? bypasserAdvancedSettings.autoCaptcha
            : false;
      }
      if (settingsUi.captchaService) {
        settingsUi.captchaService.value = bypasserAdvancedSettings.captchaService || "autoclick";
      }
      if (settingsUi.captchaApiKey) {
        settingsUi.captchaApiKey.value = bypasserAdvancedSettings.captchaApiKey || "";
      }
      if (settingsUi.autofillToggle) {
        settingsUi.autofillToggle.checked =
          bypasserAdvancedSettings.autofill !== undefined
            ? bypasserAdvancedSettings.autofill
            : true;
      }
      if (settingsUi.autofillCardDataToggle) {
        settingsUi.autofillCardDataToggle.checked =
          bypasserAdvancedSettings.autofillCardData !== undefined
            ? bypasserAdvancedSettings.autofillCardData
            : true;
      }
      if (settingsUi.autofillBillingDataToggle) {
        settingsUi.autofillBillingDataToggle.checked =
          bypasserAdvancedSettings.autofillBillingData !== undefined
            ? bypasserAdvancedSettings.autofillBillingData
            : true;
      }
      if (settingsUi.autofillDelay) {
        settingsUi.autofillDelay.value =
          bypasserAdvancedSettings.autofillDelay !== undefined
            ? bypasserAdvancedSettings.autofillDelay
            : 7;
      }
      if (settingsUi.customCardNumber) {
        settingsUi.customCardNumber.value =
          bypasserAdvancedSettings.customCardNumber || "0000000000000000";
      }
      if (settingsUi.customCardExpiry) {
        settingsUi.customCardExpiry.value = bypasserAdvancedSettings.customCardExpiry || "08/29";
      }
      if (settingsUi.customCardCvc) {
        settingsUi.customCardCvc.value = bypasserAdvancedSettings.customCardCvc || "000";
      }
      if (settingsUi.customName) {
        settingsUi.customName.value = bypasserAdvancedSettings.customName || "";
      }
      if (settingsUi.customAddress1) {
        settingsUi.customAddress1.value = bypasserAdvancedSettings.customAddress1 || "";
      }
      if (settingsUi.customAddress2) {
        settingsUi.customAddress2.value = bypasserAdvancedSettings.customAddress2 || "";
      }
      if (settingsUi.customLocality) {
        settingsUi.customLocality.value = bypasserAdvancedSettings.customLocality || "";
      }
      if (settingsUi.useRandomNames) {
        settingsUi.useRandomNames.checked =
          bypasserAdvancedSettings.useRandomNames !== undefined
            ? bypasserAdvancedSettings.useRandomNames
            : false;
      }
      if (settingsUi.useRandomAddresses) {
        settingsUi.useRandomAddresses.checked =
          bypasserAdvancedSettings.useRandomAddresses !== undefined
            ? bypasserAdvancedSettings.useRandomAddresses
            : false;
      }
      if (settingsUi.customEmailDomainEnabled) {
        settingsUi.customEmailDomainEnabled.checked =
          bypasserAdvancedSettings.customEmailDomainEnabled !== undefined
            ? bypasserAdvancedSettings.customEmailDomainEnabled
            : false;
      }
      if (settingsUi.customEmailDomain) {
        settingsUi.customEmailDomain.value = bypasserAdvancedSettings.customEmailDomain || "";
      }
      if (settingsUi.telegramEnabled) {
        settingsUi.telegramEnabled.checked =
          undefined !== bypasserAdvancedSettings.telegramEnabled
            ? bypasserAdvancedSettings.telegramEnabled
            : false;
      }
      if (settingsUi.telegramBotToken) {
        settingsUi.telegramBotToken.value = bypasserAdvancedSettings.telegramBotToken || "";
      }
      if (settingsUi.telegramChatId) {
        settingsUi.telegramChatId.value = bypasserAdvancedSettings.telegramChatId || "";
      }
      if (settingsUi.autoClickButtons) {
        settingsUi.autoClickButtons.checked =
          undefined !== bypasserAdvancedSettings.autoClickButtons
            ? bypasserAdvancedSettings.autoClickButtons
            : true;
      }
      if (settingsUi.autoClickDelay) {
        settingsUi.autoClickDelay.value = bypasserAdvancedSettings.autoClickDelay || 2000;
      }
      if (settingsUi.relayServerUrl) {
        settingsUi.relayServerUrl.value = bypasserAdvancedSettings.relayServerUrl || "";
      }
      updateCustomCvcVisibility();
      updateCaptchaApiKeyVisibility();
      if (settingsUi.hardwareAcceleration) {
        settingsUi.hardwareAcceleration.checked =
          bypasserAdvancedSettings.hardwareAcceleration !== undefined
            ? bypasserAdvancedSettings.hardwareAcceleration
            : true;
      }
      if (settingsUi.reduceAnimations) {
        settingsUi.reduceAnimations.checked =
          bypasserAdvancedSettings.reduceAnimations !== undefined
            ? bypasserAdvancedSettings.reduceAnimations
            : false;
      }
      const themeColor = bypasserAdvancedSettings.themeColor || DEFAULT_THEME_COLOR;
      if (settingsUi.themeColorPicker) {
        settingsUi.themeColorPicker.value = themeColor;
        applyThemeColor(themeColor);
      }
      setActiveThemePreset(themeColor);
      if (settingsUi.buildDate) {
        settingsUi.buildDate.textContent = new Date().toLocaleDateString("en-US", {
          year: "numeric",
          month: "long",
          day: "numeric"
        });
      }
    });
  });
}
let settingsState = {
  bypasserSettings: {},
  bypasserAdvancedSettings: {}
};
let isSaveInProgress = false;
let saveDebounceTimeoutId = null;
let saveAnimationFrameId = null;
function scheduleSettingsSave(saveImmediately = false) {
  if (saveDebounceTimeoutId) {
    clearTimeout(saveDebounceTimeoutId);
  }
  if (saveAnimationFrameId) {
    cancelAnimationFrame(saveAnimationFrameId);
  }
  if (saveImmediately) {
    saveAnimationFrameId = requestAnimationFrame(() => {
      persistSettings();
    });
  } else {
    saveDebounceTimeoutId = setTimeout(() => {
      saveAnimationFrameId = requestAnimationFrame(() => {
        persistSettings();
      });
    }, 200);
  }
}
function persistSettings() {
  if (isSaveInProgress) {
    return;
  }
  isSaveInProgress = true;
  const cvcMode = settingsUi.cvcModeSelect
    ? settingsUi.cvcModeSelect.value
    : settingsState.bypasserSettings.cvcMode || "generate";
  const customCvc = settingsUi.customCvcInput
    ? settingsUi.customCvcInput.value.trim()
    : settingsState.bypasserSettings.customCvc || "";
  const bypasserSettings = {
    ...settingsState.bypasserSettings,
    cvcMode: cvcMode,
    customCvc: customCvc,
    autoCvc: cvcMode === "generate",
    autoScreenshot: settingsUi.autoScreenshotToggle
      ? settingsUi.autoScreenshotToggle.checked
      : settingsState.bypasserSettings.autoScreenshot !== undefined
        ? settingsState.bypasserSettings.autoScreenshot
        : true,
    threeDSBypass: settingsUi.threeDSBypassToggle
      ? settingsUi.threeDSBypassToggle.checked
      : settingsState.bypasserSettings.threeDSBypass !== undefined
        ? settingsState.bypasserSettings.threeDSBypass
        : true,
    analyticsProtection: settingsUi.analyticsProtectionToggle
      ? settingsUi.analyticsProtectionToggle.checked
      : settingsState.bypasserSettings.analyticsProtection !== undefined
        ? settingsState.bypasserSettings.analyticsProtection
        : false,
    lastUpdated: Date.now()
  };
  const bypasserAdvancedSettings = {
    ...settingsState.bypasserAdvancedSettings,
    autoCaptcha: settingsUi.autoCaptchaToggle
      ? settingsUi.autoCaptchaToggle.checked
      : settingsState.bypasserAdvancedSettings.autoCaptcha !== undefined
        ? settingsState.bypasserAdvancedSettings.autoCaptcha
        : false,
    captchaService: settingsUi.captchaService
      ? settingsUi.captchaService.value
      : settingsState.bypasserAdvancedSettings.captchaService || "autoclick",
    captchaApiKey: settingsUi.captchaApiKey
      ? settingsUi.captchaApiKey.value.trim()
      : settingsState.bypasserAdvancedSettings.captchaApiKey || "",
    autofill: settingsUi.autofillToggle ? settingsUi.autofillToggle.checked : true,
    autofillCardData: settingsUi.autofillCardDataToggle
      ? settingsUi.autofillCardDataToggle.checked
      : true,
    autofillBillingData: settingsUi.autofillBillingDataToggle
      ? settingsUi.autofillBillingDataToggle.checked
      : true,
    autofillDelay: (settingsUi.autofillDelay && parseInt(settingsUi.autofillDelay.value)) || 7,
    customCardNumber: settingsUi.customCardNumber ? settingsUi.customCardNumber.value.trim() : "",
    customCardExpiry: settingsUi.customCardExpiry ? settingsUi.customCardExpiry.value.trim() : "",
    customCardCvc: settingsUi.customCardCvc ? settingsUi.customCardCvc.value.trim() : "",
    customName: settingsUi.customName ? settingsUi.customName.value.trim() : "",
    customAddress1: settingsUi.customAddress1 ? settingsUi.customAddress1.value.trim() : "",
    customAddress2: settingsUi.customAddress2 ? settingsUi.customAddress2.value.trim() : "",
    customLocality: settingsUi.customLocality ? settingsUi.customLocality.value.trim() : "",
    useRandomNames: !!settingsUi.useRandomNames && settingsUi.useRandomNames.checked,
    useRandomAddresses: !!settingsUi.useRandomAddresses && settingsUi.useRandomAddresses.checked,
    customEmailDomainEnabled:
      !!settingsUi.customEmailDomainEnabled && settingsUi.customEmailDomainEnabled.checked,
    customEmailDomain: settingsUi.customEmailDomain
      ? settingsUi.customEmailDomain.value.trim()
      : "",
    hardwareAcceleration: settingsUi.hardwareAcceleration
      ? settingsUi.hardwareAcceleration.checked
      : settingsState.bypasserAdvancedSettings.hardwareAcceleration !== undefined
        ? settingsState.bypasserAdvancedSettings.hardwareAcceleration
        : true,
    reduceAnimations: settingsUi.reduceAnimations
      ? settingsUi.reduceAnimations.checked
      : settingsState.bypasserAdvancedSettings.reduceAnimations !== undefined
        ? settingsState.bypasserAdvancedSettings.reduceAnimations
        : false,
    themeColor: settingsUi.themeColorPicker
      ? settingsUi.themeColorPicker.value
      : DEFAULT_THEME_COLOR,
    telegramEnabled: !!settingsUi.telegramEnabled && settingsUi.telegramEnabled.checked,
    telegramBotToken: settingsUi.telegramBotToken ? settingsUi.telegramBotToken.value.trim() : "",
    telegramChatId: settingsUi.telegramChatId ? settingsUi.telegramChatId.value.trim() : "",
    autoClickButtons: settingsUi.autoClickButtons ? settingsUi.autoClickButtons.checked : true,
    autoClickDelay:
      (settingsUi.autoClickDelay && parseInt(settingsUi.autoClickDelay.value)) || 2000,
    relayServerUrl: settingsUi.relayServerUrl ? settingsUi.relayServerUrl.value.trim() : "",
    lastUpdated: Date.now()
  };
  settingsState.bypasserSettings = bypasserSettings;
  settingsState.bypasserAdvancedSettings = bypasserAdvancedSettings;
  if (settingsUi.themeColorPicker) {
    applyThemeColor(bypasserAdvancedSettings.themeColor);
  }
  chrome.storage.local.set(
    {
      bypasserSettings: bypasserSettings,
      bypasserAdvancedSettings: bypasserAdvancedSettings
    },
    () => {
      isSaveInProgress = false;
      if (chrome.runtime.lastError) {
        showNotification("Failed to save settings: " + chrome.runtime.lastError.message, "error");
      } else {
        showNotification("Settings saved successfully!", "success");
        chrome.runtime.sendMessage(
          {
            type: "SETTINGS_UPDATED",
            settings: bypasserSettings,
            advancedSettings: bypasserAdvancedSettings
          },
          () => {
            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")
              ) {
                console.debug("[Settings] Ignored runtime message error:", messageText);
              }
            }
          }
        );
        chrome.tabs.query({}, tabs => {
          tabs.forEach(tab => {
            try {
              const settingsMessage = {
                type: "STRIPE_BYPASSER_ADVANCED_SETTINGS",
                settings: bypasserAdvancedSettings
              };
              chrome.tabs.sendMessage(tab.id, settingsMessage).catch(error => {
                console.debug("[Settings] Ignored message delivery error:", error);
              });
            } catch (error) {
              console.debug("[Settings] Ignored non-fatal error:", error);
            }
          });
        });
      }
    }
  );
}
function saveSettingsImmediately() {
  scheduleSettingsSave(true);
}
function showNotification(message, variant = "success") {
  let notification = settingsUi.notification;
  notification ||= document.getElementById("notification");
  notification ||= document.querySelector(".notification");
  if (!notification) {
    console.warn("[Settings] Notification element not found");
    notification = document.createElement("div");
    notification.id = "notification";
    notification.className = "notification";
    document.body.appendChild(notification);
    settingsUi.notification = notification;
  }
  const notificationIcon = variant === "success" ? "✓" : variant === "error" ? "✕" : "ℹ";
  notification.innerHTML = `<span class="notification-icon">${notificationIcon}</span><span class="notification-text">${message}</span>`;
  notification.className = "notification notification-" + variant;
  notification.style.display = "flex";
  notification.style.position = "fixed";
  notification.style.top = "20px";
  notification.style.right = "24px";
  notification.style.zIndex = "99999";
  notification.classList.remove("show");
  notification.style.opacity = "0";
  notification.style.transform = "translateY(-10px)";
  notification.offsetWidth;
  requestAnimationFrame(() => {
    notification.classList.add("show");
    notification.style.opacity = "1";
    notification.style.transform = "translateY(0)";
  });
  setTimeout(() => {
    notification.classList.remove("show");
    notification.style.opacity = "0";
    notification.style.transform = "translateY(-10px)";
    setTimeout(() => {
      notification.style.display = "none";
    }, 300);
  }, 3000);
}
function updateCustomCvcVisibility() {
  const customCvcInput = document.getElementById("customCvcInput");
  const cvcModeSelect = document.getElementById("cvcModeSelect");
  if (customCvcInput && cvcModeSelect) {
    customCvcInput.style.display = cvcModeSelect.value === "custom" ? "block" : "none";
  }
}
function updateCaptchaApiKeyVisibility() {
  const apiKeySetting = document.getElementById("apiKeySetting");
  if (apiKeySetting && settingsUi.captchaService) {
    if (settingsUi.captchaService.value === "autoclick") {
      apiKeySetting.style.display = "none";
    } else {
      apiKeySetting.style.display = "flex";
    }
  }
}
function bindUiEventHandlers() {
  if (!settingsUi.saveSettingsBtn) {
    console.warn("[Settings] Save button not found, retrying...");
    setTimeout(bindUiEventHandlers, 100);
    return;
  }
  if (settingsUi.saveSettingsBtn) {
    settingsUi.saveSettingsBtn.addEventListener("click", saveSettingsImmediately);
  }
  if (settingsUi.saveAutofillSettingsBtn) {
    settingsUi.saveAutofillSettingsBtn.addEventListener("click", () => {
      saveSettingsImmediately();
      showNotification("Autofill settings saved!", "success");
    });
  }
  if (settingsUi.resetAutofillSettingsBtn) {
    settingsUi.resetAutofillSettingsBtn.addEventListener("click", () => {
      if (settingsUi.autofillDelay) {
        settingsUi.autofillDelay.value = 7;
      }
      if (settingsUi.customCardNumber) {
        settingsUi.customCardNumber.value = "0000000000000000";
      }
      if (settingsUi.customCardExpiry) {
        settingsUi.customCardExpiry.value = "08/29";
      }
      if (settingsUi.customCardCvc) {
        settingsUi.customCardCvc.value = "000";
      }
      if (settingsUi.customName) {
        settingsUi.customName.value = "";
      }
      if (settingsUi.customAddress1) {
        settingsUi.customAddress1.value = "";
      }
      if (settingsUi.customAddress2) {
        settingsUi.customAddress2.value = "";
      }
      if (settingsUi.customLocality) {
        settingsUi.customLocality.value = "";
      }
      if (settingsUi.useRandomNames) {
        settingsUi.useRandomNames.checked = false;
      }
      if (settingsUi.useRandomAddresses) {
        settingsUi.useRandomAddresses.checked = false;
      }
      if (settingsUi.customEmailDomainEnabled) {
        settingsUi.customEmailDomainEnabled.checked = false;
      }
      if (settingsUi.customEmailDomain) {
        settingsUi.customEmailDomain.value = "";
      }
      if (settingsUi.telegramEnabled) {
        settingsUi.telegramEnabled.checked = false;
      }
      if (settingsUi.telegramBotToken) {
        settingsUi.telegramBotToken.value = "";
      }
      if (settingsUi.telegramChatId) {
        settingsUi.telegramChatId.value = "";
      }
      saveSettingsImmediately();
      showNotification("Autofill settings reset to default!", "success");
    });
  }
  if (settingsUi.cvcModeSelect) {
    settingsUi.cvcModeSelect.addEventListener(
      "change",
      () => {
        updateCustomCvcVisibility();
        if (settingsState.bypasserSettings) {
          settingsState.bypasserSettings.cvcMode = settingsUi.cvcModeSelect.value;
          settingsState.bypasserSettings.autoCvc = settingsUi.cvcModeSelect.value === "generate";
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.customCvcInput) {
    settingsUi.customCvcInput.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserSettings) {
          settingsState.bypasserSettings.customCvc = settingsUi.customCvcInput.value.trim();
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.autoScreenshotToggle) {
    settingsUi.autoScreenshotToggle.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserSettings) {
          settingsState.bypasserSettings.autoScreenshot = settingsUi.autoScreenshotToggle.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.threeDSBypassToggle) {
    settingsUi.threeDSBypassToggle.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserSettings) {
          settingsState.bypasserSettings.threeDSBypass = settingsUi.threeDSBypassToggle.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.analyticsProtectionToggle) {
    settingsUi.analyticsProtectionToggle.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserSettings) {
          settingsState.bypasserSettings.analyticsProtection =
            settingsUi.analyticsProtectionToggle.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.hardwareAcceleration) {
    settingsUi.hardwareAcceleration.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.hardwareAcceleration =
            settingsUi.hardwareAcceleration.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.reduceAnimations) {
    settingsUi.reduceAnimations.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.reduceAnimations =
            settingsUi.reduceAnimations.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.autoCaptchaToggle) {
    settingsUi.autoCaptchaToggle.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.autoCaptcha = settingsUi.autoCaptchaToggle.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.autofillToggle) {
    settingsUi.autofillToggle.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.autofill = settingsUi.autofillToggle.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.autofillCardDataToggle) {
    settingsUi.autofillCardDataToggle.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.autofillCardData =
            settingsUi.autofillCardDataToggle.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.autofillBillingDataToggle) {
    settingsUi.autofillBillingDataToggle.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.autofillBillingData =
            settingsUi.autofillBillingDataToggle.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.useRandomNames) {
    settingsUi.useRandomNames.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.useRandomNames = settingsUi.useRandomNames.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.useRandomAddresses) {
    settingsUi.useRandomAddresses.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.useRandomAddresses =
            settingsUi.useRandomAddresses.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.telegramEnabled) {
    settingsUi.telegramEnabled.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.telegramEnabled =
            settingsUi.telegramEnabled.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.telegramBotToken) {
    settingsUi.telegramBotToken.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.telegramBotToken =
            settingsUi.telegramBotToken.value.trim();
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  if (settingsUi.telegramChatId) {
    settingsUi.telegramChatId.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.telegramChatId =
            settingsUi.telegramChatId.value.trim();
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
  const telegramVisibilityToggle = document.querySelector(".telegram-toggle-visibility");
  if (telegramVisibilityToggle && settingsUi.telegramBotToken) {
    telegramVisibilityToggle.addEventListener("click", () => {
      const botTokenInput = settingsUi.telegramBotToken;
      const eyeIcon = telegramVisibilityToggle.querySelector(".eye-icon");
      const eyeOffIcon = telegramVisibilityToggle.querySelector(".eye-off-icon");
      if (botTokenInput.type === "password") {
        botTokenInput.type = "text";
        if (eyeIcon) {
          eyeIcon.style.display = "none";
        }
        if (eyeOffIcon) {
          eyeOffIcon.style.display = "block";
        }
      } else {
        botTokenInput.type = "password";
        if (eyeIcon) {
          eyeIcon.style.display = "block";
        }
        if (eyeOffIcon) {
          eyeOffIcon.style.display = "none";
        }
      }
    });
  }
  if (settingsUi.autoClickButtons) {
    settingsUi.autoClickButtons.addEventListener(
      "input",
      () => {
        if (settingsState.bypasserAdvancedSettings) {
          settingsState.bypasserAdvancedSettings.autoClickButtons =
            settingsUi.autoClickButtons.checked;
        }
        scheduleSettingsSave();
      },
      {
        once: false
      }
    );
  }
}
function bindDonationCopyButtons() {
  document.querySelectorAll(".donate-copy-btn").forEach(originalCopyButton => {
    const copyButton = originalCopyButton.cloneNode(true);
    originalCopyButton.parentNode.replaceChild(copyButton, originalCopyButton);
    copyButton.addEventListener("click", async event => {
      event.preventDefault();
      const copyTarget = copyButton.dataset.copyTarget;
      const sourceInput = document.getElementById(copyTarget);
      if (sourceInput) {
        try {
          const textToCopy = sourceInput.value;
          if (navigator.clipboard && navigator.clipboard.writeText) {
            await navigator.clipboard.writeText(textToCopy);
          } else {
            sourceInput.select();
            sourceInput.setSelectionRange(0, 99999);
            document.execCommand("copy");
          }
          copyButton.classList.add("copied");
          setTimeout(() => {
            copyButton.classList.remove("copied");
          }, 2000);
          showNotification("Copied to clipboard!", "success");
        } catch (error) {
          console.error("Failed to copy:", error);
          showNotification("Failed to copy to clipboard", "error");
        }
      }
    });
  });
}
function initializeAutofillSectionToggle() {
  const autofillSectionToggle = document.getElementById("autofillSectionToggle");
  const autofillSectionContent = document.getElementById("autofillSectionContent");
  const sectionChevron = autofillSectionToggle?.querySelector(".section-chevron");
  if (autofillSectionToggle && autofillSectionContent) {
    chrome.storage.local.get(["autofillSectionCollapsed"], storageData => {
      if (storageData.autofillSectionCollapsed !== false) {
        autofillSectionContent.classList.add("collapsed");
        if (sectionChevron) {
          sectionChevron.classList.add("rotated");
        }
      }
      if (storageData.autofillSectionCollapsed === undefined) {
        chrome.storage.local.set({
          autofillSectionCollapsed: true
        });
      }
    });
    autofillSectionToggle.addEventListener("click", event => {
      event.preventDefault();
      event.stopPropagation();
      const autofillSectionCollapsed = autofillSectionContent.classList.toggle("collapsed");
      if (sectionChevron) {
        if (autofillSectionCollapsed) {
          sectionChevron.classList.add("rotated");
        } else {
          sectionChevron.classList.remove("rotated");
        }
      }
      chrome.storage.local.set({
        autofillSectionCollapsed: autofillSectionCollapsed
      });
    });
  } else {
    setTimeout(initializeAutofillSectionToggle, 100);
  }
}
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", bindUiEventHandlers);
} else {
  bindUiEventHandlers();
}
(function () {
  function loadDeveloperSupportInfo() {
    try {
      const binanceIdInput = document.getElementById("binanceId");
      const usdtTrc20Input = document.getElementById("usdtTrc20");
      const ltcAddressInput = document.getElementById("ltcAddress");
      if (!binanceIdInput || !usdtTrc20Input || !ltcAddressInput) {
        setTimeout(loadDeveloperSupportInfo, 100);
        return;
      }
      chrome.runtime.sendMessage(
        {
          type: "GET_DEVELOPER_SUPPORT"
        },
        function (result) {
          try {
            if (chrome.runtime.lastError) {
              populateFallbackDeveloperSupport(binanceIdInput, usdtTrc20Input, ltcAddressInput);
              return;
            }
            if (result && result.success && result.data) {
              const developerSupport = result.data;
              if (developerSupport.binanceId) {
                binanceIdInput.value = developerSupport.binanceId;
              }
              if (developerSupport.usdtTrc20) {
                usdtTrc20Input.value = developerSupport.usdtTrc20;
              }
              if (developerSupport.ltcAddress) {
                ltcAddressInput.value = developerSupport.ltcAddress;
              }
            } else {
              populateFallbackDeveloperSupport(binanceIdInput, usdtTrc20Input, ltcAddressInput);
            }
          } catch (error) {
            console.error("[Settings] Error processing support info:", error);
            populateFallbackDeveloperSupport(binanceIdInput, usdtTrc20Input, ltcAddressInput);
          }
        }
      );
    } catch (error) {
      console.error("[Settings] Error loading developer support info:", error);
    }
  }
  function populateFallbackDeveloperSupport(binanceIdInput, usdtTrc20Input, ltcAddressInput) {
    if (
      window.StripeBypasserCaptchaSolver &&
      typeof window.StripeBypasserCaptchaSolver.getDeveloperSupport === "function"
    ) {
      try {
        const developerSupport = window.StripeBypasserCaptchaSolver.getDeveloperSupport();
        if (developerSupport) {
          if (developerSupport.binanceId) {
            binanceIdInput.value = developerSupport.binanceId;
          }
          if (developerSupport.usdtTrc20) {
            usdtTrc20Input.value = developerSupport.usdtTrc20;
          }
          if (developerSupport.ltcAddress) {
            ltcAddressInput.value = developerSupport.ltcAddress;
          }
          return;
        }
      } catch (error) {
        console.error("[Settings] Error getting support from window:", error);
      }
    }
    binanceIdInput.value = "211631455";
    usdtTrc20Input.value = "TThsNyTJADb9gg7yHC1USwBCw5b1DXeaYJ";
    ltcAddressInput.value = "LhDwqxZSJYV5A8Pm7cMdLQDdfpaYddY2dw";
  }
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", loadDeveloperSupportInfo);
  } else {
    setTimeout(loadDeveloperSupportInfo, 50);
  }
})();
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", bindDonationCopyButtons);
} else {
  bindDonationCopyButtons();
}
if (settingsUi.autoClickDelay) {
  settingsUi.autoClickDelay.addEventListener(
    "input",
    () => {
      if (settingsState.bypasserAdvancedSettings) {
        settingsState.bypasserAdvancedSettings.autoClickDelay =
          parseInt(settingsUi.autoClickDelay.value) || 2000;
      }
      scheduleSettingsSave();
    },
    {
      once: false
    }
  );
}
if (settingsUi.testTelegramConnection) {
  settingsUi.testTelegramConnection.addEventListener("click", async () => {
    const botToken = settingsUi.telegramBotToken ? settingsUi.telegramBotToken.value.trim() : "";
    const chatId = settingsUi.telegramChatId ? settingsUi.telegramChatId.value.trim() : "";
    if (!botToken || !chatId) {
      showNotification("Please enter both Bot Token and Chat ID", "error");
      return;
    }
    const testButton = settingsUi.testTelegramConnection;
    testButton.disabled = true;
    testButton.classList.add("loading");
    const originalButtonHtml = testButton.innerHTML;
    testButton.innerHTML = "<span></span>";
    try {
      const requestUrl = `https://api.telegram.org/bot${botToken}/sendMessage`;
      const response = await fetch(requestUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          chat_id: parseInt(chatId) || chatId,
          text: "🧪 <b>Test Connection</b>\n\n✅ Telegram notification is working correctly!\n\n📢 Join: t.me/binbhai",
          parse_mode: "HTML"
        })
      });
      const responseBody = await response.json();
      if (response.ok && responseBody.ok) {
        showNotification(
          "✅ Connection successful! Check your Telegram for the test message.",
          "success"
        );
      } else {
        showNotification(
          "❌ Connection failed: " + (responseBody.description || "Unknown error"),
          "error"
        );
      }
    } catch (error) {
      showNotification("❌ Connection failed: " + error.message, "error");
    } finally {
      testButton.disabled = false;
      testButton.classList.remove("loading");
      testButton.innerHTML = originalButtonHtml;
    }
  });
}
if (settingsUi.captchaService) {
  settingsUi.captchaService.addEventListener(
    "change",
    () => {
      updateCaptchaApiKeyVisibility();
      if (settingsState.bypasserAdvancedSettings) {
        settingsState.bypasserAdvancedSettings.captchaService = settingsUi.captchaService.value;
      }
      scheduleSettingsSave();
    },
    {
      once: false
    }
  );
}
if (settingsUi.captchaApiKey) {
  settingsUi.captchaApiKey.addEventListener(
    "input",
    () => {
      if (settingsState.bypasserAdvancedSettings) {
        settingsState.bypasserAdvancedSettings.captchaApiKey =
          settingsUi.captchaApiKey.value.trim();
      }
      scheduleSettingsSave();
    },
    {
      once: false
    }
  );
}
if (settingsUi.themeColorPicker) {
  settingsUi.themeColorPicker.addEventListener("input", event => {
    const themeColor = event.target.value;
    applyThemeColor(themeColor);
    if (settingsState.bypasserAdvancedSettings) {
      settingsState.bypasserAdvancedSettings.themeColor = themeColor;
    }
    scheduleSettingsSave();
    setActiveThemePreset(themeColor);
  });
}
if (settingsUi.resetThemeColor) {
  settingsUi.resetThemeColor.addEventListener("click", () => {
    if (settingsUi.themeColorPicker) {
      settingsUi.themeColorPicker.value = DEFAULT_THEME_COLOR;
      applyThemeColor(DEFAULT_THEME_COLOR);
      saveSettingsImmediately();
      setActiveThemePreset(DEFAULT_THEME_COLOR);
    }
  });
}
document.querySelectorAll(".theme-preset-btn").forEach(presetButton => {
  presetButton.addEventListener("click", () => {
    const color = presetButton.dataset.color;
    if (settingsUi.themeColorPicker) {
      settingsUi.themeColorPicker.value = color;
      applyThemeColor(color);
      saveSettingsImmediately();
      setActiveThemePreset(color);
    }
  });
});
setTimeout(() => {
  if (settingsUi.captchaService && settingsUi.captchaService.value === "autoclick") {
    const apiKeySetting = document.getElementById("apiKeySetting");
    if (apiKeySetting) {
      apiKeySetting.style.display = "none";
    }
  }
}, 100);
if (settingsUi.customCardExpiry) {
  settingsUi.customCardExpiry.addEventListener("input", event => {
    let normalizedText = event.target.value.replace(/\D/g, "");
    if (normalizedText.length >= 2) {
      normalizedText = normalizedText.substring(0, 2) + "/" + normalizedText.substring(2, 4);
    }
    event.target.value = normalizedText;
  });
  settingsUi.customCardExpiry.addEventListener("keydown", event => {
    if (event.key === "Backspace" && event.target.value.length === 3) {
      event.target.value = event.target.value.substring(0, 2);
    }
  });
}
if (settingsUi.customCardNumber) {
  settingsUi.customCardNumber.addEventListener("input", event => {
    var matchResult;
    let normalizedText = event.target.value.replace(/\D/g, "").replace(/\|/g, "|");
    if (!normalizedText.includes("|") && normalizedText.length > 0) {
      normalizedText = (matchResult = normalizedText.match(/.{1,4}/g))?.join(" ") || normalizedText;
      event.target.value = normalizedText;
    }
  });
}
setTimeout(() => {
  initializeAutofillSectionToggle();
}, 50);
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", () => {
    setTimeout(loadSettingsIntoUi, 50);
  });
} else {
  setTimeout(loadSettingsIntoUi, 50);
}
chrome.storage.onChanged.addListener((changes, areaName) => {
  if (areaName === "local" && (changes.bypasserSettings || changes.bypasserAdvancedSettings)) {
    clearTimeout(window._settingsUpdateTimeout);
    window._settingsUpdateTimeout = setTimeout(() => {
      if (!isSaveInProgress) {
        loadSettingsIntoUi();
        const notificationElement = settingsUi.notification;
        if (notificationElement && !notificationElement.classList.contains("show")) {
          showNotification("Settings updated from another tab", "success");
        }
      }
    }, 300);
  }
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === "RELOAD_SETTINGS" || message.type === "SETTINGS_UPDATED") {
    loadSettingsIntoUi();
    sendResponse({
      success: true
    });
    return true;
  }
});
const closeButton = document.getElementById("closeButton");
if (closeButton) {
  closeButton.addEventListener("click", event => {
    event.preventDefault();
    event.stopPropagation();
    if (window.parent !== window) {
      window.parent.postMessage(
        {
          type: "CLOSE_SETTINGS"
        },
        "*"
      );
    } else if (window.history.length > 1) {
      window.history.back();
    } else {
      window.location.href = "options.html";
    }
    return false;
  });
}
document.addEventListener("keydown", event => {
  if (event.key === "Escape") {
    if (window.history.length > 1) {
      window.history.back();
    } else if (window.parent !== window) {
      window.parent.postMessage(
        {
          type: "CLOSE_SETTINGS"
        },
        "*"
      );
    } else {
      window.location.href = "options.html";
    }
  }
});
(async () => {
  try {
    await loadPerformanceSettings();
    applyPerformanceSettings();
    Object.values(settingsUi)
      .filter(Boolean)
      .forEach(uiElement => {
        if (uiElement.nodeType === Node.ELEMENT_NODE) {
          applyPerformanceSettingsToElement(uiElement);
        }
      });
    const mutationObserverRef = new MutationObserver(mutations => {
      mutations.forEach(mutation => {
        mutation.addedNodes.forEach(addedNode => {
          if (addedNode.nodeType === Node.ELEMENT_NODE) {
            applyPerformanceSettingsToElement(addedNode);
            addedNode.querySelectorAll("*").forEach(descendant => {
              applyPerformanceSettingsToElement(descendant);
            });
          }
        });
      });
    });
    if (document.body) {
      mutationObserverRef.observe(document.body, {
        childList: true,
        subtree: true
      });
    }
  } catch (error) {
    console.warn("[Settings] Failed to load performance settings:", error);
  }
})();
const backgroundIframe = document.getElementById("backgroundIframe");
if (backgroundIframe) {
  backgroundIframe.addEventListener("load", () => {
    window.__optionsPageLoaded = true;
  });
}
