window.SKY_TODAY = "2026-04-17";
window.skyAdd = (n, from) => { const t = new Date((from || window.SKY_TODAY) + "T00:00:00Z"); t.setUTCDate(t.getUTCDate() + n); return t.toISOString().slice(0, 10); };
/* SkyOps — realistic seed data. All named sites are fictitious Iberian-style names. */

const SITES = [
  { id: "es-ab-01", name: "Albacete Solar I", region: "Castilla-La Mancha, ES",
    capacity_mw: 142.8, panels: 312400, health: 91, criticals: 2, warnings: 11,
    lastInspection: "2026-04-09", nextInspection: "2026-07-08",
    irradiance: 842, ambient: 21.4, wind: 12, alerts: 3, coverage: 96.2, trend: "up" },
  { id: "es-mu-02", name: "Lorca Photon Field", region: "Murcia, ES",
    capacity_mw: 96.2, panels: 210880, health: 84, criticals: 5, warnings: 19,
    lastInspection: "2026-04-02", nextInspection: "2026-05-14",
    irradiance: 910, ambient: 24.1, wind: 8, alerts: 7, coverage: 98.1, trend: "down" },
  { id: "pt-ev-03", name: "Évora Plana PV", region: "Alentejo, PT",
    capacity_mw: 210.5, panels: 460100, health: 78, criticals: 9, warnings: 34,
    lastInspection: "2026-03-28", nextInspection: "2026-04-21",
    irradiance: 958, ambient: 26.8, wind: 14, alerts: 12, coverage: 92.4, trend: "down" },
  { id: "es-se-04", name: "Sevilla Tracker West", region: "Andalucía, ES",
    capacity_mw: 58.4, panels: 127200, health: 95, criticals: 0, warnings: 4,
    lastInspection: "2026-04-14", nextInspection: "2026-07-14",
    irradiance: 880, ambient: 23.0, wind: 10, alerts: 1, coverage: 99.3, trend: "up" },
  { id: "es-ca-05", name: "Cáceres Hybrid Park", region: "Extremadura, ES",
    capacity_mw: 128.0, panels: 278900, health: 88, criticals: 3, warnings: 14,
    lastInspection: "2026-03-22", nextInspection: "2026-06-21",
    irradiance: 870, ambient: 22.5, wind: 15, alerts: 4, coverage: 97.0, trend: "flat" },
  { id: "pt-al-06", name: "Alcoutim Ridge",  region: "Algarve, PT",
    capacity_mw: 72.1, panels: 157300, health: 90, criticals: 1, warnings: 6,
    lastInspection: "2026-04-11", nextInspection: "2026-07-10",
    irradiance: 915, ambient: 25.2, wind: 9, alerts: 2, coverage: 95.8, trend: "up" },
  { id: "es-zr-07", name: "Zaragoza North",  region: "Aragón, ES",
    capacity_mw: 184.4, panels: 402000, health: 82, criticals: 6, warnings: 22,
    lastInspection: "2026-04-06", nextInspection: "2026-05-30",
    irradiance: 805, ambient: 19.8, wind: 22, alerts: 6, coverage: 94.1, trend: "flat" },
];

/* Review queue detections — for the current open inspection at Évora Plana PV. */
const ANOMALY_CLASS = {
  hot_cell: { label: "Hot cell", group: "MODULE" },
  module_cracking: { label: "Module cracking", group: "MODULE" },
  soiling: { label: "Soiling", group: "MODULE" },
  delamination: { label: "Delamination", group: "MODULE" },
  activated_bypass: { label: "Activated bypass diode", group: "MODULE" },
  pid: { label: "PID", group: "MODULE" },
  warm_module: { label: "Warm module", group: "MODULE" },
  missing_module: { label: "Missing module", group: "MODULE" },
  offline_string: { label: "Offline string", group: "STRING" },
  under_string: { label: "Underperforming string", group: "STRING" },
  reverse_polarity: { label: "Reverse polarity", group: "STRING" },
  inverter_fault: { label: "Inverter/combiner fault", group: "STRING" },
  vegetation: { label: "Vegetation", group: "OBSTRUCTION" },
  shading: { label: "Shading", group: "OBSTRUCTION" },
  physical_obj: { label: "Physical object", group: "OBSTRUCTION" },
  bird_dropping: { label: "Bird dropping", group: "OBSTRUCTION" },
  tilt_fault: { label: "Tilt-tracker fault", group: "MOUNTING" },
  racking: { label: "Racking issue", group: "MOUNTING" },
  ballast: { label: "Ballast issue", group: "MOUNTING" },
};

