/* firebaseAuth.jsx — Authentication (login, signup, logout) */

async function signUpGuest(email, password, name) {
  const auth = await window.getFirebaseAuth();
  const { createUserWithEmailAndPassword, updateProfile } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-auth.js');

  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    const user = userCredential.user;

    // Update profile
    await updateProfile(user, { displayName: name });

    // Save guest profile to Firestore
    const db = await window.getFirebaseDb();
    const { doc, setDoc, serverTimestamp } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

    await setDoc(doc(db, 'guests', user.uid), {
      uid: user.uid,
      email: email,
      name: name,
      verified: false,
      createdAt: serverTimestamp(),
      avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${name}`,
    });

    return user;
  } catch (error) {
    console.error('Sign up error:', error.message);
    throw error;
  }
}

async function loginGuest(email, password) {
  const auth = await window.getFirebaseAuth();
  const { signInWithEmailAndPassword } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-auth.js');

  try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    return userCredential.user;
  } catch (error) {
    console.error('Login error:', error.message);
    throw error;
  }
}

async function logoutUser() {
  const auth = await window.getFirebaseAuth();
  const { signOut } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-auth.js');

  try {
    await signOut(auth);
  } catch (error) {
    console.error('Logout error:', error.message);
    throw error;
  }
}

async function getCurrentUser() {
  const auth = await window.getFirebaseAuth();
  return auth.currentUser;
}

async function onAuthStateChanged(callback) {
  const auth = await window.getFirebaseAuth();
  const { onAuthStateChanged: fbOnAuthStateChanged } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-auth.js');

  return fbOnAuthStateChanged(auth, callback);
}

/* ── Social + phone sign-in (additive) ──────────────────────────────────────
 * All providers lazy-import from the SAME pinned CDN used above. On first
 * social sign-in we upsert guests/{uid} with setDoc(merge:true) so the guest
 * profile exists for downstream portal reads. Firebase error codes are
 * preserved on throw (we never wrap/swallow them). */

async function upsertGuestProfile(user) {
  try {
    const db = await window.getFirebaseDb();
    const { doc, setDoc, serverTimestamp } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');
    const displayName = user.displayName || (user.email || '').split('@')[0] || 'Guest';
    await setDoc(doc(db, 'guests', user.uid), {
      uid: user.uid,
      email: user.email || '',
      name: displayName,
      verified: false,
      createdAt: serverTimestamp(),
      avatar: user.photoURL || `https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(displayName)}`,
    }, { merge: true });
  } catch (e) {
    // Profile upsert is best-effort; a transient Firestore error must not block
    // a successful auth. The session still carries the identity.
    console.error('Guest profile upsert failed:', e.message);
  }
}

async function signInWithProvider(makeProvider) {
  const auth = await window.getFirebaseAuth();
  const authMod = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-auth.js');
  const provider = makeProvider(authMod);
  try {
    const result = await authMod.signInWithPopup(auth, provider);
    await upsertGuestProfile(result.user);
    return result.user;
  } catch (error) {
    console.error('Social sign-in error:', error.code || error.message);
    throw error; // preserve Firebase error code
  }
}

async function signInWithGoogle() {
  return signInWithProvider((m) => new m.GoogleAuthProvider());
}

async function signInWithFacebook() {
  return signInWithProvider((m) => new m.FacebookAuthProvider());
}

async function signInWithApple() {
  return signInWithProvider((m) => new m.OAuthProvider('apple.com'));
}

// Begins phone verification. Returns the confirmationResult the caller must
// pass to confirmPhoneCode along with the 6-digit SMS code.
async function startPhoneSignIn(phoneNumber, recaptchaContainerId) {
  const auth = await window.getFirebaseAuth();
  const { RecaptchaVerifier, signInWithPhoneNumber } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-auth.js');
  try {
    const verifier = new RecaptchaVerifier(auth, recaptchaContainerId, { size: 'invisible' });
    const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, verifier);
    return confirmationResult;
  } catch (error) {
    console.error('Phone sign-in error:', error.code || error.message);
    throw error; // preserve Firebase error code
  }
}

async function confirmPhoneCode(confirmationResult, code) {
  try {
    const result = await confirmationResult.confirm(code);
    await upsertGuestProfile(result.user);
    return result.user;
  } catch (error) {
    console.error('Phone code confirm error:', error.code || error.message);
    throw error; // preserve Firebase error code
  }
}

window.signUpGuest = signUpGuest;
window.loginGuest = loginGuest;
window.logoutUser = logoutUser;
window.getCurrentUser = getCurrentUser;
window.onAuthStateChanged = onAuthStateChanged;
window.signInWithGoogle = signInWithGoogle;
window.signInWithFacebook = signInWithFacebook;
window.signInWithApple = signInWithApple;
window.startPhoneSignIn = startPhoneSignIn;
window.confirmPhoneCode = confirmPhoneCode;
