// Mock data for Bleu SmartDER prototype
// Shared across all screens.
// Sourced from: "3-tenant 6-device Bleu SmartDER MVP — Dummy Data, Dashboard
// Fields and Final Deliverable Brief" (2026-05).

const TENANTS = [
  {
    id: 't-ahmed',
    tenantCode: 'T-AHM-001',
    name: 'Ahmed Hassan Farm',
    type: 'Irrigation + cold storage',
    contact: 'Ahmed Hassan',
    email: 'ahmed.demo@bleu.sd',
    phone: '+249 900 000 101',
    address: 'Gezira State, Sudan',
    package: 'Standard',
    deviceCount: 3,
    activeDevices: 2,
    monthSpend: 249000,
    balance: 0,
    status: 'active',
    joined: '2024-11-08',
  },
  {
    id: 't-mariam',
    tenantCode: 'T-MCS-002',
    name: 'Mariam Cold Storage',
    type: 'Cold room / packhouse',
    contact: 'Mariam Bakheit',
    email: 'mariam.demo@bleu.sd',
    phone: '+249 900 000 102',
    address: 'Khartoum Industrial Zone',
    package: 'Premium',
    deviceCount: 1,
    activeDevices: 1,
    monthSpend: 192000,
    balance: 0,
    status: 'active',
    joined: '2025-02-01',
  },
  {
    id: 't-yousif',
    tenantCode: 'T-YCH-003',
    name: 'Yousif Cooperative Hub',
    type: 'Cooperative energy hub',
    contact: 'Yousif Bakri',
    email: 'yousif.demo@bleu.sd',
    phone: '+249 900 000 103',
    address: 'Northern State, Sudan',
    package: 'Standard',
    deviceCount: 2,
    activeDevices: 1,
    monthSpend: 128000,
    balance: 0,
    status: 'active',
    joined: '2025-01-20',
  },
];

const PACKAGES = [
  { id: 'pkg-basic', name: 'Basic',    monthlyFee: 60000,  includedKwh: 50,  desc: 'Single pump, small solar-only unit, pilot device, basic monitoring.',         color: '#7d8da0' },
  { id: 'pkg-std',   name: 'Standard', monthlyFee: 120000, includedKwh: 100, desc: 'Irrigation clusters, mixed productive loads, multi-device farms, cooperatives.', color: '#1b5c8e' },
  { id: 'pkg-prem',  name: 'Premium',  monthlyFee: 220000, includedKwh: 220, desc: 'Cold rooms, packhouses, hybrid sites, higher-load productive users.',           color: '#5baa6f' },
];

const TARIFF = { sdgPerKwh: 1000, effectiveFrom: '2025-01-01' };

