// Live data store — starts EMPTY. The household populates assets, routines,
// contacts, and to-dos themselves; new records are created via window.Hub.
// Categories below are a generic starting taxonomy for the Add-Asset form.

const CATEGORIES = ['HVAC', 'Water Features', 'Plumbing', 'Electrical', 'Appliances', 'Exterior'];

const ASSETS = [];
const ROUTINES = [];
const CONTACTS = [];
const TODOS = [];

// Backfill defensive defaults after a localStorage hydrate.
function normalizeRecords() {
  ROUTINES.forEach(r => {
    if (r.synced === undefined) r.synced = false;
    if (!Array.isArray(r.completions)) r.completions = [];
    if (r.reminder === undefined) r.reminder = null;
    delete r.assignee; // legacy field — single-user app
  });
  TODOS.forEach(td => {
    delete td.assignee;
  });
}

// helpers
const findAsset    = id => ASSETS.find(a => a.id === id);
const findContact  = id => CONTACTS.find(c => c.id === id);
const findRoutine  = id => ROUTINES.find(r => r.id === id);

const routinesByAsset   = id => ROUTINES.filter(r => r.asset === id);
const todosByAsset      = id => TODOS.filter(t => t.asset === id);
const contactsByAsset   = id => {
  const ids = new Set(routinesByAsset(id).map(r => r.contact).filter(Boolean));
  CONTACTS.forEach(c => { if ((c.assets || []).includes(id)) ids.add(c.id); });
  return [...ids].map(findContact).filter(Boolean);
};
const assetsByContact   = id => {
  const ids = new Set(ROUTINES.filter(r => r.contact === id).map(r => r.asset));
  const c = findContact(id);
  (c && c.assets || []).forEach(aid => ids.add(aid));
  return [...ids].map(findAsset).filter(Boolean);
};
const routinesByContact = id => ROUTINES.filter(r => r.contact === id);

// A routine counts as "unscheduled" (not on the calendar) when it has no concrete next date.
const isUnscheduled = r => !r || !r.nextLabel || ['Not scheduled', 'Unscheduled', 'TBD', '—', ''].includes(r.nextLabel);

Object.assign(window, {
  CATEGORIES, ASSETS, ROUTINES, CONTACTS, TODOS,
  findAsset, findContact, findRoutine,
  routinesByAsset, todosByAsset, contactsByAsset,
  assetsByContact, routinesByContact,
  normalizeRecords, isUnscheduled,
});
