// Live status from Duck Monitor at status.thekaufmanhouse.com.
// One fetch per page, shared by both designs. Maps monitor names →
// service names, returns { [serviceName]: 'up'|'down'|'loading'|'unknown' }.
// Also exposes useOverallUptime() computed from recent heartbeats.

const STATUS_ENDPOINT = 'https://status.thekaufmanhouse.com/api/v1/status-pages/slug/kaufmanhouse/monitors';

// Monitor names as they appear in Duck Monitor → our service tile names.
// Anything not listed here stays 'unknown' (rendered as —).
const MONITOR_TO_SERVICE = {
  'Cloud': 'Cloud',
  'MailToyou': 'Email',
  'Vault': 'Vault',
  'Paper': 'Paper',
  'Photos': 'Photos',
  'Change': 'Change',
};

let _cache = null;
let _cachePromise = null;

function fetchStatus() {
  if (_cachePromise) return _cachePromise;
  _cachePromise = fetch(STATUS_ENDPOINT, { cache: 'no-store' })
    .then((r) => r.ok ? r.json() : Promise.reject(new Error('status ' + r.status)))
    .then((j) => {
      _cache = j && j.data ? j.data : [];
      return _cache;
    })
    .catch(() => { _cache = []; return _cache; });
  return _cachePromise;
}

function useLiveStatus() {
  const [monitors, setMonitors] = React.useState(_cache);
  React.useEffect(() => {
    let off = false;
    fetchStatus().then((d) => { if (!off) setMonitors(d); });
    const t = setInterval(() => {
      _cachePromise = null;
      fetchStatus().then((d) => { if (!off) setMonitors(d); });
    }, 60000);
    return () => { off = true; clearInterval(t); };
  }, []);

  const out = {};
  for (const s of window.SERVICES) out[s.name] = monitors == null ? 'loading' : 'unknown';
  if (monitors) {
    for (const m of monitors) {
      const svc = MONITOR_TO_SERVICE[m.name];
      if (!svc) continue;
      const hb = m.heartbeats && m.heartbeats.length ? m.heartbeats[m.heartbeats.length - 1] : null;
      // Duck Monitor: status 1 = up, 0 = down. Inactive monitors stay unknown.
      if (!m.active) { out[svc] = 'unknown'; continue; }
      out[svc] = hb && hb.status === 1 ? 'up' : hb ? 'down' : 'unknown';
    }
  }
  return out;
}

function useOverallUptime() {
  const [monitors, setMonitors] = React.useState(_cache);
  React.useEffect(() => {
    let off = false;
    fetchStatus().then((d) => { if (!off) setMonitors(d); });
  }, []);
  if (!monitors || !monitors.length) return null;
  let total = 0, up = 0;
  for (const m of monitors) {
    if (!m.active || !m.heartbeats) continue;
    for (const hb of m.heartbeats) {
      total++;
      if (hb.status === 1) up++;
    }
  }
  if (!total) return null;
  return (up / total) * 100;
}

window.useLiveStatus = useLiveStatus;
window.useOverallUptime = useOverallUptime;