const rand = (seed => () => (seed = (seed * 9301 + 49297) % 233280) / 233280)(42);

const DETECTIONS = (() => {
  const kinds = Object.keys(ANOMALY_CLASS);
  const sev = ["critical","high","medium","low"];
  const temporal = ["NEW","PERSISTENT","DEGRADED","RESOLVED"];
  const source = ["INSPECTION_SYSTEM","INSPECTION_HUMAN","SENSOR_CONTINUOUS","SATELLITE","FIELD_REPORT"];
  const out = [];
  for (let i = 0; i < 64; i++) {
    const r = rand();
    const k = kinds[Math.floor(rand() * kinds.length)];
    const sidx = r < 0.12 ? 0 : r < 0.35 ? 1 : r < 0.7 ? 2 : 3;
    const tidx = Math.floor(rand() * temporal.length);
    const soff = Math.floor(rand() * source.length);
    const str = `INV-${String(1 + Math.floor(rand()*12)).padStart(2,"0")}.CMB-${String(1+Math.floor(rand()*8)).padStart(2,"0")}.STR-${String(1+Math.floor(rand()*14)).padStart(2,"0")}`;
    const mod = `MOD-${String(1+Math.floor(rand()*2200)).padStart(4,"0")}`;
    const conf = Math.round(55 + rand() * 43);
    const dT = +(2.4 + rand() * 28).toFixed(2);
    out.push({
      id: `OBS-${String(4200+i).padStart(5,"0")}`,
      kind: k, label: ANOMALY_CLASS[k].label, group: ANOMALY_CLASS[k].group,
      severity: sev[sidx],
      temporal: temporal[tidx],
      source: source[soff],
      string: str, module: mod,
      confidence: conf,
      dT,
      area_m2: +(0.15 + rand() * 1.6).toFixed(2),
      lat: +(38.573 + rand()*0.12).toFixed(5),
      lng: +(-7.916 + rand()*0.12).toFixed(5),
      detectedAt: `2026-04-16 ${String(9+Math.floor(rand()*6)).padStart(2,"0")}:${String(Math.floor(rand()*60)).padStart(2,"0")}`,
      review: "pending",
      assignee: null,
    });
  }
  // Ensure variety of kinds & pin a couple of memorable detections up top
  out[0] = { ...out[0], kind: "hot_cell", label: "Hot cell", group: "MODULE", severity: "critical", temporal: "NEW", confidence: 97, dT: 28.44, source: "INSPECTION_SYSTEM" };
  out[1] = { ...out[1], kind: "activated_bypass", label: "Activated bypass diode", group: "MODULE", severity: "high", temporal: "PERSISTENT", confidence: 91, dT: 16.12, source: "INSPECTION_SYSTEM" };
  out[2] = { ...out[2], kind: "tilt_fault", label: "Tilt-tracker fault", group: "MOUNTING", severity: "high", temporal: "DEGRADED", confidence: 88, dT: 9.4, source: "SENSOR_CONTINUOUS" };
  out[3] = { ...out[3], kind: "vegetation", label: "Vegetation", group: "OBSTRUCTION", severity: "medium", temporal: "NEW", confidence: 79, dT: 4.2, source: "SATELLITE" };
  out[4] = { ...out[4], kind: "offline_string", label: "Offline string", group: "STRING", severity: "critical", temporal: "NEW", confidence: 94, dT: 18.9, source: "INSPECTION_SYSTEM" };
  return out;
})();

/* Portfolio alerts */
const ALERTS = [
  { id: "ALT-1042", site: "Évora Plana PV", kind: "String offline > 4h", sev: "critical", when: "12m ago", mic: "MIC-2026-04-033" },
  { id: "ALT-1041", site: "Lorca Photon Field", kind: "Hot cell ΔT > 25°C", sev: "critical", when: "38m ago", mic: "MIC-2026-04-029" },
  { id: "ALT-1040", site: "Zaragoza North", kind: "Tracker stuck — 14 rows", sev: "high", when: "1h ago", mic: "MIC-2026-04-031" },
  { id: "ALT-1039", site: "Albacete Solar I", kind: "Soiling index > threshold", sev: "medium", when: "3h ago", mic: "MIC-2026-04-028" },
  { id: "ALT-1038", site: "Évora Plana PV", kind: "Coverage gap — 7.6% of AOI", sev: "medium", when: "4h ago", mic: "MIC-2026-04-033" },
];

