// firebase-auth.jsx
// Initialize Firebase and expose auth functions globally

const firebaseConfig = {
  apiKey: "AIzaSyAMhw9M07wGzHFEMow6hRLhlO4rIcEPIaI",
  authDomain: "gydauth.firebaseapp.com",
  projectId: "gydauth",
  storageBucket: "gydauth.firebasestorage.app",
  messagingSenderId: "769583310469",
  appId: "1:769583310469:web:93b52845cd2487adc9ebec",
  measurementId: "G-0B4R2BV7RR"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const db = firebase.firestore();

const syncToBackend = async (uid, email, name, savedIds) => {
  try {
    const payload = { uid };
    if (email) payload.email = email;
    if (name) payload.name = name;
    if (savedIds) payload.savedIds = Array.from(savedIds);
    payload.lastLogin = new Date().toISOString();

    let backendUrl = "/api/admin/users";
    if (typeof window !== "undefined") {
      const port = window.location.port;
      if (window.location.protocol === "file:" || (port && port !== "3001" && port !== "3000")) {
        backendUrl = "http://localhost:3001/api/admin/users";
      }
    }

    await fetch(backendUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(payload)
    });
  } catch (err) {
    console.error("Failed to sync candidate to backend MongoDB:", err);
  }
};

/**
 * Sign up a new user with email and password
 */
const signUp = async (email, password, displayName) => {
  try {
    const userCredential = await auth.createUserWithEmailAndPassword(email, password);
    const user = userCredential.user;
    if (displayName) {
      await user.updateProfile({ displayName });
    }
    // Save profile to Firestore (EXCLUDING PASSWORD for security)
    await db.collection("users").doc(user.uid).set({
      email: user.email,
      name: displayName || user.email.split("@")[0],
      createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      lastLogin: firebase.firestore.FieldValue.serverTimestamp()
    }, { merge: true });
    
    // Sync to MongoDB in background
    syncToBackend(user.uid, user.email, displayName || user.email.split("@")[0]);
    
    // Send verification email
    await user.sendEmailVerification();

    // Sign out immediately so they aren't "logged in" until verified
    await auth.signOut();
    
    return { user: null, error: null, success: true };
  } catch (error) {
    console.error("Sign Up Error:", error.code, error.message);
    if (error.code === "auth/email-already-in-use") {
      try {
        // Try to sign in to check verification status
        const userCredential = await auth.signInWithEmailAndPassword(email, password);
        const user = userCredential.user;
        
        if (!user.emailVerified) {
          await user.sendEmailVerification();
          await auth.signOut();
          return { user: null, error: null, success: true }; // Act like fresh signup
        } else {
          await auth.signOut();
          return { user: null, error: "This email is already registered" };
        }
      } catch (signInErr) {
        // If password is wrong or other error, just say already registered
        return { user: null, error: "This email is already registered" };
      }
    }
    if (error.code === "auth/weak-password") {
      return { user: null, error: "Password should be at least 6 characters" };
    }
    return { user: null, error: error.message };
  }
};



/**
 * Sign in an existing user
 */
const signIn = async (email, password) => {
  try {
    const userCredential = await auth.signInWithEmailAndPassword(email, password);
    const user = userCredential.user;
    
    // Check if email is verified
    if (!user.emailVerified) {
      // Allow user to sign in but maybe restricted? 
      // User request says "able to login" after verification.
      // So we should probably sign them out if not verified or return a specific error.
      await auth.signOut();
      return { user: null, error: "VERIFY_EMAIL" };
    }

    // Update last login
    await db.collection("users").doc(user.uid).update({
      lastLogin: firebase.firestore.FieldValue.serverTimestamp()
    });
    
    // Sync to MongoDB in background
    syncToBackend(user.uid, user.email, user.displayName || user.email.split("@")[0]);
    
    return { user, error: null };
  } catch (error) {
    console.error("Sign In Error:", error.code, error.message);
    if (error.code === "auth/user-not-found" || error.code === "auth/wrong-password" || error.code === "auth/invalid-credential") {
      return { user: null, error: "Invalid email or password" };
    }
    return { user: null, error: error.message };
  }
};

/**
 * Send email verification
 */
const sendVerificationEmail = async () => {
  const user = auth.currentUser;
  if (user) {
    await user.sendEmailVerification();
    return { error: null };
  }
  return { error: "No user logged in" };
};

/**
 * Check if an email is already registered in Firestore
 */
const isEmailRegistered = async (email) => {
  try {
    const snapshot = await db.collection("users").where("email", "==", email).limit(1).get();
    return !snapshot.empty;
  } catch (error) {
    console.error("Check Email Error:", error);
    return false;
  }
};

/**
 * Send password reset email only if registered
 */
const sendPasswordReset = async (email) => {
  try {
    // Check if user exists first
    const exists = await isEmailRegistered(email);
    if (!exists) {
      return { error: "This email is not registered with us." };
    }

    await auth.sendPasswordResetEmail(email);
    return { error: null };
  } catch (error) {
    console.error("Reset Error:", error.message);
    return { error: error.message };
  }
};



/**
 * Sign out the current user
 */
const signOutUser = async () => {
  try {
    await auth.signOut();
    return { error: null };
  } catch (error) {
    console.error("Sign Out Error:", error.message);
    return { error: error.message };
  }
};

/**
 * Sign in with Google provider
 */
const signInWithGoogle = async () => {
  try {
    const provider = new firebase.auth.GoogleAuthProvider();
    const result = await auth.signInWithPopup(provider);
    const user = result.user;
    
    // Save/Update Google profile in Firestore
    await db.collection("users").doc(user.uid).set({
      email: user.email,
      name: user.displayName,
      photoURL: user.photoURL,
      lastLogin: firebase.firestore.FieldValue.serverTimestamp()
    }, { merge: true });
    
    // Sync to MongoDB in background
    syncToBackend(user.uid, user.email, user.displayName);
    
    return { user: result.user, error: null };
  } catch (error) {
    console.error("Google Sign In Error:", error.code, error.message);
    return { user: null, error: error.message };
  }
};

/**
 * Sync saved job IDs to Firestore
 */
const syncSavedJobs = async (userId, savedIds) => {
  try {
    await db.collection("users").doc(userId).set({
      savedIds: Array.from(savedIds),
      updatedAt: firebase.firestore.FieldValue.serverTimestamp()
    }, { merge: true });

    // Sync to MongoDB in background
    syncToBackend(userId, null, null, savedIds);
  } catch (error) {
    console.error("Firestore Sync Error:", error);
  }
};

/**
 * Fetch saved job IDs from Firestore
 */
const getSavedJobs = async (userId) => {
  try {
    const doc = await db.collection("users").doc(userId).get();
    if (doc.exists) {
      return doc.data().savedIds || [];
    }
    return [];
  } catch (error) {
    console.error("Firestore Fetch Error:", error);
    return [];
  }
};

/**
 * Listen for auth state changes
 */
const onAuthChange = (callback) => {
  return auth.onAuthStateChanged((user) => {
    if (user) {
      // Sync candidate profile to MongoDB in background
      syncToBackend(user.uid, user.email, user.displayName || user.email.split("@")[0]);
      
      callback({
        uid: user.uid,
        email: user.email,
        name: user.displayName || user.email.split("@")[0],
        photoURL: user.photoURL,
        emailVerified: user.emailVerified
      });
    } else {
      callback(null);
    }
  });
};

// Expose to global window object
Object.assign(window, { auth, db, signUp, signIn, signInWithGoogle, signOutUser, onAuthChange, syncSavedJobs, getSavedJobs, sendVerificationEmail, sendPasswordReset });