const DEVICES = [
  // ============ Ahmed Hassan Farm ============
  {
    id: 'd-pump-01',
    label: 'Water Pump 01',
    serial: 'BLD-WP-0118',
    type: 'solar_battery_der',
    typeLabel: 'Solar + Battery',
    tenantId: 't-ahmed',
    package: 'Standard',
    pvKw: 15, batteryKwh: 30, maxLoadKw: 10,
    inverter: 'Demo inverter Hybrid-15K-Demo',
    location: 'North Field, Gezira',
    lat: 14.4012, lng: 33.5108,
    installDate: '2025-01-01',
    status: 'active',
    firmware: '1.0.4',
    tick: 3000,
    simEnabled: true,
    pvNow: 11.8, soc: 72, loadKwh: 8.2, credit: 41.3,
    liveLoadKw: 4.6, batteryTempC: 34,
    connectivity: 'online', gsm: 'fair',
    todayGen: 58.4, alarms: 1,
  },
  {
    id: 'd-cold-A',
    label: 'Cold Room A',
    serial: 'BLD-CR-0204',
    type: 'solar_battery_der',
    typeLabel: 'Solar + Battery',
    tenantId: 't-ahmed',
    package: 'Premium',
    pvKw: 30, batteryKwh: 60, maxLoadKw: 20,
    inverter: 'Demo inverter Hybrid-30K-Demo',
    location: 'Storage Yard, Gezira',
    lat: 14.4031, lng: 33.5142,
    installDate: '2025-03-15',
    status: 'active',
    firmware: '1.0.4',
    tick: 3000,
    simEnabled: true,
    pvNow: 22.6, soc: 68, loadKwh: 12.4, credit: 128.7,
    liveLoadKw: 9.2, batteryTempC: 35,
    connectivity: 'online', gsm: 'good',
    todayGen: 96.4, alarms: 1,
  },
  {
    id: 'd-irrig',
    label: 'Irrigation Unit',
    serial: 'BLD-IRR-0042',
    type: 'solar_only',
    typeLabel: 'Solar Only',
    tenantId: 't-ahmed',
    package: 'Basic',
    pvKw: 5, batteryKwh: 0, maxLoadKw: 4,
    inverter: '—',
    location: 'East Field, Gezira',
    lat: 14.3992, lng: 33.5202,
    installDate: '2024-12-10',
    status: 'maintenance',
    firmware: '1.0.2',
    tick: 5000,
    simEnabled: true,
    pvNow: 3.7, soc: null, loadKwh: 4.0, credit: 12.1,
    liveLoadKw: 1.4, batteryTempC: null,
    connectivity: 'online', gsm: 'fair',
    todayGen: 18.4, alarms: 0,
  },

  // ============ Mariam Cold Storage ============
  {
    id: 'd-mariam-1',
    label: 'Main Cooling Unit',
    serial: 'BLD-MCS-0101',
    type: 'hybrid',
    typeLabel: 'Hybrid',
    tenantId: 't-mariam',
    package: 'Premium',
    pvKw: 30, batteryKwh: 60, maxLoadKw: 22,
    inverter: 'Demo inverter Hybrid-30K-Demo',
    location: 'Khartoum Industrial Zone',
    lat: 15.5007, lng: 32.5599,
    installDate: '2025-02-01',
    status: 'active',
    firmware: '1.0.4',
    tick: 3000,
    simEnabled: true,
    pvNow: 18.4, soc: 74, loadKwh: 18.6, credit: 83.2,
    liveLoadKw: 11.6, batteryTempC: 36,
    connectivity: 'online', gsm: 'good',
    todayGen: 88.2, alarms: 0,
  },

  // ============ Yousif Cooperative Hub ============
  {
    id: 'd-yousif-1',
    label: 'Cooperative Hub Unit',
    serial: 'BLD-YCH-0701',
    type: 'solar_battery_der',
    typeLabel: 'Solar + Battery',
    tenantId: 't-yousif',
    package: 'Standard',
    pvKw: 10, batteryKwh: 20, maxLoadKw: 8,
    inverter: 'Demo inverter Hybrid-10K-Demo',
    location: 'Cooperative Site, Northern State',
    lat: 18.7012, lng: 30.4011,
    installDate: '2025-01-20',
    status: 'active',
    firmware: '1.0.4',
    tick: 3000,
    simEnabled: true,
    pvNow: 6.2, soc: 76, loadKwh: 5.1, credit: 33.4,
    liveLoadKw: 3.2, batteryTempC: 33,
    connectivity: 'weak_gsm', gsm: 'weak',
    todayGen: 32.6, alarms: 0,
  },
  {
    id: 'd-yousif-2',
    label: 'Dryer Unit B',
    serial: 'BLD-YCH-0702',
    type: 'solar_battery_der',
    typeLabel: 'Solar + Battery',
    tenantId: 't-yousif',
    package: 'Premium',
    pvKw: 25, batteryKwh: 60, maxLoadKw: 20,
    inverter: 'Pending commissioning',
    location: 'Cooperative Site, Northern State',
    lat: 18.7044, lng: 30.4022,
    installDate: null,
    status: 'inactive',
    firmware: '—',
    tick: 3000,
    simEnabled: false,
    pvNow: 0, soc: null, loadKwh: 0, credit: 0,
    liveLoadKw: 0, batteryTempC: null,
    connectivity: 'not_commissioned', gsm: null,
    todayGen: 0, alarms: 0,
  },
];

