import {
  GoogleAuthProvider,
  FacebookAuthProvider,
  TwitterAuthProvider,
  signInWithPopup,
  signOut,
  onAuthStateChanged,
} from 'firebase/auth';
import { auth } from './firebase.js';

const googleProvider = new GoogleAuthProvider();
const facebookProvider = new FacebookAuthProvider();
const twitterProvider = new TwitterAuthProvider();

let currentUser = null;
const authListeners = [];

export function onAuthChange(callback) {
  authListeners.push(callback);
  // Call immediately with current state
  callback(currentUser);
}

function notifyListeners() {
  authListeners.forEach((cb) => cb(currentUser));
}

export function getCurrentUser() {
  return currentUser;
}

export async function loginWithGoogle() {
  try {
    const result = await signInWithPopup(auth, googleProvider);
    return result.user;
  } catch (error) {
    handleAuthError(error);
    return null;
  }
}

export async function loginWithFacebook() {
  try {
    const result = await signInWithPopup(auth, facebookProvider);
    return result.user;
  } catch (error) {
    handleAuthError(error);
    return null;
  }
}

export async function loginWithTwitter() {
  try {
    const result = await signInWithPopup(auth, twitterProvider);
    return result.user;
  } catch (error) {
    handleAuthError(error);
    return null;
  }
}

export async function logout() {
  try {
    await signOut(auth);
  } catch (error) {
    console.error('Sign out error:', error);
  }
}

function handleAuthError(error) {
  if (error.code === 'auth/popup-closed-by-user') return;
  if (error.code === 'auth/cancelled-popup-request') return;

  let message = 'Authentication failed. Please try again.';

  if (error.code === 'auth/account-exists-with-different-credential') {
    message = 'An account already exists with the same email. Try signing in with a different provider.';
  } else if (error.code === 'auth/popup-blocked') {
    message = 'Popup was blocked by your browser. Please allow popups and try again.';
  } else if (error.code === 'auth/unauthorized-domain') {
    message = 'This domain is not authorized for sign-in. Please check Firebase Console settings.';
  }

  showToast(message, 'error');
}

function showToast(message, type = 'info') {
  const existing = document.querySelector('.toast');
  if (existing) existing.remove();

  const toast = document.createElement('div');
  toast.className = `toast ${type}`;
  toast.textContent = message;
  document.body.appendChild(toast);
  setTimeout(() => toast.remove(), 4000);
}

export function initAuth() {
  onAuthStateChanged(auth, (user) => {
    currentUser = user;
    notifyListeners();
  });
}