/* Activity */
const ACTIVITY = [
  { t: "09:42", who: "T. Aragón",    what: "Accepted 42 detections", sub: "Évora Plana PV · MIC-2026-04-033", kind: "accept" },
  { t: "09:31", who: "System",       what: "Satellite diff ingested", sub: "Sentinel-2 · cloud cover 4%", kind: "sat" },
  { t: "09:18", who: "M. Rivera",    what: "Reclassified 6 observations", sub: "Soiling → Bird dropping", kind: "class" },
  { t: "08:55", who: "System",       what: "Processing complete", sub: "1,204 detections · 92.4% coverage", kind: "ok" },
  { t: "08:12", who: "System",       what: "Upload complete — 847 GB", sub: "DJI M350 · 14 sorties", kind: "upload" },
  { t: "07:40", who: "L. Ferreira",  what: "Pre-flight passed", sub: "MIC-2026-04-033 v3", kind: "ok" },
];

/* MIC inherited */
const INHERITED = {
  from: "MIC-2026-01-017  (2026-01-14)",
  thresholds: [
    { key: "Hot cell ΔT", last: "20.0 °C", now: "18.0 °C", delta: "−2.0" },
    { key: "String offline", last: "15 min", now: "10 min", delta: "−5" },
    { key: "Soiling index", last: "0.055",   now: "0.050",  delta: "−0.005" },
    { key: "Coverage target", last: "95.0%",  now: "97.0%",  delta: "+2.0" },
  ],
  priorityZones: [
    { name: "Zone A — Inverters 3, 7",   note: "Tracker faults recurring in last 2 cycles" },
    { name: "Zone B — Combiner 4.2",     note: "PID under monitoring since 2025-09" },
    { name: "Zone C — Sector NW",        note: "Vegetation pressure from tree line" },
  ],
  toReverify: 27,
  defectsCarriedOver: 112,
};

window.SITES = SITES;
window.ANOMALY_CLASS = ANOMALY_CLASS;
window.DETECTIONS = DETECTIONS;
window.ALERTS = ALERTS;
window.ACTIVITY = ACTIVITY;
window.INHERITED = INHERITED;

/* ───────────────────────────────────────────────────────────
   INSPECTIONS — one per site per cycle. The spine of the app.
   stages: draft → scheduled → flying → processing → review → reported → closed
   ─────────────────────────────────────────────────────────── */
const INSP_STAGES = ["draft","scheduled","flying","processing","review","reported","closed"];

