import { login, verifyOtp, verifySession } from '../lib/auth.js';
import { saveGeminiKey, testGeminiKey, getServerKeyStatus } from '../lib/gemini.js';
import { setSetting } from '../lib/db.js';

const $ = (id) => document.getElementById(id);

let currentStep = 1;
const TOTAL_STEPS = 6;

// Steps the DB says are already satisfied — the wizard skips over them so a
// returning user is never asked for what the server already has. (ADR-30)
//   2 = login   3 = Gemini key
const skip = { 2: false, 3: false };

function showStep(n) {
  document.querySelectorAll('.step').forEach((el) => el.classList.toggle('active', Number(el.dataset.step) === n));
  document.querySelector('.progress').style.setProperty('--p', `${(n / TOTAL_STEPS) * 100}%`);
  currentStep = n;
  window.scrollTo(0, 0);
}

// Advance from the current step to the next one that isn't already satisfied.
function nextVisible(from) {
  let n = from + 1;
  while (n < TOTAL_STEPS && skip[n]) n++;
  return Math.min(n, TOTAL_STEPS);
}
function advance() { showStep(nextVisible(currentStep)); }

document.querySelectorAll('[data-next]').forEach((btn) => {
  btn.addEventListener('click', advance);
});

// Returning-user fast-path (ADR-30): the account is already fully configured on
// the server, so username+password is all we need — no need to re-walk Gemini /
// FB / settings / legal. Mark onboarding done and show a short "ready" screen.
async function showReady(username) {
  await setSetting('onboardingCompleted', Date.now());
  document.querySelectorAll('.step').forEach((el) => el.classList.remove('active'));
  const ready = $('ob-ready');
  ready.hidden = false;
  ready.classList.add('active');
  const progress = document.querySelector('.progress');
  if (progress) progress.style.setProperty('--p', '100%');
  const msg = $('ob-ready-msg');
  if (msg && username) msg.textContent = `שלום ${username} — החשבון והמפתח שלך כבר מוגדרים. הכל מוכן לשימוש.`;
  window.scrollTo(0, 0);
}

$('ob-ready-fb')?.addEventListener('click', () => {
  chrome.tabs.create({ url: 'https://www.facebook.com/', active: true });
  window.close();
});
$('ob-ready-close')?.addEventListener('click', () => window.close());

// ── Bootstrap: probe the server and pre-satisfy steps ───────────────────────
// Runs before the user does anything. If the session survived (storage.sync
// mirror across reinstall) we skip login; if the DB already holds a Gemini key
// we skip the key step. The SW only opens this page when SOMETHING is missing,
// so this mostly fast-paths "session ok, key missing" → straight to Gemini.
async function bootstrap() {
  const boot = $('ob-boot-status');
  let sess = { ok: false };
  try { sess = await verifySession(); } catch { sess = { ok: false }; }

  if (sess.ok) {
    skip[2] = true; // already logged in
    let ks = { hasKey: false };
    try { ks = await getServerKeyStatus(); } catch { ks = { hasKey: false }; }
    if (ks.hasKey) skip[3] = true;

    // Session valid AND key present = fully-configured returning user. Even if
    // the SW opened this page, don't make them click through — go straight to
    // the ready screen. (Normally the SW skips onboarding entirely here.)
    if (skip[2] && skip[3]) { await showReady(sess.username); return; }

    if (boot) {
      const who = sess.username ? ` כ-${sess.username}` : '';
      boot.textContent = skip[3]
        ? `✅ מחובר${who} — החשבון והמפתח כבר מוגדרים. אפשר להמשיך.`
        : `✅ מחובר${who} — נותר רק לחבר מפתח Gemini.`;
      boot.hidden = false;
    }
    const nextBtn = $('ob-welcome-next');
    if (nextBtn) nextBtn.textContent = skip[3] ? 'הכל מוכן, המשך →' : 'המשך לחיבור AI →';
  }

  // If the key already exists, reflect it on the Gemini step too (in case the
  // user navigates there manually).
  if (skip[3]) {
    const gs = $('ob-gemini-status');
    if (gs) gs.textContent = '✅ כבר מוגדר מפתח — אפשר לדלג.';
  }
}
bootstrap();

