// Firebase initialization for Precision Cabinets LLC
// Uses compat SDK loaded via CDN in index.html

const firebaseConfig = {
  apiKey: "AIzaSyCirHKSvnpvWd9Kx4Ox2ceG4AfM0sgAt54",
  authDomain: "precision-cabinets-llc.firebaseapp.com",
  projectId: "precision-cabinets-llc",
  storageBucket: "precision-cabinets-llc.firebasestorage.app",
  messagingSenderId: "883508520152",
  appId: "1:883508520152:web:bcd58ba64177fa510223ad",
};

// Initialize Firebase
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

const db = firebase.firestore();
const auth = firebase.auth();
const storage = firebase.storage();

// Enable Firestore persistence for offline support
db.enablePersistence({ synchronizeTabs: true }).catch((err) => {
  if (err.code === 'failed-precondition') {
    console.warn('Firestore persistence unavailable: multiple tabs open');
  } else if (err.code === 'unimplemented') {
    console.warn('Firestore persistence not supported in this browser');
  }
});

// Helper: get current user's custom claims
async function getUserClaims() {
  const user = auth.currentUser;
  if (!user) return null;
  const token = await user.getIdTokenResult();
  return token.claims;
}

// Helper: check if user is a vendor
async function isVendorUser() {
  const claims = await getUserClaims();
  return claims && claims.role === 'vendor';
}

// Helper: check if user is an employee/admin
async function isEmployeeUser() {
  const claims = await getUserClaims();
  return claims && (claims.role === 'employee' || claims.role === 'admin');
}

// Helper: get the vendor ID from claims
async function getVendorId() {
  const claims = await getUserClaims();
  return claims ? claims.vendorId || null : null;
}

// Helper: call a Cloud Function
async function callFunction(name, data) {
  const fn = firebase.app().functions('us-central1');
  const callable = fn.httpsCallable(name);
  const result = await callable(data);
  return result.data;
}

// Helper: upload a file to Storage and return the download URL
async function uploadFile(path, file, onProgress) {
  const ref = storage.ref(path);
  const task = ref.put(file);

  return new Promise((resolve, reject) => {
    task.on('state_changed',
      (snap) => {
        if (onProgress) {
          onProgress(Math.round((snap.bytesTransferred / snap.totalBytes) * 100));
        }
      },
      reject,
      async () => {
        const url = await task.snapshot.ref.getDownloadURL();
        resolve(url);
      }
    );
  });
}

// Generate a draft ID for photo uploads before order submission
function generateDraftId() {
  return 'draft_' + Date.now() + '_' + Math.random().toString(36).slice(2, 9);
}

Object.assign(window, {
  db, auth, storage,
  getUserClaims, isVendorUser, isEmployeeUser, getVendorId,
  callFunction, uploadFile, generateDraftId,
});
