/**
 * Halaman Setup Lokal - Manajemen Key & Pengaturan UI
 */

// --- Storage helpers ---
let uiLocales = {};

async function applyTranslations(lang) {
  try {
    const url = chrome.runtime.getURL(`_locales/${lang}/messages.json`);
    const res = await fetch(url);
    uiLocales = await res.json();
    document.querySelectorAll('[data-i18n]').forEach(el => {
      const key = el.getAttribute('data-i18n');
      if (uiLocales[key]) {
        if (el.tagName === 'TEXTAREA' || (el.tagName === 'INPUT' && el.type === 'text')) {
          el.placeholder = uiLocales[key].message;
        } else {
          el.innerHTML = uiLocales[key].message;
        }
      }
    });
  } catch (e) {
    console.error('Translation error:', e);
  }
}

function localSet(key, val) {
  return new Promise(resolve => {
    const o = {}; o[key] = val;
    chrome.storage.local.set(o, () => resolve(val));
  });
}
function localGet(key, fallback = '') {
  return new Promise(resolve => {
    const o = {}; o[key] = fallback;
    chrome.storage.local.get(o, r => resolve(r[key]));
  });
}

// --- Tab switching ---
document.querySelectorAll('.provider-tab').forEach(tab => {
  tab.addEventListener('click', () => {
    document.querySelectorAll('.provider-tab').forEach(t => t.classList.remove('active'));
    tab.classList.add('active');
    const provider = tab.dataset.provider;
    document.querySelectorAll('.keys-panel').forEach(p => p.style.display = 'none');
    document.getElementById(`${provider}-panel`).style.display = 'block';
  });
});

// --- Load saved data ---
async function loadSavedData() {
  const provider = await localGet('localProvider', 'gemini');
  document.getElementById('providerSelect').value = provider;

  const apiBackend = await localGet('localApiBackend', 'proxy');
  document.getElementById('apiBackend').value = apiBackend;

  updateBackendVisibility(apiBackend);

  // Keys
  const geminiKeys = await localGet('localKeys_gemini', []);
  const groqKeys = await localGet('localKeys_groq', []);
  const mistralKeys = await localGet('localKeys_mistral', []);
  renderKeyList('gemini', geminiKeys);
  renderKeyList('groq', groqKeys);
  renderKeyList('mistral', mistralKeys);

  // Settings
  const settings = await localGet('localSettings', {});
  document.getElementById('maxKeywords').value = settings.maxKeywords || 35;
  document.getElementById('language').value = settings.language || 'en';
  
  const defaultUiLang = chrome.i18n.getUILanguage().startsWith('id') ? 'id' : 'en';
  const uiLang = settings.uiLanguage || defaultUiLang;
  const uiLangSelect = document.getElementById('uiLanguage');
  if (uiLangSelect) uiLangSelect.value = uiLang;
  applyTranslations(uiLang);

  // Auto fill
  document.getElementById('autoCategory').checked = settings.autoCategory !== false;
  document.getElementById('autoFileType').checked = settings.autoFileType !== false;
  document.getElementById('defaultNo').checked = settings.defaultNo !== false;
  document.getElementById('defaultAi').checked = settings.defaultAi !== false;

  // Title length
  if (settings.minTitleLength) document.getElementById('minTitleLength').value = settings.minTitleLength;

  // Sync Settings
  document.getElementById('enableSmartUpload').checked = settings.enableSmartUpload === true;
  document.getElementById('syncEmail').value = settings.syncEmail || '';
}

function updateSyncUi(isLoggedIn) {
  const wrapper = document.getElementById('syncSettingsWrapper');
  const enableSmartUpload = document.getElementById('enableSmartUpload');
  const syncEmail = document.getElementById('syncEmail');
  const testDbBtn = document.getElementById('testDbBtn');
  
  if (isLoggedIn) {
    wrapper.style.opacity = '1';
    wrapper.style.pointerEvents = 'auto';
    enableSmartUpload.disabled = false;
    syncEmail.disabled = false;
    if (testDbBtn) testDbBtn.style.display = 'inline-block';
  } else {
    wrapper.style.opacity = '0.5';
    wrapper.style.pointerEvents = 'none';
    enableSmartUpload.disabled = true;
    syncEmail.disabled = true;
    enableSmartUpload.checked = false; // Force disable if not logged in
    if (testDbBtn) testDbBtn.style.display = 'none';
  }
}

