// Popup JS — Texter Captcha Solver with Auth
(function () {
  'use strict';

  const API_BASE = 'https://textercompter.store/auth_api.php';

  // ── DOM refs ──
  const tabs = document.querySelectorAll('.tab');
  const panels = document.querySelectorAll('.tab-panel');
  const tabIndicator = document.getElementById('tabIndicator');

  // Dynamic engine list container
  const enginesList = document.getElementById('engines-list');

  const appVersion = document.getElementById('appVersion');
  const updateBanner = document.getElementById('update-banner');
  const latestVersionSpan = document.getElementById('latest-version');

  // Automation toggles
  const autoSolve = document.getElementById('auto-solve');
  const autoRefresh = document.getElementById('auto-refresh');

  // Auth elements
  const authLoggedOut = document.getElementById('auth-logged-out');
  const authLoggedIn = document.getElementById('auth-logged-in');
  const authError = document.getElementById('auth-error');
  const authTabs = document.querySelectorAll('.auth-tab');
  const authForms = document.querySelectorAll('.auth-form');

  // Login form
  const loginEmail = document.getElementById('login-email');
  const loginPassword = document.getElementById('login-password');
  const btnLogin = document.getElementById('btn-login');

  // Register form
  const registerName = document.getElementById('register-name');
  const registerEmail = document.getElementById('register-email');
  const registerPassword = document.getElementById('register-password');
  const btnRegister = document.getElementById('btn-register');

  // User card
  const userName = document.getElementById('user-name');
  const userEmail = document.getElementById('user-email');
  const userAvatar = document.getElementById('user-avatar');
  const userCredits = document.getElementById('user-credits');
  const userPlan = document.getElementById('user-plan');
  const userSolves = document.getElementById('user-solves');
  const btnRefresh = document.getElementById('btn-refresh-account');
  const btnLogout = document.getElementById('btn-logout');
  const btnBuyCredits = document.getElementById('btn-buy-credits');

  // Pricing & Manual Payment
  const pricingOverlay = document.getElementById('pricing-overlay');
  const btnClosePricing = document.getElementById('btn-close-pricing');
  const plansGrid = document.getElementById('plans-grid');
  const paymentBox = document.getElementById('payment-box');
  const paymentTitle = document.getElementById('payment-title');
  const paymentQr = document.getElementById('payment-qr');
  const selectedPlanKey = document.getElementById('selected-plan-key');
  const confirmPaymentBtn = document.getElementById('confirm-payment-btn');
  const paymentTransactionId = document.getElementById('payment-transaction-id');
  const authPendingBanner = document.getElementById('auth-pending-banner');
  const pendingPlanName = document.getElementById('pending-plan-name');

  const currentSiteUrl = document.getElementById('currentSiteUrl');
  const btnExcludeSite = document.getElementById('btnExcludeSite');
  const btnRequestCaptcha = document.getElementById('btnRequestCaptcha');
  const btnRequestNewSite = document.getElementById('btnRequestNewSite');
  const excludedList = document.getElementById('excludedList');
  const emptyExcluded = document.getElementById('emptyExcluded');

  // Footer
  const btnOptions = document.getElementById('btnOptions');

  let currentHostname = '';

  // ── Default settings ──
  const DEFAULT_SETTINGS = {
    engines: {},
    autoSolve: true,
    autoRefresh: false,
    excludedSites: []
  };

  // ── Dynamic engine config (loaded from server) ──
  let cachedEngineConfig = null; // Array of engine objects from server

  // ══════════════════════════════════════════
  //  AUTH SYSTEM
  // ══════════════════════════════════════════

  // Auth tab switching
  authTabs.forEach(tab => {
    tab.addEventListener('click', () => {
      const target = tab.dataset.authTab;
      authTabs.forEach(t => t.classList.toggle('active', t.dataset.authTab === target));
      authForms.forEach(f => f.classList.toggle('active', f.id === `auth-form-${target}`));
      hideAuthError();
    });
  });

  function showAuthError(msg) {
    authError.textContent = msg;
    authError.style.display = 'block';
  }

  function hideAuthError() {
    authError.style.display = 'none';
  }

  function setAuthLoading(btn, loading) {
    const text = btn.querySelector('.auth-btn-text');
    const loader = btn.querySelector('.auth-btn-loader');
    btn.disabled = loading;
    text.style.display = loading ? 'none' : '';
    loader.style.display = loading ? 'inline' : 'none';
  }

  // Check stored auth state
  function checkAuthState() {
    chrome.storage.sync.get(['apiKey', 'userName', 'userEmail', 'userCredits', 'userPlan', 'userSolves'], (result) => {
      if (result.apiKey && result.userName) {
        showLoggedIn(result);
        fetchLatestAccountData(false);
      } else {
        showLoggedOut();
      }
    });
  }

  function showLoggedIn(data) {
    authLoggedOut.style.display = 'none';
    authLoggedIn.style.display = 'block';

    userName.textContent = data.userName || '—';
    userEmail.textContent = data.userEmail || '—';
    userAvatar.textContent = (data.userName || 'T').charAt(0).toUpperCase();
    userCredits.textContent = (data.userCredits || 0).toLocaleString();
    userPlan.textContent = (data.userPlan || 'free').charAt(0).toUpperCase() + (data.userPlan || 'free').slice(1);
    userSolves.textContent = (data.userSolves || 0).toLocaleString();

    // Handle Pending Transactions UI
    if (data.pendingPlan) {
      authPendingBanner.style.display = 'block';
      pendingPlanName.textContent = data.pendingPlan;
      btnBuyCredits.style.opacity = '0.5';
      btnBuyCredits.style.pointerEvents = 'none';
      btnBuyCredits.textContent = 'Payment Pending...';
    } else {
      authPendingBanner.style.display = 'none';
      btnBuyCredits.style.opacity = '1';
      btnBuyCredits.style.pointerEvents = '';
      btnBuyCredits.innerHTML = '💳 Buy Credits';
    }

    // Unlock settings
    unlockSettings();
  }

  function showLoggedOut() {
    authLoggedOut.style.display = 'block';
    authLoggedIn.style.display = 'none';

    // Lock settings
    lockSettings();
  }

  function lockSettings() {
    document.querySelectorAll('#panel-engines .section, #panel-sites .section').forEach(s => {
      s.classList.add('settings-locked');
    });
  }

  function unlockSettings() {
    document.querySelectorAll('#panel-engines .section, #panel-sites .section').forEach(s => {
      s.classList.remove('settings-locked');
    });
  }

  // ── Login ──
  btnLogin.addEventListener('click', async () => {
    hideAuthError();
    const email = loginEmail.value.trim();
    const password = loginPassword.value;

    if (!email || !password) {
      showAuthError('Email and password are required.');
      return;
    }

    setAuthLoading(btnLogin, true);

    try {
      const res = await fetch(`${API_BASE}?action=login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password })
      });
      const data = await res.json();

      if (data.success) {
        const session = {
          apiKey: data.api_key,
          userName: data.name,
          userEmail: data.email,
          userCredits: data.credits,
          userPlan: data.plan,
          userSolves: data.total_solves,
          pendingPlan: data.pending_plan || null
        };
        chrome.storage.sync.set(session, () => {
          showLoggedIn(session);
          loginEmail.value = '';
          loginPassword.value = '';
        });
      } else {
        showAuthError(data.error || 'Login failed.');
      }
    } catch (err) {
      showAuthError('Connection error. Please try again.');
    }

    setAuthLoading(btnLogin, false);
  });

  // ── Register ──
  btnRegister.addEventListener('click', async () => {
    hideAuthError();
    const name = registerName.value.trim();
    const email = registerEmail.value.trim();
    const password = registerPassword.value;

    if (!name || !email || !password) {
      showAuthError('All fields are required.');
      return;
    }

    if (password.length < 6) {
      showAuthError('Password must be at least 6 characters.');
      return;
    }

    setAuthLoading(btnRegister, true);

    try {
      const res = await fetch(`${API_BASE}?action=register`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, email, password })
      });
      const data = await res.json();

      if (data.success) {
        const session = {
          apiKey: data.api_key,
          userName: data.name,
          userEmail: data.email,
          userCredits: data.credits,
          userPlan: data.plan,
          userSolves: data.total_solves,
          pendingPlan: null
        };
        chrome.storage.sync.set(session, () => {
          showLoggedIn(session);
          registerName.value = '';
          registerEmail.value = '';
          registerPassword.value = '';
        });
      } else {
        showAuthError(data.error || 'Registration failed.');
      }
    } catch (err) {
      showAuthError('Connection error. Please try again.');
    }

    setAuthLoading(btnRegister, false);
  });

  // ── Logout ──
  btnLogout.addEventListener('click', () => {
    chrome.storage.sync.remove(['apiKey', 'userName', 'userEmail', 'userCredits', 'userPlan', 'userSolves', 'pendingPlan'], () => {
      showLoggedOut();
      closePricingOverlay();
    });
  });

  // ── Pricing Overlay Logic ──
  let cachedPlans = null;

  function closePricingOverlay() {
    if (pricingOverlay) pricingOverlay.style.display = 'none';
    if (paymentBox) paymentBox.style.display = 'none';
    if (plansGrid) {
      plansGrid.querySelectorAll('.plan-card').forEach(c => c.classList.remove('selected'));
    }
  }

  if (btnClosePricing) {
    btnClosePricing.addEventListener('click', closePricingOverlay);
  }

  async function fetchPlans() {
    if (cachedPlans) return cachedPlans;
    try {
      const res = await fetch(`${API_BASE}?action=get_plans`, { method: 'POST' });
      const data = await res.json();
      if (data.success && data.plans) {
        cachedPlans = data.plans;
        return data.plans;
      }
    } catch (e) { }
    return null;
  }

  function renderPlans(plans) {
    plansGrid.innerHTML = '';
    const keys = Object.keys(plans);
    keys.forEach(key => {
      const p = plans[key];
      const isFeatured = key === 'pro';

      const card = document.createElement('div');
      card.className = `plan-card ${isFeatured ? 'featured' : ''}`;
      card.innerHTML = `
        <div class="plan-info">
          <div class="plan-title">${esc(p.name)} Plan</div>
          <div class="plan-credits">${Number(p.credits).toLocaleString()} Solves</div>
        </div>
        <div class="plan-price">${esc(p.label)}</div>
      `;

      card.addEventListener('click', () => {
        plansGrid.querySelectorAll('.plan-card').forEach(c => c.classList.remove('selected'));
        card.classList.add('selected');

        // Show QR
        paymentTitle.textContent = `💳 Pay ₹${p.price} for ${p.name}`;

        const upiId = '7550900985@okbizaxis';
        const payeeName = 'Texter Computer';
        const qrData = `upi://pay?pa=${upiId}&pn=${encodeURIComponent(payeeName)}&am=${p.price}&cu=INR`;
        
        // Use local QRCode library
        QRCode.toDataURL(qrData, { 
          width: 150, 
          margin: 1,
          color: {
            dark: '#000000',
            light: '#ffffff'
          }
        }, (err, url) => {
          if (err) {
            console.error('QR Generation Error:', err);
            return;
          }
          addLogoToQR(url, 'T', (brandedUrl) => {
            paymentQr.src = brandedUrl;
          });
        });

        selectedPlanKey.value = key;
        confirmPaymentBtn.querySelector('.auth-btn-text').textContent = `✅ I've Paid ₹${p.price}`;

        paymentBox.style.display = 'block';
        paymentBox.scrollIntoView({ behavior: 'smooth' });
      });
      plansGrid.appendChild(card);
    });
  }

  if (btnBuyCredits) {
    btnBuyCredits.addEventListener('click', async () => {
      if (btnBuyCredits.style.pointerEvents === 'none') return;

      if (pricingOverlay.style.display === 'block') {
        closePricingOverlay();
        return;
      }

      pricingOverlay.style.display = 'block';
      if (!cachedPlans) {
        const plans = await fetchPlans();
        if (plans) {
          renderPlans(plans);
        } else {
          plansGrid.innerHTML = '<div style="text-align:center;color:var(--danger);font-size:11px;">Failed to load plans.</div>';
        }
      }
    });
  }

  // ── Submit Manual Payment ──
    confirmPaymentBtn.addEventListener('click', async () => {
      const planKey = selectedPlanKey.value;
      const transactionId = paymentTransactionId.value.trim();
      
      if (!planKey) return;
      if (!transactionId) {
        alert('Please enter the Transaction ID / UTR No. before confirming.');
        paymentTransactionId.focus();
        return;
      }

      chrome.storage.sync.get(['apiKey'], async (result) => {
        if (!result.apiKey) return;

        setAuthLoading(confirmPaymentBtn, true);

        try {
          const res = await fetch(`${API_BASE}?action=submit_payment`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
              api_key: result.apiKey, 
              plan_key: planKey,
              transaction_id: transactionId
            })
          });
          const data = await res.json();

          if (data.success) {
            closePricingOverlay();
            paymentTransactionId.value = ''; // clear for next time
            // Refresh account data to show pending banner
            fetchLatestAccountData(false);
          } else {
            alert(data.error || 'Failed to submit payment.');
          }
        } catch (e) {
          alert('Connection error.');
        }

        setAuthLoading(confirmPaymentBtn, false);
      });
    });

  async function fetchLatestAccountData(isManual = false) {
    if (isManual && btnRefresh) {
      btnRefresh.textContent = '⏳…';
      btnRefresh.disabled = true;
    }

    chrome.storage.sync.get(['apiKey'], async (result) => {
      if (!result.apiKey) {
        showLoggedOut();
        return;
      }

      try {
        const res = await fetch(`${API_BASE}?action=account`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ api_key: result.apiKey })
        });
        const data = await res.json();

        if (data.success) {
          const updated = {
            userName: data.name,
            userEmail: data.email,
            userCredits: data.credits,
            userPlan: data.plan,
            userSolves: data.total_solves,
            pendingPlan: data.pending_plan || null
          };
          chrome.storage.sync.set(updated, () => {
            showLoggedIn({ ...updated, apiKey: result.apiKey });
          });
        } else {
          // API key invalid — log out
          chrome.storage.sync.remove(['apiKey', 'userName', 'userEmail', 'userCredits', 'userPlan', 'userSolves', 'pendingPlan'], () => {
            showLoggedOut();
          });
        }
      } catch (err) {
        // Silent fail — keep existing data
      }

      if (isManual && btnRefresh) {
        btnRefresh.textContent = '🔄 Refresh';
        btnRefresh.disabled = false;
      }
    });
  }

  // ── Refresh Account ──
  btnRefresh.addEventListener('click', () => {
    fetchLatestAccountData(true);
  });

  // Enter key support for auth forms
  loginPassword.addEventListener('keydown', (e) => { if (e.key === 'Enter') btnLogin.click(); });
  loginEmail.addEventListener('keydown', (e) => { if (e.key === 'Enter') loginPassword.focus(); });
  registerPassword.addEventListener('keydown', (e) => { if (e.key === 'Enter') btnRegister.click(); });

  // ══════════════════════════════════════════
  //  TAB SWITCHING
  // ══════════════════════════════════════════

  function switchTab(tabName) {
    tabs.forEach(t => {
      t.classList.toggle('active', t.dataset.tab === tabName);
      t.setAttribute('aria-selected', t.dataset.tab === tabName ? 'true' : 'false');
    });

    panels.forEach(p => {
      const isActive = p.id === `panel-${tabName}`;
      p.classList.toggle('active', isActive);
    });

    const activeTab = document.querySelector(`.tab[data-tab="${tabName}"]`);
    if (activeTab && tabIndicator) {
      const idx = Array.from(tabs).indexOf(activeTab);
      tabIndicator.style.transform = `translateX(${idx * 100}%)`;
    }
  }

  tabs.forEach(tab => {
    tab.addEventListener('click', () => switchTab(tab.dataset.tab));
  });

  // ══════════════════════════════════════════
  //  DYNAMIC ENGINE RENDERING
  // ══════════════════════════════════════════

  /** Fetch engine config from background (which caches from server) */
  function loadEngineConfig(callback) {
    chrome.runtime.sendMessage({ action: 'GET_SOLVER_CONFIG' }, (response) => {
      if (response && response.config && response.config.engines) {
        cachedEngineConfig = response.config.engines;
        callback(cachedEngineConfig);
      } else {
        // No config yet — show placeholder
        if (enginesList) {
          enginesList.innerHTML = '<div style="text-align:center; color:var(--text-muted); font-size:11px; padding:20px;">No engine config available. Check your connection.</div>';
        }
        callback([]);
      }
    });
  }

  /** Render engine toggle cards dynamically */
  function renderEngineCards(engines, settings) {
    if (!enginesList) return;
    enginesList.innerHTML = '';

    const engineSettings = (settings && settings.engines) || {};

    engines.forEach(engine => {
      const key = engine.key;
      const isChecked = engineSettings[key] !== false; // default to true
      const hostnames = (engine.hostnames || []).join(', ');
      const truncatedHost = hostnames.length > 30 ? hostnames.substring(0, 28) + '…' : hostnames;

      const card = document.createElement('div');
      card.className = 'toggle-card' + (isChecked ? '' : ' disabled');
      card.dataset.engine = key;
      card.innerHTML = `
        <div class="toggle-info">
          <span class="toggle-icon" style="background:${esc(engine.iconColor || '#7c6aff')};color:#fff">${esc(engine.icon || key.charAt(0).toUpperCase())}</span>
          <div>
            <div class="toggle-title">${esc(engine.name)}</div>
            <div class="toggle-desc">${esc(truncatedHost)}</div>
          </div>
        </div>
        <label class="switch">
          <input type="checkbox" id="engine-${esc(key)}" ${isChecked ? 'checked' : ''}>
          <span class="slider"></span>
        </label>
      `;

      const checkbox = card.querySelector('input[type="checkbox"]');
      checkbox.addEventListener('change', () => {
        card.classList.toggle('disabled', !checkbox.checked);
        saveSettings();
      });

      enginesList.appendChild(card);
    });
  }

  // ══════════════════════════════════════════
  //  SETTINGS
  // ══════════════════════════════════════════

  function loadSettings() {
    chrome.runtime.sendMessage({ action: 'GET_SETTINGS' }, (response) => {
      const s = response && response.settings ? response.settings : DEFAULT_SETTINGS;

      autoSolve.checked = s.autoSolve !== false;
      autoRefresh.checked = s.autoRefresh === true;

      // Render engine cards with current settings
      loadEngineConfig((engines) => {
        renderEngineCards(engines, s);
      });

      renderExcludedSites(s.excludedSites || []);
      updateExcludeButton(s.excludedSites || []);

      // Auto-update version
      const manifest = chrome.runtime.getManifest();
      if (appVersion) appVersion.textContent = 'v' + manifest.version;
    });
  }

  function updateCardStates() {
    document.querySelectorAll('.toggle-card[data-engine]').forEach(card => {
      const engineId = card.dataset.engine;
      const checkbox = document.getElementById(`engine-${engineId}`);
      if (checkbox) card.classList.toggle('disabled', !checkbox.checked);
    });
  }

  function saveSettings() {
    // Build engines object dynamically from all rendered checkboxes
    const engines = {};
    document.querySelectorAll('.toggle-card[data-engine]').forEach(card => {
      const key = card.dataset.engine;
      const checkbox = document.getElementById(`engine-${key}`);
      if (checkbox) {
        engines[key] = checkbox.checked;
      }
    });

    const settings = {
      engines,
      autoSolve: autoSolve.checked,
      autoRefresh: autoRefresh.checked
    };

    chrome.runtime.sendMessage({ action: 'SAVE_SETTINGS', settings });
    updateCardStates();
  }

  // Automation toggles change listeners
  if (autoSolve) autoSolve.addEventListener('change', saveSettings);
  if (autoRefresh) autoRefresh.addEventListener('change', saveSettings);

  // ══════════════════════════════════════════
  //  SITE MANAGEMENT
  // ══════════════════════════════════════════

  function detectCurrentSite() {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabList) => {
      if (tabList[0] && tabList[0].url) {
        try {
          const url = new URL(tabList[0].url);
          currentHostname = url.hostname;
          currentSiteUrl.textContent = currentHostname || '—';
        } catch (e) {
          currentSiteUrl.textContent = 'N/A';
        }
      } else {
        currentSiteUrl.textContent = 'N/A';
      }
    });
  }

  function renderExcludedSites(sites) {
    excludedList.querySelectorAll('.excluded-item').forEach(el => el.remove());

    if (!sites || sites.length === 0) {
      emptyExcluded.style.display = 'flex';
      return;
    }

    emptyExcluded.style.display = 'none';

    sites.forEach(site => {
      const item = document.createElement('div');
      item.className = 'excluded-item';
      item.innerHTML = `
          < span class="excluded-item-url" > ${esc(site)}</span >
            <button class="excluded-item-remove" data-site="${esc(site)}" title="Remove">
              <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>
        `;
      excludedList.appendChild(item);

      item.querySelector('.excluded-item-remove').addEventListener('click', () => {
        removeSiteFromBlacklist(site);
      });
    });
  }

  function updateExcludeButton(sites) {
    const isExcluded = sites.includes(currentHostname);
    if (isExcluded) {
      btnExcludeSite.textContent = '✓ Site Excluded';
      btnExcludeSite.classList.add('active');
    } else {
      btnExcludeSite.innerHTML = `
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
            Exclude from Auto Solve
              `;
      btnExcludeSite.classList.remove('active');
    }
  }

  function addSiteToBlacklist() {
    if (!currentHostname) return;

    chrome.runtime.sendMessage({
      action: 'UPDATE_SITE_BLACKLIST',
      operation: 'add',
      site: currentHostname
    }, (response) => {
      if (response && response.sites) {
        renderExcludedSites(response.sites);
        updateExcludeButton(response.sites);
      }
    });
  }

  function removeSiteFromBlacklist(site) {
    chrome.runtime.sendMessage({
      action: 'UPDATE_SITE_BLACKLIST',
      operation: 'remove',
      site: site
    }, (response) => {
      if (response && response.sites) {
        renderExcludedSites(response.sites);
        updateExcludeButton(response.sites);
      }
    });
  }

  btnExcludeSite.addEventListener('click', () => {
    if (btnExcludeSite.classList.contains('active')) {
      removeSiteFromBlacklist(currentHostname);
    } else {
      addSiteToBlacklist();
    }
  });

  // ── Request Captcha Solve ──
  btnRequestCaptcha.addEventListener('click', () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabList) => {
      if (tabList[0]) {
        chrome.tabs.sendMessage(tabList[0].id, { action: 'TRIGGER_CAPTCHA_SOLVE' });
        btnRequestCaptcha.textContent = '✓ Requested!';
        btnRequestCaptcha.style.pointerEvents = 'none';
        setTimeout(() => {
          btnRequestCaptcha.innerHTML = `
              <svg width="14" height="14" 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="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                Request Captcha Solve
                  `;
          btnRequestCaptcha.style.pointerEvents = '';
        }, 1500);
      }
    });
  });

  // ── Request New Site Captcha ──
  if (btnRequestNewSite) {
    btnRequestNewSite.addEventListener('click', async () => {
      chrome.storage.sync.get(['apiKey', 'userPlan'], async (result) => {
        if (!result.apiKey) {
          btnRequestNewSite.textContent = '✗ Require Login';
          btnRequestNewSite.style.color = 'var(--danger)';
          btnRequestNewSite.style.borderColor = 'var(--danger)';
          setTimeout(() => {
            btnRequestNewSite.innerHTML = `
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
                    Request Captcha from this site
                      `;
            btnRequestNewSite.style.color = 'var(--accent-light)';
            btnRequestNewSite.style.borderColor = 'var(--accent)';
          }, 2000);
          return;
        }

        if (!result.userPlan || result.userPlan === 'free') {
          btnRequestNewSite.textContent = '👑 Premium Only';
          btnRequestNewSite.style.color = '#f59e0b';
          btnRequestNewSite.style.borderColor = '#f59e0b';
          setTimeout(() => {
            btnRequestNewSite.innerHTML = `
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
                    Request Captcha from this site
                      `;
            btnRequestNewSite.style.color = 'var(--accent-light)';
            btnRequestNewSite.style.borderColor = 'var(--accent)';
          }, 2000);
          return;
        }

        if (!currentHostname || currentHostname === '—' || currentHostname === 'N/A') {
          btnRequestNewSite.textContent = '✗ Invalid Site';
          setTimeout(() => {
            btnRequestNewSite.innerHTML = `
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
                        Request Captcha from this site
            `;
          }, 2000);
          return;
        }

        btnRequestNewSite.textContent = '⏳ Sending...';
        btnRequestNewSite.style.pointerEvents = 'none';

        try {
          const res = await fetch(`${API_BASE}?action=request_captcha`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ api_key: result.apiKey, site_url: currentHostname })
          });
          const data = await res.json();

          if (data.success) {
            btnRequestNewSite.textContent = '✓ Requested!';
            btnRequestNewSite.style.color = 'var(--success)';
            btnRequestNewSite.style.borderColor = 'var(--success)';
          } else {
            btnRequestNewSite.textContent = '✗ Failed';
            btnRequestNewSite.style.color = 'var(--danger)';
            btnRequestNewSite.style.borderColor = 'var(--danger)';
          }
        } catch (e) {
          btnRequestNewSite.textContent = '✗ Error';
          btnRequestNewSite.style.color = 'var(--danger)';
          btnRequestNewSite.style.borderColor = 'var(--danger)';
        }

        setTimeout(() => {
          btnRequestNewSite.innerHTML = `
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
            Request Captcha from this site
              `;
          btnRequestNewSite.style.color = 'var(--accent-light)';
          btnRequestNewSite.style.borderColor = 'var(--accent)';
          btnRequestNewSite.style.pointerEvents = '';
        }, 3000);
      });
    });
  }

  // ── Open Options Page ──
  btnOptions.addEventListener('click', () => {
    chrome.runtime.openOptionsPage();
  });

  // ── Helpers ──
  function esc(str) {
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
  }

  function addLogoToQR(qrDataUrl, text, callback) {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();
    
    img.onload = () => {
      const size = img.width;
      canvas.width = size;
      canvas.height = size;
      
      // Draw QR
      ctx.drawImage(img, 0, 0);
      
      // Draw Logo Background (white circle)
      const logoSize = size * 0.28;
      const x = (size - logoSize) / 2;
      const y = (size - logoSize) / 2;
      
      ctx.fillStyle = '#ffffff';
      ctx.beginPath();
      ctx.arc(size/2, size/2, logoSize/1.8, 0, Math.PI * 2);
      ctx.fill();
      
      // Draw "T" letter
      ctx.fillStyle = '#7c6aff'; // Accent color
      ctx.font = `bold ${logoSize * 0.8}px 'Inter', sans-serif`;
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText(text, size/2, size/2 + (logoSize * 0.05));
      
      callback(canvas.toDataURL('image/png'));
    };
    img.src = qrDataUrl;
  }

  // ── Auto Update System ──
  async function checkForUpdates() {
    try {
      const response = await fetch('https://textercompter.store/download.php');
      const text = await response.text();
      
      // Match $version = '1.3.0'; OR Version 1.3.0
      const versionMatch = text.match(/\$version\s*=\s*'([\d.]+)'/) || text.match(/Version\s+([\d.]+)/);
      
      if (versionMatch && versionMatch[1]) {
        const remoteVersion = versionMatch[1];
        const localVersion = chrome.runtime.getManifest().version;
        
        if (isNewerVersion(remoteVersion, localVersion)) {
          if (latestVersionSpan) latestVersionSpan.textContent = remoteVersion;
          if (updateBanner) updateBanner.style.display = 'block';
        }
      }
    } catch (e) {
      console.error('Update check failed:', e);
    }
  }

  function isNewerVersion(remote, local) {
    const r = remote.split('.').map(Number);
    const l = local.split('.').map(Number);
    for (let i = 0; i < Math.max(r.length, l.length); i++) {
      const rv = r[i] || 0;
      const lv = l[i] || 0;
      if (rv > lv) return true;
      if (rv < lv) return false;
    }
    return false;
  }

  if (updateBanner) {
    updateBanner.addEventListener('click', () => {
      chrome.tabs.create({ url: 'https://textercompter.store/download.php' });
    });
  }

  // ── Init ──
  checkAuthState();
  detectCurrentSite();
  loadSettings();
  checkForUpdates();

  requestAnimationFrame(() => {
    switchTab('account');
  });
})();
