// ============ Firebase client bootstrap + auth helpers ============
let fbInitPromise = null;
function initFirebase() {
  if (fbInitPromise) return fbInitPromise;
  fbInitPromise = (async () => {
    const r = await fetch("/api/firebase-config");
    if (!r.ok) throw new Error("Failed to load Firebase config");
    const cfg = await r.json();
    if (!cfg.apiKey) throw new Error("Firebase API key not configured on server");
    if (!firebase.apps.length) firebase.initializeApp(cfg);
    return cfg;
  })();
  return fbInitPromise;
}

// Reactive auth state. Returns {ready, user, claims, error}.
function useFirebaseAuth() {
  const [state, setState] = React.useState({ ready: false, user: null, claims: null, error: null });
  React.useEffect(() => {
    let unsub;
    initFirebase()
      .then(() => {
        unsub = firebase.auth().onAuthStateChanged(async (u) => {
          if (!u) { setState({ ready: true, user: null, claims: null, error: null }); return; }
          try {
            const tokenRes = await u.getIdTokenResult(true); // force refresh to pick up claim updates
            setState({
              ready: true,
              user: { uid: u.uid, email: u.email, name: u.displayName || u.email },
              claims: tokenRes.claims,
              error: null,
            });
          } catch (e) {
            setState({ ready: true, user: null, claims: null, error: e.message });
          }
        });
      })
      .catch(err => setState({ ready: true, user: null, claims: null, error: err.message }));
    return () => { if (unsub) unsub(); };
  }, []);
  return state;
}

async function getIdToken() {
  const u = firebase.auth().currentUser;
  if (!u) throw new Error("not signed in");
  return await u.getIdToken();
}

// authed JSON fetch helper (throws on non-2xx, returns parsed body)
async function apiAuth(url, { method = "GET", json } = {}) {
  const token = await getIdToken();
  const headers = { "Authorization": `Bearer ${token}` };
  let body;
  if (json) { headers["Content-Type"] = "application/json"; body = JSON.stringify(json); }
  const r = await fetch(url, { method, headers, body });
  if (!r.ok) {
    let msg = `HTTP ${r.status}`;
    try { const j = await r.json(); if (j.error) msg = j.error; } catch {}
    throw new Error(msg);
  }
  if (r.status === 204) return null;
  return r.json();
}

// Same rule as the server: presence of `readOnly` (legacy admin parity) or role=Viewer.
function isReadOnly(claims) {
  return Object.prototype.hasOwnProperty.call(claims || {}, "readOnly") || claims?.role === "Viewer";
}

async function fbSignIn(email, password) {
  await initFirebase();
  return firebase.auth().signInWithEmailAndPassword(email, password);
}
async function fbSignOut() {
  if (!firebase.apps.length) return;
  return firebase.auth().signOut();
}

Object.assign(window, { initFirebase, useFirebaseAuth, getIdToken, apiAuth, isReadOnly, fbSignIn, fbSignOut });