function updateBackendVisibility(mode) {
  if (mode === 'proxy') {
    document.getElementById('keysCard').style.display = 'none';
    document.getElementById('providerSelectRow').style.display = 'none';
  } else {
    document.getElementById('keysCard').style.display = 'block';
    document.getElementById('providerSelectRow').style.display = 'flex';
  }
}

// --- Toggle & Provider ---
document.getElementById('providerSelect').addEventListener('change', async (e) => {
  await localSet('localProvider', e.target.value);
});

document.getElementById('apiBackend').addEventListener('change', async (e) => {
  const mode = e.target.value;
  await localSet('localApiBackend', mode);
  updateBackendVisibility(mode);
});

// --- Firebase Auth & Firestore Setup ---
const firebaseConfig = {
  apiKey: "AIzaSyCNGYKxyqvqCrduHbl6BJ5a2AbBOJMsrz8",
  authDomain: "fast-proxy-ai.firebaseapp.com",
  projectId: "fast-proxy-ai",
  storageBucket: "fast-proxy-ai.firebasestorage.app",
  messagingSenderId: "1005825635113",
  appId: "1:1005825635113:web:604f96f2746e17f0ff7d38"
};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}
const auth = firebase.auth();
const db = firebase.firestore();

// Set persistence to LOCAL to ensure session survives browser restarts
auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL);

async function fetchSubscriptionStatus(email) {
  const subSection = document.getElementById('subscriptionSection');
  const statusBadge = document.getElementById('subStatusBadge');
  const expiryRow = document.getElementById('subExpiryRow');
  const expiryDate = document.getElementById('subExpiryDate');

  subSection.style.display = 'block';
  statusBadge.textContent = 'Mengecek...';
  statusBadge.className = 'sub-badge-active';
  expiryRow.style.display = 'none';

  try {
    const docRef = db.collection('users').doc(email);
    const docSnap = await docRef.get();

    if (docSnap.exists) {
      const data = docSnap.data();
      const expiry = data.subscriptionExpiry ? new Date(data.subscriptionExpiry) : null;
      const now = new Date();

      const noticeEl = document.getElementById('subExpiredNotice');

      if (expiry && expiry > now) {
        if (data.isTrial) {
            statusBadge.textContent = 'AKTIF (TRIAL 1 HARI)';
            statusBadge.className = 'sub-badge-active';
            statusBadge.style.background = 'rgba(9, 132, 227, 0.2)';
            statusBadge.style.color = '#74b9ff';
            statusBadge.style.borderColor = 'rgba(9, 132, 227, 0.5)';
            updatePurchaseButton(false); // Enable the button for trial users
        } else {
            statusBadge.textContent = 'AKTIF PRO';
            statusBadge.className = 'sub-badge-active';
            statusBadge.style.background = '';
            statusBadge.style.color = '';
            statusBadge.style.borderColor = '';
            updatePurchaseButton(true);
        }
        expiryRow.style.display = 'flex';
        expiryDate.textContent = expiry.toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' });
        if (noticeEl) noticeEl.style.display = 'none';
      } else if (expiry) {
        statusBadge.textContent = 'TELAH BERAKHIR';
        statusBadge.className = 'sub-badge-expired';
        statusBadge.style.background = 'rgba(239, 68, 68, 0.15)';
        statusBadge.style.fontSize = '12px';
        expiryRow.style.display = 'flex';
        expiryDate.textContent = expiry.toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' });
        if (noticeEl) noticeEl.style.display = 'block';
        updatePurchaseButton(false);
      } else {
        statusBadge.textContent = 'Tidak berlangganan Sewa APIKey';
        statusBadge.className = 'sub-badge-expired';
        statusBadge.style.background = '#636e72';
        statusBadge.style.fontSize = '11px';
        if (noticeEl) noticeEl.style.display = 'none';
        updatePurchaseButton(false);
        showStatus('proxy-status', '💡 Note: Anda harus menggunakan APIKey sendiri jika tidak menyewa API.', 'info');
      }
    } else {
      const noticeEl = document.getElementById('subExpiredNotice');
      statusBadge.textContent = 'Tidak berlangganan Sewa APIKey';
      statusBadge.className = 'sub-badge-expired';
      statusBadge.style.background = '#636e72';
      statusBadge.style.fontSize = '11px';
      if (noticeEl) noticeEl.style.display = 'none';
      updatePurchaseButton(false);
      showStatus('proxy-status', '💡 Note: Anda harus menggunakan APIKey sendiri jika tidak menyewa API.', 'info');
    }
  } catch (e) {
    console.warn("Error fetching sub:", e);
    statusBadge.textContent = 'ERROR';
    updatePurchaseButton(false);
  }
}

