// ── React globals (available to all files loaded after this) ─
const { useState, useEffect, useCallback, useMemo, useRef } = React;

// ── Constants ────────────────────────────────────────────────
const LS_AUTH_EMAIL = 'intime_auth_email';

// ── Firebase core ────────────────────────────────────────────
let fbApp = null, fbDb = null, fbCache = {}, fbInitPromise = null;
const getFB = async n => {
  if (fbCache[n]) return fbCache[n];
  fbCache[n] = await import(`https://www.gstatic.com/firebasejs/10.12.0/firebase-${n}.js`);
  return fbCache[n];
};

async function initFirebase() {
  if (fbInitPromise) return fbInitPromise;
  const cfg = window.__FIREBASE_CONFIG__;
  if (!cfg || cfg.apiKey === 'PASTE_YOUR_API_KEY') return false;
  fbInitPromise = (async () => {
    try {
      const { initializeApp } = await getFB('app');
      const { getDatabase }   = await getFB('database');
      fbApp = initializeApp(cfg);
      fbDb  = getDatabase(fbApp);
      return true;
    } catch (e) { console.warn('Firebase init failed', e); fbInitPromise = null; return false; }
  })();
  return fbInitPromise;
}

async function fbWrite(hid, data) {
  if (!fbDb) return;
  try { const { ref, update } = await getFB('database'); await update(ref(fbDb, `households/${hid}`), data); }
  catch (e) { console.warn(e); }
}

async function fbListen(hid, cb) {
  if (!fbDb) return () => {};
  try {
    const { ref, onValue, off } = await getFB('database');
    const r = ref(fbDb, `households/${hid}`);
    onValue(r, s => { const v = s.val(); if (v) cb(v); });
    return () => off(r);
  } catch { return () => {}; }
}

async function fbDelete(hid) {
  if (!fbDb) return;
  try { const { ref, remove } = await getFB('database'); await remove(ref(fbDb, `households/${hid}`)); }
  catch (e) { console.warn(e); }
}

// ── Firebase Auth ─────────────────────────────────────────────
let fbAuthInstance = null;

async function initAuth() {
  if (fbAuthInstance) return fbAuthInstance;
  const ok = await initFirebase();
  if (!ok) return null;
  try {
    const { getAuth } = await getFB('auth');
    fbAuthInstance = getAuth(fbApp);
    return fbAuthInstance;
  } catch(e) { console.warn('Auth init failed', e); return null; }
}

async function sendMagicLink(email) {
  const auth = await initAuth();
  if (!auth) throw new Error('Firebase Auth not available. Check your Firebase config.');
  const { sendSignInLinkToEmail } = await getFB('auth');
  await sendSignInLinkToEmail(auth, email, {
    url: window.location.origin + window.location.pathname,
    handleCodeInApp: true,
  });
  try { localStorage.setItem(LS_AUTH_EMAIL, email); } catch {}
}

async function completeMagicLink() {
  const auth = await initAuth();
  if (!auth) return null;
  const { isSignInWithEmailLink, signInWithEmailLink } = await getFB('auth');
  if (!isSignInWithEmailLink(auth, window.location.href)) return null;
  let email;
  try { email = localStorage.getItem(LS_AUTH_EMAIL); } catch {}
  if (!email) email = window.prompt('Please confirm your email to finish signing in:');
  if (!email) return null;
  try {
    const result = await signInWithEmailLink(auth, email, window.location.href);
    try { localStorage.removeItem(LS_AUTH_EMAIL); } catch {}
    window.history.replaceState({}, document.title, window.location.pathname);
    return result.user;
  } catch(e) { console.warn('Magic link completion failed', e); return null; }
}

async function signInCustomToken(token) {
  const auth = await initAuth();
  if (!auth) throw new Error('Firebase Auth not available');
  const { signInWithCustomToken } = await getFB('auth');
  const result = await signInWithCustomToken(auth, token);
  return result.user;
}

async function signOutUser() {
  const auth = await initAuth();
  if (!auth) return;
  const { signOut } = await getFB('auth');
  await signOut(auth);
}

const VAPID_KEY = 'BNWlUDUw2W4XgUA15JqTcp0OQEcQVjboEp4HgdudLtZ9uilcq5ToAkYi7RIPH0qxAmujMOpj7yWBnZThLyBmxS0';

async function initPush(householdId, uid) {
  if (!('Notification' in window) || !('serviceWorker' in navigator) || !fbApp) return null;
  try {
    const reg        = await navigator.serviceWorker.register('/sw.js');
    const permission = await Notification.requestPermission();
    if (permission !== 'granted') return null;
    const { getMessaging, getToken } = await getFB('messaging');
    const messaging  = getMessaging(fbApp);
    const token      = await getToken(messaging, { vapidKey: VAPID_KEY, serviceWorkerRegistration: reg });
    if (token) await fbWritePushToken(householdId, uid, token);
    return token;
  } catch(e) {
    console.warn('Push setup failed:', e);
    return null;
  }
}

async function fbWritePushToken(householdId, uid, token) {
  if (!fbDb) return;
  const { ref, update } = await getFB('database');
  await update(ref(fbDb, `households/${householdId}/members/${uid}`), { pushToken: token });
}

// ── Firebase data helpers ─────────────────────────────────────
async function fbWriteMember(hid, uid, data) {
  if (!fbDb) return;
  try {
    const { ref, set } = await getFB('database');
    await set(ref(fbDb, `households/${hid}/members/${uid}`), data);
  } catch(e) { console.warn(e); }
}

async function fbWriteWheel(hid, data) {
  if (!fbDb) return;
  try {
    const { ref, set } = await getFB('database');
    await set(ref(fbDb, `households/${hid}/wheel`), data);
  } catch(e) { console.warn(e); }
}

async function fbListenWheel(hid, cb) {
  if (!fbDb) return () => {};
  try {
    const { ref, onValue, off } = await getFB('database');
    const r = ref(fbDb, `households/${hid}/wheel`);
    onValue(r, s => cb(s.val()));
    return () => off(r);
  } catch { return () => {}; }
}

async function fbWriteIOU(hid, id, data) {
  if (!fbDb) return;
  try {
    const { ref, set } = await getFB('database');
    await set(ref(fbDb, `households/${hid}/ious/${id}`), data);
  } catch(e) { console.warn(e); }
}

async function fbRedeemIOU(hid, id, redeemedAt) {
  if (!fbDb) return;
  try {
    const { ref, update } = await getFB('database');
    await update(ref(fbDb, `households/${hid}/ious/${id}`), { redeemedAt });
  } catch(e) { console.warn(e); }
}

async function fbListenIOUs(hid, cb) {
  if (!fbDb) return () => {};
  try {
    const { ref, onValue, off } = await getFB('database');
    const r = ref(fbDb, `households/${hid}/ious`);
    onValue(r, s => cb(s.val()));
    return () => off(r);
  } catch { return () => {}; }
}

const firebaseConfigured = () => {
  const c = window.__FIREBASE_CONFIG__;
  return !!(c && c.apiKey && c.apiKey !== 'PASTE_YOUR_API_KEY');
};
