/* ProHippo — Firestore data layer
 *
 * One live store per signed-in user. Each collection is kept in sync with
 * Firestore via onSnapshot, so any add/edit/delete shows up instantly across
 * the whole app. Feature modules read data with the useCollection() hook and
 * never touch Firestore directly.
 *
 * Firestore layout:  users/{uid}/{collection}/{docId}
 */
(function () {
  const COLLECTIONS = ["assessees", "hearings", "notices", "invoices", "matters"];

  const cache = {};
  const subs  = {};
  COLLECTIONS.forEach(c => { cache[c] = []; subs[c] = new Set(); });

  let uid = null;
  let fsUnsubs = [];
  let started = false;

  const db = () => firebase.firestore();
  const colRef = (c) => db().collection("users").doc(uid).collection(c);
  const strip = (o) => { const x = { ...o }; delete x.id; return x; };

  function emit(c) { subs[c].forEach(fn => fn(cache[c])); }

  function start(userId) {
    if (started && uid === userId) return;
    stop();
    uid = userId;
    started = true;
    COLLECTIONS.forEach(c => {
      try {
        const unsub = colRef(c).onSnapshot(
          snap => { cache[c] = snap.docs.map(d => ({ id: d.id, ...d.data() })); emit(c); },
          err  => { console.error("DataStore snapshot error [" + c + "]:", err); }
        );
        fsUnsubs.push(unsub);
      } catch (e) {
        console.error("DataStore start error [" + c + "]:", e);
      }
    });
  }

  function stop() {
    fsUnsubs.forEach(u => { try { u(); } catch (e) {} });
    fsUnsubs = [];
    COLLECTIONS.forEach(c => { cache[c] = []; emit(c); });
    started = false;
    uid = null;
  }

  function subscribe(c, fn) { subs[c].add(fn); return () => subs[c].delete(fn); }
  function get(c) { return cache[c] || []; }

  function add(c, data) {
    return colRef(c).add({ ...strip(data), createdAt: new Date().toISOString() });
  }
  function update(c, id, data) {
    return colRef(c).doc(id).update(strip(data));
  }
  function remove(c, id) {
    return colRef(c).doc(id).delete();
  }

  /* Write the bundled sample data — only into collections that are empty. */
  async function seedDemo() {
    const D = window.DEMO || {};
    for (const c of COLLECTIONS) {
      if (cache[c].length) continue;
      const arr = D[c] || [];
      if (!arr.length) continue;
      const batch = db().batch();
      arr.forEach(rec => batch.set(colRef(c).doc(), { ...strip(rec), createdAt: new Date().toISOString() }));
      await batch.commit();
    }
  }

  /* Delete every record across all collections for this user. */
  async function clearAll() {
    for (const c of COLLECTIONS) {
      const snap = await colRef(c).get();
      if (snap.empty) continue;
      const batch = db().batch();
      snap.docs.forEach(d => batch.delete(d.ref));
      await batch.commit();
    }
  }

  window.DataStore = { start, stop, subscribe, get, add, update, remove, seedDemo, clearAll, COLLECTIONS };

  /* React hook — live array for a collection, re-renders on any change. */
  window.useCollection = function (c) {
    const [items, setItems] = React.useState(() => window.DataStore.get(c));
    React.useEffect(() => window.DataStore.subscribe(c, setItems), [c]);
    return items;
  };
})();