// Function to generate hardware fingerprint and get Device ID
async function getOrCreateDeviceId() {
  return new Promise(async (resolve) => {
    chrome.storage.local.get(['deviceId'], async (res) => {
      if (res.deviceId) {
         resolve(res.deviceId);
      } else {
         const components = [
           navigator.hardwareConcurrency || 'unknown',
           navigator.deviceMemory || 'unknown',
           screen.width,
           screen.height,
           screen.colorDepth,
           Intl.DateTimeFormat().resolvedOptions().timeZone
         ];
         try {
           const canvas = document.createElement('canvas');
           const gl = canvas.getContext('webgl');
           if (gl) {
             const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
             if (debugInfo) components.push(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL));
           }
         } catch(e) {}
         
         const rawString = components.join('|');
         const msgBuffer = new TextEncoder().encode(rawString);
         const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
         const hashArray = Array.from(new Uint8Array(hashBuffer));
         const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
         
         const newId = 'dev_' + hashHex.substring(0, 16);
         chrome.storage.local.set({ deviceId: newId }, () => resolve(newId));
      }
    });
  });
}

// Global flag to prevent clearing tokens during initial load
let isInitialAuthCheck = true;

auth.onAuthStateChanged(async (user) => {
  if (user) {
    console.log("[Auth] User logged in:", user.email);
    updateSyncUi(true);
    document.getElementById('proxyUserInfo').style.display = 'block';
    document.getElementById('proxyUserEmail').textContent = user.email;
    document.getElementById('googleLoginBtn').style.display = 'none';
    document.getElementById('googleLogoutBtn').style.display = 'block';
    const notLoggedInNotice = document.getElementById('notLoggedInNotice');
    if (notLoggedInNotice) notLoggedInNotice.style.display = 'none';

    // Sync with background script's expected storage key
    const token = await user.getIdToken();
    await localSet('userAuth', {
      user: {
        email: user.email,
        uid: user.uid,
        displayName: user.displayName,
        photoURL: user.photoURL,
        lastLoginAt: user.metadata.lastSignInTime,
        createdAt: user.metadata.creationTime
      },
      token: token,
      refreshToken: user.refreshToken
    });

    fetchSubscriptionStatus(user.email);

    try {
      const docRef = db.collection('users').doc(user.email);
      const subSnap = await docRef.get();
      let isPro = false;

      if (subSnap.exists) {
        const subData = subSnap.data();
        const expiry = subData.subscriptionExpiry ? new Date(subData.subscriptionExpiry) : null;
        if (expiry && expiry > new Date()) {
          isPro = true;
        }
      }

      // --- TRIAL ACTIVATION LOGIC ---
      if (!isPro) {
        try {
          const deviceId = await getOrCreateDeviceId();
          // Find proxy url to use for api
          const configSnap = await db.collection('proxyConfig').get();
          let proxyBaseUrl = '';
          configSnap.forEach(doc => {
            if (!proxyBaseUrl && doc.data().proxyUrl) {
               const url = new URL(doc.data().proxyUrl);
               proxyBaseUrl = url.origin;
            }
          });
          
          console.log("[Trial] deviceId:", deviceId, "proxyBaseUrl:", proxyBaseUrl);
          if (proxyBaseUrl) {
             const res = await fetch(proxyBaseUrl + '/api/webhook-lynkid', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'start-trial', email: user.email, deviceHash: deviceId })
             });
             const trialRes = await res.json();
             console.log("[Trial] Response:", trialRes);
             if (trialRes.ok) {
                 isPro = true;
                 fetchSubscriptionStatus(user.email);
                 showStatus('proxy-status', '✅ Free Trial 1 Hari Berhasil Diaktifkan!', 'success');
                 
                 const noticeEl = document.getElementById('subExpiredNotice');
                 if (noticeEl) {
                     noticeEl.style.display = 'block';
                     noticeEl.style.background = 'rgba(9, 132, 227, 0.1)';
                     noticeEl.style.borderColor = 'rgba(9, 132, 227, 0.3)';
                     noticeEl.style.color = '#74b9ff';
                     noticeEl.innerHTML = '✨ <b>Masa Percobaan (Trial 1 Hari) Aktif!</b><br>Nikmati fitur AI tanpa batas. Beli paket sekarang agar tidak terputus besok.';
                 }
             } else {
                 if (trialRes.code !== 'TRIAL_USED' && trialRes.code !== 'TRIAL_USED_USER') {
                     console.log("Trial claim failed:", trialRes.message);
                 }
             }
          }
        } catch(e) {
          console.error("Error claiming trial:", e);
        }
      }

      if (isPro) {
        // --- DEVICE TRACKING LOGIC ---
        try {
          const deviceId = await getOrCreateDeviceId();
          const devicesRef = db.collection('users').doc(user.email).collection('devices');
          const devicesSnap = await devicesRef.get();
          
          let deviceCount = 0;
          let isDeviceRegistered = false;
          
          devicesSnap.forEach(d => {
             deviceCount++;
             if (d.id === deviceId) isDeviceRegistered = true;
          });
          
          if (!isDeviceRegistered && deviceCount >= 2) {
             isPro = false; // Batalkan status PRO
             await localSet('aiProxyServers', []);
             await localSet('aiProxyUrl', '');
             await localSet('aiProxyToken', '');
             showStatus('proxy-status', '❌ Akses Ditolak: Batas Maksimal 2 Perangkat Tercapai.', 'error');
             
             const limitNotice = document.getElementById('deviceLimitNotice');
             if (limitNotice) limitNotice.style.display = 'block';
             
             const sb = document.getElementById('subStatusBadge');
             if (sb) {
               sb.textContent = 'LIMIT PERANGKAT';
               sb.className = 'sub-badge-expired';
               sb.style.background = 'rgba(239, 68, 68, 0.15)';
               sb.style.color = '#fca5a5';
             }
          } else {
             // Daftarkan atau update perangkat ini
             await devicesRef.doc(deviceId).set({
                lastSeen: new Date().toISOString(),
                userAgent: navigator.userAgent
             }, { merge: true });
             
             const limitNotice = document.getElementById('deviceLimitNotice');
             if (limitNotice) limitNotice.style.display = 'none';
          }
        } catch (err) {
          console.warn("[Device] Error checking devices:", err);
          // Jika Firebase rules belum di-update, biarkan lolos dulu (fail-safe) agar tidak memblokir user secara total
        }
      }

      if (isPro) {
        // Ambil SEMUA dokumen dari collection proxyConfig (multi-server load balancing)
        const configSnap = await db.collection('proxyConfig').get();
        const servers = [];
        configSnap.forEach(doc => {
          const data = doc.data();
          if (data.proxyUrl && data.proxyToken) {
            servers.push({ id: doc.id, url: data.proxyUrl, token: data.proxyToken });
          }
        });

        if (servers.length > 0) {
          await localSet('aiProxyServers', servers);
          // Backward compatibility: tetap simpan satu sebagai default
          await localSet('aiProxyUrl', servers[0].url);
          await localSet('aiProxyToken', servers[0].token);
          showStatus('proxy-status', `✅ Layanan Sewa API Aktif! (${servers.length} server tersedia)`, 'success');
        }
      } else {
        await localSet('aiProxyServers', []);
        await localSet('aiProxyUrl', '');
        await localSet('aiProxyToken', '');
        showStatus('proxy-status', '❌ Masa sewa habis atau belum berlangganan.', 'error');
      }
    } catch (e) {
      showStatus('proxy-status', `❌ Gagal memvalidasi status: ${e.message}`, 'error');
    }
  } else {
    console.log("[Auth] User logged out or session expired.");
    updateSyncUi(false);
    document.getElementById('proxyUserInfo').style.display = 'none';
    document.getElementById('googleLoginBtn').style.display = 'block';
    document.getElementById('googleLogoutBtn').style.display = 'none';
    const notLoggedInNotice = document.getElementById('notLoggedInNotice');
    if (notLoggedInNotice) notLoggedInNotice.style.display = 'block';

    // Clear userAuth info
    await localSet('userAuth', null);

    // ONLY clear tokens if this is NOT the initial load check.
    // This prevents wiping tokens if Firebase takes a moment to initialize the session.
    if (!isInitialAuthCheck) {
      await localSet('aiProxyServers', []);
      await localSet('aiProxyUrl', '');
      await localSet('aiProxyToken', '');
      showStatus('proxy-status', 'Sesi berakhir.', 'info');
    }

    const subSection = document.getElementById('subscriptionSection');
    if (subSection) subSection.style.display = 'none';
    updatePurchaseButton(false);
  }
  isInitialAuthCheck = false;
});

