/* global firebase */

// ===========================================================
// Firebase Configuration for Area 7
// ===========================================================

// IMPORTANTE: Reemplazá estos valores con los de tu proyecto Firebase
// Los encontrás en: Firebase Console → Project Settings → General → Your apps → Web app
const firebaseConfig = {
  apiKey: "AIzaSyB4rkdSFXLl29vsEFEz9X8GkorupwabPKw",
  authDomain: "area7-66ade.firebaseapp.com",
  projectId: "area7-66ade",
  storageBucket: "area7-66ade.firebasestorage.app",
  messagingSenderId: "429415682662",
  appId: "1:429415682662:web:7031b065d970dcdf9d93a7"
};

// Initialize Firebase
let db = null;
let firebaseInitialized = false;

function initFirebase() {
  if (firebaseInitialized) return db;
  
  if (typeof firebase === 'undefined') {
    console.error('Firebase SDK not loaded');
    return null;
  }
  
  // Check if already initialized
  if (!firebase.apps || firebase.apps.length === 0) {
    firebase.initializeApp(firebaseConfig);
  }
  
  db = firebase.firestore();
  firebaseInitialized = true;
  console.log('Firebase initialized');
  return db;
}

// Booking functions
async function saveBooking(bookingData) {
  const database = initFirebase();
  if (!database) {
    console.error('Firebase not available, booking saved locally only');
    return { success: false, localOnly: true };
  }
  
  try {
    const bookingRef = await database.collection('bookings').add({
      ...bookingData,
      createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      status: 'confirmed'
    });
    
    return { success: true, id: bookingRef.id };
  } catch (error) {
    console.error('Error saving booking:', error);
    return { success: false, error: error.message };
  }
}

async function getBookings(courtId, date) {
  const database = initFirebase();
  if (!database) return [];
  
  try {
    const snapshot = await database
      .collection('bookings')
      .where('courtId', '==', courtId)
      .where('date', '==', date)
      .where('status', '==', 'confirmed')
      .get();
    
    const bookings = [];
    snapshot.forEach(doc => {
      bookings.push({ id: doc.id, ...doc.data() });
    });
    
    return bookings;
  } catch (error) {
    console.error('Error fetching bookings:', error);
    return [];
  }
}

async function getAllBookingsForDate(date) {
  const database = initFirebase();
  if (!database) return {};
  
  try {
    const snapshot = await database
      .collection('bookings')
      .where('date', '==', date)
      .where('status', '==', 'confirmed')
      .get();
    
    const bookings = {};
    snapshot.forEach(doc => {
      const data = doc.data();
      const key = `${data.courtId}|${data.date}|${data.hour}`;
      bookings[key] = 'reservado';
    });
    
    return bookings;
  } catch (error) {
    console.error('Error fetching bookings:', error);
    return {};
  }
}

// Check if a slot is available
async function checkAvailability(courtId, date, hour) {
  const database = initFirebase();
  if (!database) return true; // Assume available if Firebase not loaded
  
  try {
    const snapshot = await database
      .collection('bookings')
      .where('courtId', '==', courtId)
      .where('date', '==', date)
      .where('hour', '==', hour)
      .where('status', '==', 'confirmed')
      .get();
    
    return snapshot.empty;
  } catch (error) {
    console.error('Error checking availability:', error);
    return true; // Assume available on error
  }
}