const INVOICES = [
  // ----- Current open invoices -----
  {
    id: 'INV-2026-04-AHM',
    tenantId: 't-ahmed',
    month: 4, year: 2026,
    devices: 3,
    issuedAt: '2026-05-01',
    dueDate: '2026-05-15',
    status: 'pending_payment',
    subtotal: 249000, tax: 0, total: 249000,
    tariff: 1000,
    // §16 PDF: one tenant-level base fee + per-device variable lines.
    lines: [
      { deviceId: null,        desc: 'Tenant Monthly Base Fee — Standard Package', qty: 1,   unit: 'month', price: 120000, total: 120000, group: 'Tenant base fee' },
      { deviceId: 'd-pump-01', desc: 'Included Energy — Water Pump 01',            qty: 100, unit: 'kWh',   price: 0,      total: 0,      group: 'Water Pump 01' },
      { deviceId: 'd-pump-01', desc: 'Variable Energy — Water Pump 01',            qty: 42,  unit: 'kWh',   price: 1000,   total: 42000,  group: 'Water Pump 01' },
      { deviceId: 'd-cold-A',  desc: 'Included Energy — Cold Room A',              qty: 100, unit: 'kWh',   price: 0,      total: 0,      group: 'Cold Room A' },
      { deviceId: 'd-cold-A',  desc: 'Variable Energy — Cold Room A',              qty: 87,  unit: 'kWh',   price: 1000,   total: 87000,  group: 'Cold Room A' },
      { deviceId: 'd-irrig',   desc: 'Irrigation Unit — Maintenance Mode',         qty: 1,   unit: 'month', price: 0,      total: 0,      group: 'Irrigation Unit' },
    ],
  },
  {
    id: 'INV-2026-04-MCS',
    tenantId: 't-mariam',
    month: 4, year: 2026,
    devices: 1,
    issuedAt: '2026-05-01',
    dueDate: '2026-05-15',
    status: 'pending_verification',
    subtotal: 192000, tax: 0, total: 192000,
    tariff: 1000,
    lines: [
      { deviceId: null,          desc: 'Tenant Monthly Base Fee — Premium Package', qty: 1,   unit: 'month', price: 120000, total: 120000, group: 'Tenant base fee' },
      { deviceId: 'd-mariam-1',  desc: 'Included Energy — Main Cooling Unit',       qty: 220, unit: 'kWh',   price: 0,      total: 0,      group: 'Main Cooling Unit' },
      { deviceId: 'd-mariam-1',  desc: 'Variable Energy — Main Cooling Unit',       qty: 72,  unit: 'kWh',   price: 1000,   total: 72000,  group: 'Main Cooling Unit' },
    ],
  },
  {
    id: 'INV-2026-04-YCH',
    tenantId: 't-yousif',
    month: 4, year: 2026,
    devices: 2,
    issuedAt: '2026-05-01',
    dueDate: '2026-05-15',
    status: 'overdue',
    subtotal: 128000, tax: 0, total: 128000,
    tariff: 1000,
    lines: [
      { deviceId: null,         desc: 'Tenant Monthly Base Fee — Standard Package', qty: 1,   unit: 'month', price: 120000, total: 120000, group: 'Tenant base fee' },
      { deviceId: 'd-yousif-1', desc: 'Included Energy — Cooperative Hub Unit',     qty: 100, unit: 'kWh',   price: 0,      total: 0,      group: 'Cooperative Hub Unit' },
      { deviceId: 'd-yousif-1', desc: 'Variable Energy — Cooperative Hub Unit',     qty: 8,   unit: 'kWh',   price: 1000,   total: 8000,   group: 'Cooperative Hub Unit' },
      { deviceId: 'd-yousif-2', desc: 'Dryer Unit B — Not commissioned',            qty: 1,   unit: 'month', price: 0,      total: 0,      group: 'Dryer Unit B' },
    ],
  },

  // ----- Optional historical (paid) -----
  {
    id: 'INV-2026-03-AHM',
    tenantId: 't-ahmed',
    month: 3, year: 2026,
    devices: 3,
    issuedAt: '2026-04-01',
    dueDate: '2026-04-15',
    status: 'paid',
    subtotal: 218000, tax: 0, total: 218000,
    tariff: 1000,
    paidAt: '2026-04-11',
    method: 'online',
  },
];