document.getElementById('googleLoginBtn').addEventListener('click', () => {
  const btn = document.getElementById('googleLoginBtn');
  const originalText = btn.innerHTML;
  btn.innerHTML = '<span class="spinner"></span> Menghubungkan...';
  btn.disabled = true;

  const clientId = '1005825635113-khn172rlccv0dnbgvmg991tn3peihcam.apps.googleusercontent.com';
  const redirectUri = chrome.identity.getRedirectURL();
  const nonce = Math.random().toString(36).substring(2) + Date.now().toString(36);
  const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${clientId}&response_type=id_token&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email%20profile&nonce=${nonce}`;

  chrome.identity.launchWebAuthFlow({
    url: authUrl,
    interactive: true
  }, (responseUrl) => {
    btn.innerHTML = originalText;
    btn.disabled = false;

    if (chrome.runtime.lastError || !responseUrl) {
      showStatus('proxy-status', `Login gagal: ${chrome.runtime.lastError?.message || 'Batal'}`, 'error');
      return;
    }

    try {
      const url = new URL(responseUrl.replace('#', '?'));
      const idToken = url.searchParams.get('id_token');

      if (!idToken) {
        showStatus('proxy-status', 'Login gagal: Token tidak ditemukan.', 'error');
        return;
      }

      showStatus('proxy-status', 'Mengotentikasi...', 'info');
      const credential = firebase.auth.GoogleAuthProvider.credential(idToken);
      firebase.auth().signInWithCredential(credential).catch((error) => {
        showStatus('proxy-status', `Gagal: ${error.message}`, 'error');
      });
    } catch (e) {
      showStatus('proxy-status', `Error: ${e.message}`, 'error');
    }
  });
});

document.getElementById('googleLogoutBtn').addEventListener('click', async () => {
  // Explicit logout by user
  isInitialAuthCheck = false;
  await auth.signOut();
  await localSet('aiProxyServers', []);
  await localSet('aiProxyUrl', '');
  await localSet('aiProxyToken', '');
  await localSet('userAuth', null);
  showStatus('proxy-status', 'Berhasil keluar.', 'info');
});

// --- Key Validation & Save ---
async function validateAndSaveKeys(provider) {
  const textarea = document.getElementById(`${provider}-keys-input`);
  const rawKeys = textarea.value.trim();
  if (!rawKeys) {
    showStatus('keys-status', 'Silakan masukkan API key', 'error');
    return;
  }

  const keys = rawKeys.split('\n').map(k => k.trim()).filter(k => k.length > 0);
  if (keys.length === 0) {
    showStatus('keys-status', 'Key tidak valid', 'error');
    return;
  }

  const btn = document.getElementById(`${provider}-validate-btn`);
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span> Validasi...';

  const results = [];
  let validCount = 0;
  const listEl = document.getElementById(`${provider}-key-list`);
  listEl.innerHTML = '';

  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    const masked = maskKey(key);
    const item = createKeyItem(masked, 'checking', 'Mengecek...');
    item.id = `key-item-${provider}-${i}`;
    listEl.appendChild(item);

    let result;
    try {
      result = await new Promise((resolve, reject) => {
        chrome.runtime.sendMessage(
          { cmd: 'validateKey', target: 'background', provider, apiKey: key },
          (resp) => {
            if (chrome.runtime.lastError) reject(new Error(chrome.runtime.lastError.message));
            else resolve(resp);
          }
        );
      });
    } catch (e) {
      result = { valid: false, error: e.message };
    }

    if (!result) result = { valid: false, error: 'Koneksi ke sistem latar belakang terputus. Harap Refresh (F5).' };

    results.push({ key, ...result });
    const itemEl = document.getElementById(`key-item-${provider}-${i}`);
    if (result.valid) {
      validCount++;
      itemEl.className = 'key-item valid';
      itemEl.querySelector('.key-status').className = 'key-status status-valid';
      itemEl.querySelector('.key-status').textContent = '✓ Valid';
    } else {
      itemEl.className = 'key-item invalid';
      itemEl.querySelector('.key-status').className = 'key-status status-invalid';
      itemEl.querySelector('.key-status').textContent = `✗ Gagal`;
    }
  }

  const validKeys = results.filter(r => r.valid).map(r => r.key);
  await localSet(`localKeys_${provider}`, validKeys);
  const indexData = await localGet('localKeyIndex', {});
  indexData[provider] = 0;
  await localSet('localKeyIndex', indexData);

  btn.disabled = false;
  btn.innerHTML = 'Simpan & Validasi';

  if (validCount > 0) {
    showStatus('keys-status', `Berhasil menyimpan ${validCount} key ${provider}`, 'success');
  } else {
    showStatus('keys-status', `Semua key tidak valid`, 'error');
  }
  textarea.value = '';
}

async function clearKeys(provider) {
  if (!confirm(`Hapus semua key ${provider}?`)) return;
  await localSet(`localKeys_${provider}`, []);
  document.getElementById(`${provider}-key-list`).innerHTML = '';
  showStatus('keys-status', `Semua key ${provider} dihapus`, 'info');
}

function renderKeyList(provider, keys) {
  const listEl = document.getElementById(`${provider}-key-list`);
  listEl.innerHTML = '';
  if (!keys || keys.length === 0) return;

  keys.forEach((key, i) => {
    const item = createKeyItem(maskKey(key), 'valid', '✓ Tersimpan');
    const removeBtn = document.createElement('button');
    removeBtn.className = 'key-remove';
    removeBtn.innerHTML = '×';
    removeBtn.onclick = () => removeKey(provider, i);
    item.appendChild(removeBtn);
    listEl.appendChild(item);
  });
}

async function removeKey(provider, index) {
  const keys = await localGet(`localKeys_${provider}`, []);
  keys.splice(index, 1);
  await localSet(`localKeys_${provider}`, keys);
  renderKeyList(provider, keys);
}

function createKeyItem(maskedKey, status, statusText) {
  const item = document.createElement('div');
  item.className = `key-item ${status}`;
  item.innerHTML = `
    <span class="key-text">${maskedKey}</span>
    <span class="key-status status-${status}">${statusText}</span>
  `;
  return item;
}

function maskKey(key) {
  if (key.length <= 10) return '****';
  return key.substring(0, 6) + '•••' + key.substring(key.length - 4);
}

// --- Settings ---
async function saveSettings() {
  const current = await localGet('localSettings', {});
  const settings = {
    ...current,
    maxKeywords: parseInt(document.getElementById('maxKeywords').value) || 35,
    language: document.getElementById('language').value || 'en',
    uiLanguage: document.getElementById('uiLanguage') ? document.getElementById('uiLanguage').value : 'id',
    // Auto fill
    autoCategory: document.getElementById('autoCategory').checked,
    autoFileType: document.getElementById('autoFileType').checked,
    defaultNo: document.getElementById('defaultNo').checked,
    defaultAi: document.getElementById('defaultAi').checked,
    // Title length
    minTitleLength: parseInt(document.getElementById('minTitleLength').value) || 70,
    // Sync Settings
    enableSmartUpload: document.getElementById('enableSmartUpload').checked,
    syncEmail: document.getElementById('syncEmail').value.trim()
  };

  await localSet('localSettings', settings);
  showStatus('settings-status', 'Tersimpan otomatis!', 'success');
}

async function resetSettings() {
  if (!confirm('Kembalikan semua pengaturan ke default?')) return;

  document.getElementById('maxKeywords').value = 35;
  document.getElementById('language').value = 'en';
  document.getElementById('autoCategory').checked = true;
  document.getElementById('autoFileType').checked = true;
  document.getElementById('defaultNo').checked = true;
  document.getElementById('defaultAi').checked = true;
  document.getElementById('minTitleLength').value = 70;
  document.getElementById('enableSmartUpload').checked = false;
  document.getElementById('syncEmail').value = '';

  await localSet('localSettings', {
    maxKeywords: 35, language: 'en',
    autoCategory: true, autoFileType: true, defaultNo: true, defaultAi: true,
    minTitleLength: 70, enableSmartUpload: false, syncEmail: ''
  });
  showStatus('settings-status', 'Pengaturan telah direset', 'info');
}

// Auto-save bindings
const settingIds = [
  'maxKeywords', 'language', 'uiLanguage', 'autoCategory', 'autoFileType', 'defaultNo', 'defaultAi', 'minTitleLength', 'enableSmartUpload', 'syncEmail'
];
settingIds.forEach(id => {
  const el = document.getElementById(id);
  if (el) el.addEventListener('change', saveSettings);
});

const uiLangEl = document.getElementById('uiLanguage');
if (uiLangEl) {
  uiLangEl.addEventListener('change', (e) => {
    applyTranslations(e.target.value);
  });
}

// --- Test Connection ---
async function testConnection() {
  const testBtn = document.getElementById('testBtn');
  const resultEl = document.getElementById('test-result');
  const testPrompt = document.getElementById('testPrompt').value.trim();
  const provider = document.getElementById('providerSelect').value;
  const backend = document.getElementById('apiBackend').value;

  if (!testPrompt) {
    showStatus('keys-status', 'Masukkan deskripsi gambar untuk tes', 'error');
    return;
  }

  await localSet('imgName', testPrompt);
  await localSet('searchType', 'localAi');

  testBtn.disabled = true;
  testBtn.innerHTML = '<span class="spinner"></span> Menjalankan...';
  resultEl.style.display = 'block';
  resultEl.textContent = `Menghubungi AI (${backend === 'proxy' ? 'Sewa API' : provider})...`;

  const startTime = Date.now();

  try {
    const result = await new Promise((resolve, reject) => {
      chrome.runtime.sendMessage(
        { cmd: 'localProcess', target: 'background', searchType: backend === 'proxy' ? 'proxy' : 'localAi', imageUrl: null, isTest: true },
        (resp) => {
          if (chrome.runtime.lastError) reject(new Error(chrome.runtime.lastError.message));
          else resolve(resp);
        }
      );
    });
    const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);

    if (result && result.success) {
      resultEl.style.borderColor = 'var(--green)';
      resultEl.textContent = `✅ Berhasil (${elapsed}s)\n\n${result.result}`;
    } else {
      resultEl.style.borderColor = 'var(--red)';
      resultEl.textContent = `❌ Gagal (${elapsed}s)\n\n${result?.error || 'Terjadi kesalahan'}`;
    }
  } catch (e) {
    const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
    resultEl.style.borderColor = 'var(--red)';
    resultEl.textContent = `❌ Error (${elapsed}s)\n\n${e.message || e}`;
  }

  testBtn.disabled = false;
  testBtn.innerHTML = '▶ Jalankan Tes AI';
}

// --- Status UI ---
function showStatus(elementId, message, type = 'info') {
  const el = document.getElementById(elementId);
  el.innerHTML = `<div class="status-bar ${type}">${message}</div>`;
  setTimeout(() => { if (el.textContent === message) el.innerHTML = ''; }, 6000);
}

// --- Bind all button events ---
document.getElementById('gemini-validate-btn').addEventListener('click', () => validateAndSaveKeys('gemini'));
document.getElementById('gemini-clear-btn').addEventListener('click', () => clearKeys('gemini'));
document.getElementById('groq-validate-btn').addEventListener('click', () => validateAndSaveKeys('groq'));
document.getElementById('groq-clear-btn').addEventListener('click', () => clearKeys('groq'));
document.getElementById('mistral-validate-btn').addEventListener('click', () => validateAndSaveKeys('mistral'));
document.getElementById('mistral-clear-btn').addEventListener('click', () => clearKeys('mistral'));
document.getElementById('resetSettingsBtn').addEventListener('click', resetSettings);
document.getElementById('testBtn').addEventListener('click', testConnection);

document.getElementById('testDbBtn').addEventListener('click', async () => {
  const btn = document.getElementById('testDbBtn');
  btn.disabled = true;
  btn.textContent = 'Mengecek...';
  
  try {
    const userAuth = await localGet('userAuth', null);
    const settings = await localGet('localSettings', {});
    const ownEmail = userAuth?.user?.email || null;
    const teamId = settings.syncEmail ? settings.syncEmail.trim().toLowerCase() : null;
    
    if (!ownEmail) {
      throw new Error('User belum login. Silakan Login terlebih dahulu.');
    }

    const results = [];
    const testHash = 'test_' + Math.random().toString(36).substring(7);
    const testData = {
      filename: 'test_sync.jpg',
      date: new Date().toISOString(),
      hash: testHash,
      uploadedBy: ownEmail
    };

    // 1. Test own personal collection
    try {
      await db.collection('users').doc(ownEmail).collection('uploads').doc(testHash).set(testData);
      const readDoc = await db.collection('users').doc(ownEmail).collection('uploads').doc(testHash).get();
      if (readDoc.exists) {
        results.push(`✅ Koleksi pribadi (${ownEmail}): OK`);
        await db.collection('users').doc(ownEmail).collection('uploads').doc(testHash).delete();
      } else {
        results.push(`❌ Koleksi pribadi: Write OK, Read gagal`);
      }
    } catch (e) {
      results.push(`❌ Koleksi pribadi: ${e.message}`);
    }

    // 2. Test shared team collection
    if (teamId) {
      try {
        await db.collection('teams').doc(teamId).collection('uploads').doc(testHash).set(testData);
        const readTeam = await db.collection('teams').doc(teamId).collection('uploads').doc(testHash).get();
        if (readTeam.exists) {
          results.push(`✅ Tim (${teamId}): Write & Read OK — Shared pool aktif!`);
          await db.collection('teams').doc(teamId).collection('uploads').doc(testHash).delete();
        } else {
          results.push(`❌ Tim (${teamId}): Write OK, Read gagal`);
        }
      } catch (e) {
        results.push(`❌ Tim (${teamId}): ${e.message}`);
      }
    } else {
      results.push(`⚠️ Email Tim belum diisi — hanya menggunakan koleksi pribadi`);
    }

    showStatus('settings-status', results.join('<br>'), 'success');
  } catch (e) {
    showStatus('settings-status', '❌ DB Error: ' + e.message, 'error');
  } finally {
    btn.disabled = false;
    btn.textContent = '🔍 Test Sync';
  }
});

// --- Purchase & Modal Logic ---
const PURCHASE_LINK = 'http://lynk.id/aronisme/w6rgnn913xpm/checkout';

function updatePurchaseButton(isPro) {
  const buyBtn = document.getElementById('buySubBtn');
  if (isPro) {
    buyBtn.disabled = true;
    buyBtn.innerHTML = '✅ Berlangganan';
    buyBtn.className = 'btn btn-outline';
  } else {
    buyBtn.disabled = false;
    buyBtn.innerHTML = '⚡ Sewa API Sekarang';
    buyBtn.className = 'btn btn-green';
  }
}

// Modal Elements
const paymentModal = document.getElementById('paymentModal');
const modalUserEmail = document.getElementById('modalUserEmail');
const modalCopyBtn = document.getElementById('modalCopyBtn');
const modalCancelBtn = document.getElementById('modalCancelBtn');
const buySubBtn = document.getElementById('buySubBtn');

buySubBtn.addEventListener('click', () => {
  const user = auth.currentUser;
  if (!user) {
    showStatus('proxy-status', 'Silakan masuk dengan Google terlebih dahulu.', 'error');
    return;
  }
  modalUserEmail.textContent = user.email;
  paymentModal.style.display = 'flex';
});

modalCopyBtn.addEventListener('click', () => {
  const email = modalUserEmail.textContent;
  navigator.clipboard.writeText(email).then(() => {
    const originalText = modalCopyBtn.textContent;
    modalCopyBtn.textContent = '✅ Tersalin! Mengalihkan...';
    modalCopyBtn.style.background = 'linear-gradient(135deg, #10b981, #059669)';
    modalCopyBtn.style.boxShadow = '0 4px 20px rgba(16, 185, 129, 0.4)';
    setTimeout(() => {
      modalCopyBtn.textContent = originalText;
      modalCopyBtn.style.background = '';
      modalCopyBtn.style.boxShadow = '';
      // Redirect after copy
      window.open(PURCHASE_LINK, '_blank');
      paymentModal.style.display = 'none';
    }, 1000);
  });
});

modalCancelBtn.addEventListener('click', () => {
  paymentModal.style.display = 'none';
});

// Close modal when clicking outside
paymentModal.addEventListener('click', (e) => {
  if (e.target === paymentModal) paymentModal.style.display = 'none';
});

// --- Init ---
loadSavedData();
loadSavedData();