const INSPECTIONS = [
  // Évora Plana PV — 4 historical cycles
  { id: "MIC-2026-04-033", siteId: "pt-ev-03", cycle: "Q2 2026", status: "processing",
    startedAt: "2026-04-15", plannedFor: "2026-04-15", baseline: "MIC-2026-01-017",
    coverage: 92.4, detections: 58, critical: 2, lead: "T. Aragón", drone: "DJI M350 RTK",
    progress: { draft: 1, scheduled: 1, flying: 1, processing: 0.68, review: 0, reported: 0, closed: 0 },
    flights: 14, images: 8729, bytes: 1_529_600_000_000, gsd: 1.24, area_ha: 412.4 },
  { id: "MIC-2026-01-017", siteId: "pt-ev-03", cycle: "Q1 2026", status: "closed",
    startedAt: "2026-01-14", plannedFor: "2026-01-14", baseline: "MIC-2025-10-008",
    coverage: 98.1, detections: 1198, critical: 8, lead: "T. Aragón", drone: "DJI M350 RTK",
    progress: { draft: 1, scheduled: 1, flying: 1, processing: 1, review: 1, reported: 1, closed: 1 },
    flights: 12, images: 7820, bytes: 1_318_400_000_000, gsd: 1.24, area_ha: 412.4 },
  { id: "MIC-2025-10-008", siteId: "pt-ev-03", cycle: "Q4 2025", status: "closed",
    startedAt: "2025-10-09", plannedFor: "2025-10-09", baseline: "MIC-2025-07-004",
    coverage: 97.4, detections: 1082, critical: 6, lead: "L. Ferreira", drone: "DJI M350 RTK",
    progress: { draft: 1, scheduled: 1, flying: 1, processing: 1, review: 1, reported: 1, closed: 1 },
    flights: 11, images: 7410, bytes: 1_218_400_000_000, gsd: 1.30, area_ha: 412.4 },
  { id: "MIC-2025-07-004", siteId: "pt-ev-03", cycle: "Q3 2025", status: "closed",
    startedAt: "2025-07-12", plannedFor: "2025-07-12", baseline: null,
    coverage: 95.2, detections: 1431, critical: 14, lead: "L. Ferreira", drone: "DJI M300 RTK",
    progress: { draft: 1, scheduled: 1, flying: 1, processing: 1, review: 1, reported: 1, closed: 1 },
    flights: 13, images: 8140, bytes: 1_408_400_000_000, gsd: 1.42, area_ha: 412.4 },
  { id: "MIC-2026-07-041", siteId: "pt-ev-03", cycle: "Q3 2026", status: "scheduled",
    startedAt: null, plannedFor: "2026-07-10", baseline: "MIC-2026-04-033",
    coverage: 0, detections: 0, critical: 0, lead: "T. Aragón", drone: "DJI M350 RTK",
    progress: { draft: 1, scheduled: 1, flying: 0, processing: 0, review: 0, reported: 0, closed: 0 },
    flights: 0, images: 0, bytes: 0, gsd: null, area_ha: 412.4 },

  // Lorca Photon Field
  { id: "MIC-2026-04-029", siteId: "es-mu-02", cycle: "Q2 2026", status: "review",
    startedAt: "2026-04-14", plannedFor: "2026-04-14", baseline: "MIC-2026-01-014",
    coverage: 100, detections: 214, critical: 4, lead: "M. Rivera", drone: "DJI M350 RTK",
    progress: { draft: 1, scheduled: 1, flying: 1, processing: 1, review: 0.45, reported: 0, closed: 0 },
    flights: 6, images: 1410, bytes: 114_200_000_000, gsd: 1.8, area_ha: 82.1 },
  { id: "MIC-2026-01-014", siteId: "es-mu-02", cycle: "Q1 2026", status: "closed",
    startedAt: "2026-01-20", plannedFor: "2026-01-20", baseline: "MIC-2025-10-006",
    coverage: 99.2, detections: 380, critical: 11, lead: "M. Rivera", drone: "DJI M350 RTK",
    progress: { draft: 1, scheduled: 1, flying: 1, processing: 1, review: 1, reported: 1, closed: 1 },
    flights: 5, images: 1320, bytes: 108_200_000_000, gsd: 1.8, area_ha: 82.1 },

  // Zaragoza North
  { id: "MIC-2026-04-031", siteId: "es-zr-07", cycle: "Q2 2026", status: "flying",
    startedAt: "2026-04-18", plannedFor: "2026-04-18", baseline: "MIC-2026-01-022",
    coverage: 41, detections: 0, critical: 0, lead: "J. Castaño", drone: "DJI M350 RTK",
    progress: { draft: 1, scheduled: 1, flying: 0.55, processing: 0, review: 0, reported: 0, closed: 0 },
    flights: 4, images: 1340, bytes: 210_800_000_000, gsd: null, area_ha: 180.4 },
  { id: "MIC-2026-01-022", siteId: "es-zr-07", cycle: "Q1 2026", status: "closed",
    startedAt: "2026-01-22", plannedFor: "2026-01-22", baseline: null,
    coverage: 96.4, detections: 840, critical: 9, lead: "J. Castaño", drone: "DJI M350 RTK",
    progress: { draft: 1, scheduled: 1, flying: 1, processing: 1, review: 1, reported: 1, closed: 1 },
    flights: 9, images: 4120, bytes: 522_800_000_000, gsd: 1.42, area_ha: 180.4 },

  // Albacete — failed processing
  { id: "MIC-2026-04-028", siteId: "es-ab-01", cycle: "Q2 2026", status: "processing",
    startedAt: "2026-04-11", plannedFor: "2026-04-11", baseline: "MIC-2026-01-011",
    coverage: 0, detections: 0, critical: 0, lead: "A. Soler", drone: "DJI M350 RTK",
    progress: { draft: 1, scheduled: 1, flying: 1, processing: 0.41, review: 0, reported: 0, closed: 0 },
    flights: 8, images: 3102, bytes: 412_100_000_000, gsd: null, area_ha: 260.0,
    error: "SfM — insufficient tie points · sector 4" },
];

window.INSP_STAGES = INSP_STAGES;
window.INSPECTIONS = INSPECTIONS;