const PAYMENTS = [
  {
    id: 'PAY-2026-0504-MCS',
    tenantId: 't-mariam',
    invoiceId: 'INV-2026-04-MCS',
    method: 'reference_upload',
    methodLabel: 'Transfer reference upload',
    amount: 192000,
    status: 'pending_verification',
    reference: 'REF-MCS-044',
    submittedAt: '2026-05-04',
  },
  {
    id: 'PAY-2026-0411-AHM',
    tenantId: 't-ahmed',
    invoiceId: 'INV-2026-03-AHM',
    method: 'online',
    methodLabel: 'Online payment',
    amount: 218000,
    status: 'verified',
    reference: 'BLU-AHM-031',
    submittedAt: '2026-04-11',
    verifiedAt: '2026-04-11',
  },
];

const ALARMS = [
  // §5 PDF: Alerts card shows 3 = 2 warnings + 1 info.
  {
    id: 'a1', deviceId: 'd-cold-A', tenantId: 't-ahmed',
    severity: 'warn', kind: 'fault_watch',
    msg: 'Cold Room A compressor cycling above normal threshold',
    at: '2026-05-13 14:22:00', cleared: false,
  },
  {
    id: 'a2', deviceId: 'd-pump-01', tenantId: 't-ahmed',
    severity: 'warn', kind: 'paygo_low',
    msg: 'Water Pump 01 PAYGo credit below 50 kWh',
    at: '2026-05-13 14:17:08', cleared: false,
  },
  {
    id: 'a3', deviceId: 'd-irrig', tenantId: 't-ahmed',
    severity: 'info', kind: 'maintenance',
    msg: 'Irrigation Unit set to maintenance mode',
    at: '2026-05-13 14:04:00', cleared: false,
  },
];

// §5 Required activity feed — verbatim from PDF.
const ACTIVITY = [
  { at: '14:22', deviceId: 'd-cold-A',   tag: 'warn', kind: 'fault_watch',  msg: 'Cold Room A compressor cycling above normal threshold' },
  { at: '14:20', deviceId: null,         tag: 'info', kind: 'billing',      msg: 'INV-2026-04-AHM generated for Ahmed Hassan Farm' },
  { at: '14:17', deviceId: 'd-pump-01',  tag: 'warn', kind: 'paygo_low',    msg: 'Water Pump 01 PAYGo credit below 50 kWh' },
  { at: '14:10', deviceId: 'd-mariam-1', tag: 'info', kind: 'sync',         msg: 'Main Cooling Unit restored after 11 minutes offline' },
  { at: '14:04', deviceId: 'd-irrig',    tag: 'info', kind: 'maintenance',  msg: 'Irrigation Unit moved to maintenance mode' },
  { at: '13:48', deviceId: 'd-yousif-1', tag: 'warn', kind: 'connectivity', msg: 'Cooperative Hub Unit switched to weak GSM fallback' },
];

// §11 PDF: SmartDER Intelligence panel data (constants, used by admin + tenant screens).
const INTELLIGENCE = {
  forecastSolarTomorrowKwh: 182,
  expectedLoadKwh: 146,
  expectedSurplusKwh: 36,
  batteryRisk: 'Low',
  dispatchWindow: '10:00–15:00',
  faultWatch: 'Cold Room A compressor cycling above normal threshold',
  dataConfidencePercent: 82,
  lastSyncLabel: '3 minutes ago',
  basis: 'Simulated PV curve + last 7 days load profile',
  recommendation: 'Prioritise irrigation and cold-room charging between 10:00 and 15:00 tomorrow. Expected solar surplus is sufficient to avoid evening battery stress.',
  disclaimer: 'Forecast and recommendation values are part of the MVP simulation and will be validated with live pilot telemetry during the R&D phase.',
};

