/* ===== tracking-data.jsx — process stages + live progress helpers =====
   Stage distributions are no longer hardcoded: every borehole record in
   the store carries its own `stage`, and all totals derive from the live
   window.BOREHOLE_ITEMS array maintained by store.js. */

/* The 6 stages a borehole passes through, mirroring the investigation workflow. */
const STAGES = [
  { key: "valitood",    name: "Välitööd",        en: "Field work",   short: "Väli",   hex: "#64748b", icon: "drill" },
  { key: "valimaarang", name: "Välimäärang",     en: "Field ID",     short: "Määrang",hex: "#2563eb", icon: "layers" },
  { key: "laboris",     name: "Laboris",         en: "At lab",       short: "Labor",  hex: "#7c3aed", icon: "flask" },
  { key: "tulemused",   name: "Labori tulemused",en: "Lab results",  short: "Tulem.", hex: "#9333ea", icon: "flask" },
  { key: "analuus",     name: "Analüüs",         en: "Analysis",     short: "Analüüs",hex: "#d97706", icon: "activity" },
  { key: "aruanne",     name: "Aruanne",         en: "Report",       short: "Aruanne",hex: "#15803d", icon: "check" },
];
const N_STAGES = STAGES.length;

function liveItems() { return window.BOREHOLE_ITEMS || []; }

/* Stage totals across all projects, or filtered to one project. */
function stageTotals(projectId) {
  const totals = STAGES.map(() => 0);
  liveItems().forEach((b) => {
    if (projectId && projectId !== b.project) return;
    const s = Math.min(Math.max(b.stage || 0, 0), N_STAGES - 1);
    totals[s] += 1;
  });
  return totals;
}
function totalHoles(projectId) { return stageTotals(projectId).reduce((a, b) => a + b, 0); }

/* cumulative: how many holes have REACHED a given stage index (funnel down the process) */
function reachedCount(stageIdx, projectId) {
  const t = stageTotals(projectId);
  let s = 0; for (let i = stageIdx; i < t.length; i++) s += t[i];
  return s;
}

/* Overall progress 0..1 = mean normalised stage index across all holes. */
function overallProgress(projectId) {
  const t = stageTotals(projectId);
  const n = t.reduce((a, b) => a + b, 0);
  if (!n) return 0;
  const weighted = t.reduce((acc, c, i) => acc + c * i, 0);
  return weighted / ((N_STAGES - 1) * n);
}

/* Stable pseudo-random 0..1 from a string (legacy helper, still used for jitter). */
function hash01(str, salt) {
  let h = 2166136261 ^ (salt || 0);
  for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619); }
  return ((h >>> 0) % 10000) / 10000;
}

Object.assign(window, {
  STAGES, N_STAGES,
  stageTotals, totalHoles, reachedCount, overallProgress, hash01,
});