// Step 2: Login. `_obOtp` holds the identifier while we wait for the 2FA code;
// when set, the same button verifies the code instead of re-sending the password.
let _obOtp = null;
$('ob-login-btn').addEventListener('click', async () => {
  const btn = $('ob-login-btn');
  $('ob-login-error').hidden = true;

  // --- 2FA step 2: the button is in "verify code" mode ---
  if (_obOtp) {
    const code = $('ob-password').value.trim();
    if (!/^\d{6}$/.test(code)) {
      $('ob-login-error').textContent = 'הזן קוד בן 6 ספרות'; $('ob-login-error').hidden = false; return;
    }
    btn.disabled = true; btn.textContent = 'מאמת...';
    const v = await verifyOtp(_obOtp.id, code).catch(() => ({ ok: false, error: 'אין חיבור לשרת' }));
    btn.disabled = false;
    if (!v.ok) { $('ob-login-error').textContent = v.error || 'קוד שגוי'; $('ob-login-error').hidden = false; btn.textContent = 'אמת קוד'; return; }
    // success → restore the form for next time + continue the wizard
    const uname = v.username; _obOtp = null;
    $('ob-username').disabled = false; $('ob-password').type = 'password'; $('ob-password').value = ''; btn.textContent = 'התחבר';
    skip[2] = true;
    let hasKey = false; try { const ks = await getServerKeyStatus(); hasKey = !!ks.hasKey; } catch {}
    if (hasKey) { await showReady(uname); return; }
    advance(); return;
  }

  // --- 2FA step 1: email + password ---
  const username = $('ob-username').value.trim();
  const password = $('ob-password').value;
  if (!username || !password) {
    $('ob-login-error').textContent = 'יש למלא אימייל/שם משתמש וסיסמה';
    $('ob-login-error').hidden = false;
    return;
  }
  btn.disabled = true; btn.textContent = 'מתחבר...';
  let r;
  try {
    r = await login(username, password);
  } catch (e) {
    r = { ok: false, error: 'אין חיבור לשרת — בדוק אינטרנט ונסה שוב' };
  }
  btn.disabled = false; btn.textContent = 'התחבר';
  if (!r.ok) {
    $('ob-login-error').textContent = r.error === 'invalid credentials' ? 'אימייל/שם משתמש או סיסמה שגויים' : r.error;
    $('ob-login-error').hidden = false;
    return;
  }
  // 2FA: password OK, code emailed → reuse the password field for the code.
  if (r.otpRequired) {
    _obOtp = { id: r.identifier || username };
    $('ob-username').disabled = true;
    $('ob-password').value = ''; $('ob-password').type = 'text';
    $('ob-login-error').textContent = r.email ? `שלחנו קוד ל-${r.email} — הזן אותו כאן` : 'שלחנו קוד לאימייל — הזן אותו כאן';
    $('ob-login-error').hidden = false;
    btn.textContent = 'אמת קוד';
    return;
  }
  skip[2] = true;
  // After a fresh login, check whether this account is already configured. If it
  // already has a Gemini key, it's a returning user — username+password was
  // enough, so fast-path straight to "ready" instead of re-walking the wizard.
  let hasKey = false;
  try { const ks = await getServerKeyStatus(); hasKey = !!ks.hasKey; } catch {}
  if (hasKey) { await showReady(username); return; }
  advance();
});

// Step 3: Gemini
$('ob-open-aistudio').addEventListener('click', () => {
  chrome.tabs.create({ url: 'https://aistudio.google.com/apikey' });
});

$('ob-save-gemini').addEventListener('click', async () => {
  const key = $('ob-gemini-key').value.trim();
  if (!key) {
    $('ob-gemini-status').textContent = 'הכנס מפתח קודם';
    return;
  }
  $('ob-gemini-status').textContent = '⏳ בודק...';
  const saved = await saveGeminiKey(key);
  if (!saved.ok) {
    $('ob-gemini-status').textContent = `❌ ${saved.error}`;
    return;
  }
  const r = await testGeminiKey();
  if (r.ok) {
    $('ob-gemini-status').textContent = '✅ מחובר בהצלחה!';
    skip[3] = true;
    setTimeout(advance, 800);
  } else {
    $('ob-gemini-status').textContent = `❌ ${r.error}`;
  }
});

$('ob-skip-gemini').addEventListener('click', advance);

// Step 4: Open the connected platform (currently FB; will be selectable as we add more)
$('ob-open-fb').addEventListener('click', () => {
  chrome.tabs.create({ url: 'https://www.facebook.com/', active: true });
});

// Step 6: Legal + finish
$('ob-accept-tos').addEventListener('change', (e) => {
  $('ob-finish').disabled = !e.target.checked;
});

$('ob-finish').addEventListener('click', async () => {
  // Save throttle config from step 5
  await chrome.runtime.sendMessage({
    type: 'SET_THROTTLE_CONFIG',
    payload: {
      activeHourStart: Number($('ob-active-start').value) || 9,
      activeHourEnd: Number($('ob-active-end').value) || 22,
      dailyCap: Number($('ob-daily-cap').value) || 25,
    },
  });
  // Mark onboarding done
  await setSetting('onboardingCompleted', Date.now());
  // Open popup or close tab
  window.close();
});

$('ob-privacy').addEventListener('click', (e) => {
  e.preventDefault();
  chrome.tabs.create({ url: 'https://organicai.doogree.co.il/legal/privacy.html' });
});
