'use client';

import { initializeApp, FirebaseApp, getApp } from 'firebase/app';
import { getAuth, Auth, connectAuthEmulator } from 'firebase/auth';
import { getFirestore, Firestore, connectFirestoreEmulator } from 'firebase/firestore';
import { getStorage } from 'firebase/storage';
import { validateEnvironment, isProduction } from './env';

// Production configuration with proper fallbacks
const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY || "AIzaSyBeTIpPVjU3M0300L1ZOBc3-Se-9xBJm8o",
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN || "wolna-glowa.firebaseapp.com",
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID || "wolna-glowa",
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET || "wolna-glowa.firebasestorage.app",
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID || "413197196957",
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID || "1:413197196957:web:19290e91a2c83075073e74"
};

// Validate Firebase configuration
const validateFirebaseConfig = (config: any) => {
  const requiredFields = ['apiKey', 'authDomain', 'projectId', 'storageBucket', 'messagingSenderId', 'appId'];
  
  for (const field of requiredFields) {
    if (!config[field]) {
      throw new Error(`Missing required Firebase configuration: ${field}`);
    }
  }
  
  return true;
};

// Initialize Firebase
let app: FirebaseApp;

try {
  // Validate configuration
  validateFirebaseConfig(firebaseConfig);
  
  // Initialize Firebase app
  app = getApp();
} catch (error: any) {
  // If no app exists, create one
  if (error.code === 'app/no-app') {
    app = initializeApp(firebaseConfig);
  } else {
    console.error('Firebase initialization error:', error);
    throw error;
  }
}

// Initialize Firebase services
export const auth = getAuth(app);

// Initialize Firestore
// Note: Firestore may attempt WebSocket connections which can cause CORS warnings
// These warnings are harmless and don't affect functionality
// Firestore will automatically fall back to HTTP long polling if WebSocket fails
export const db = getFirestore(app);

export const storage = getStorage(app);

export default app; 