// §12 PDF: Low-bandwidth widget — expanded card values.
const LOW_BANDWIDTH = {
  lastSyncMinutes: 4,
  bufferActive: true,
  queuedReadings: 23,
  gsm: 'weak',
  autoSync: true,
  gateway: 'Raspberry Pi + Node-RED demo gateway',
  protocol: 'MQTT / REST',
  oldestQueuedMinutes: 12,
  compression: true,
  nextSyncSeconds: 60,
  dataLossRisk: 'Low',
  lastRecoveryEvent: 'Main Cooling Unit restored after 11 minutes offline',
  readingsRecovered: 220,
  readingsLost: 0,
};

// Time-series generators (deterministic-ish sine + noise)
function genSolarCurve(samples = 96, pvCapacityKw = 20, seed = 1) {
  // 24h sample at 15-min steps (or whatever): solar follows sunrise–sunset bell.
  const out = [];
  let s = seed;
  for (let i = 0; i < samples; i++) {
    const hour = (i / samples) * 24;
    let v = 0;
    if (hour > 5.5 && hour < 19) {
      const t = (hour - 5.5) / 13.5;
      v = pvCapacityKw * Math.pow(Math.sin(t * Math.PI), 1.6);
    }
    s = (s * 9301 + 49297) % 233280;
    const noise = (s / 233280 - 0.5) * pvCapacityKw * 0.04;
    out.push(Math.max(0, v + noise));
  }
  return out;
}

function genLoadCurve(samples = 96, maxLoadKw = 8, seed = 2) {
  const out = [];
  let s = seed;
  for (let i = 0; i < samples; i++) {
    const hour = (i / samples) * 24;
    // Two humps morning + evening
    const m = Math.exp(-Math.pow((hour - 8) / 2.4, 2));
    const e = Math.exp(-Math.pow((hour - 19) / 2.0, 2));
    let v = maxLoadKw * (0.25 + 0.55 * m + 0.7 * e);
    s = (s * 9301 + 49297) % 233280;
    v += (s / 233280 - 0.5) * maxLoadKw * 0.08;
    out.push(Math.max(0.1, v));
  }
  return out;
}

function genSocCurve(samples = 96, seed = 3) {
  const out = [];
  let s = seed;
  let soc = 55;
  for (let i = 0; i < samples; i++) {
    const hour = (i / samples) * 24;
    // Charges during day, discharges evening/night
    const dcharge = hour > 7 && hour < 17 ? 0.8 : -0.5;
    soc += dcharge;
    s = (s * 9301 + 49297) % 233280;
    soc += (s / 233280 - 0.5) * 0.6;
    soc = Math.max(15, Math.min(98, soc));
    out.push(soc);
  }
  return out;
}

function genPaygoCurve(samples = 30, start = 60, perDay = 2.2, seed = 4) {
  const out = [];
  let v = start;
  let s = seed;
  for (let i = 0; i < samples; i++) {
    s = (s * 9301 + 49297) % 233280;
    const nv = (s / 233280) > 0.18 ? -perDay : 30; // occasional top-up
    v += nv + (s / 233280 - 0.5) * 1.2;
    v = Math.max(2, v);
    out.push(v);
  }
  return out;
}

Object.assign(window, {
  TENANTS, PACKAGES, TARIFF, DEVICES, INVOICES, PAYMENTS, ALARMS, ACTIVITY,
  INTELLIGENCE, LOW_BANDWIDTH,
  genSolarCurve, genLoadCurve, genSocCurve, genPaygoCurve,
});
