// Mock data + helpers
const fmtNum = (n, d = 0) => {
  if (n === null || n === undefined || isNaN(n)) return '—';
  return Number(n).toLocaleString('en-IN', { minimumFractionDigits: d, maximumFractionDigits: d });
};

// localStorage caches — read once at module init so demo data can seed from saved prefs
const _agriStorage = (() => { try { return JSON.parse(localStorage.getItem('velonics_agri_data') || '{}'); } catch { return {}; } })();

// deviceId must match MQTT_CLIENT_ID in firmware/aquactrl/credentials.h
// Tanks with deviceId: null show static demo data (no live MQTT feed)
const initialTanks = [
  {
    id: 't1',
    deviceId: 'VelonicsOne_001',   // ← live ESP32 device
    name: 'Overhead Tank — Main',
    type: 'Overhead',
    location: 'Rooftop',
    capacity: 1000,
    level: 0,
    motor: false,
    motorMode: 'auto',
    valveIn: false,
    valveOut: false,
    online: false,               // set true when first telemetry arrives
    runtime: 0,
    flow: 0,
    voltage: 0,
    current: 0,
    energyToday: 0,
    consumedToday: 0,
    cycles: 0,
    temp: 0,
    tds: 0,
    lastFill: 0,
    autoStart: 25, autoStop: 90, lowAlarm: 15, highAlarm: 95,
    maxRuntime: 60, vLow: 180, vHigh: 260, iMax: 8,
    dryRun: true, overflow: true,
    fw: '2.3.0',
    signal: 4,
    lastSeen: '—',
  },
  {
    id: 't2',
    deviceId: null,              // demo / not yet provisioned
    name: 'Underground Sump',
    type: 'Underground',
    location: 'Backyard',
    capacity: 2000,
    level: 45,
    motor: false,
    motorMode: 'auto',
    valveIn: false,
    valveOut: false,
    online: false,
    runtime: 42,
    flow: 0,
    voltage: 232,
    current: 0,
    energyToday: 0.8,
    consumedToday: 410,
    cycles: 1,
    temp: 26,
    tds: 280,
    lastFill: 28,
    autoStart: 20, autoStop: 85, lowAlarm: 10, highAlarm: 95,
    maxRuntime: 90, vLow: 180, vHigh: 260, iMax: 10,
    dryRun: true, overflow: true,
    fw: '—', signal: 0, lastSeen: '—',
  },
  {
    id: 't3',
    deviceId: null,
    name: 'Garden Tank',
    type: 'Irrigation',
    location: 'Front lawn',
    capacity: 500,
    level: 18,
    motor: false,
    motorMode: 'manual',
    valveIn: false,
    valveOut: false,
    online: false,
    runtime: 12,
    flow: 0,
    voltage: 226,
    current: 0,
    energyToday: 0.3,
    consumedToday: 220,
    cycles: 2,
    temp: 31,
    tds: 410,
    lastFill: 18,
    autoStart: 25, autoStop: 90, lowAlarm: 20, highAlarm: 95,
    maxRuntime: 45, vLow: 180, vHigh: 260, iMax: 6,
    dryRun: true, overflow: false,
    fw: '—', signal: 0, lastSeen: '—',
  },
  {
    id: 't4',
    deviceId: null,
    name: 'Terrace Tank',
    type: 'Overhead',
    location: 'Annex roof',
    capacity: 750,
    level: 89,
    motor: false,
    motorMode: 'auto',
    valveIn: false,
    valveOut: false,
    online: false,
    runtime: 0,
    flow: 0,
    voltage: 0,
    current: 0,
    energyToday: 0,
    consumedToday: 0,
    cycles: 0,
    temp: 27,
    tds: 300,
    lastFill: 32,
    autoStart: 25, autoStop: 90, lowAlarm: 15, highAlarm: 95,
    maxRuntime: 60, vLow: 180, vHigh: 260, iMax: 8,
    dryRun: true, overflow: true,
    fw: '—', signal: 0, lastSeen: '—',
  },
  {
    id: 'ap1',
    deviceId: null,
    virtual: true,
    name: 'Farm Pump — Main',
    type: 'Agri Pump',
    location: 'Field A',
    capacity: 0,
    site: 'Farm House',
    online: false,
    fw: '—', signal: 0, lastSeen: '—',
    // Motor
    motor: false,
    motorStatus: 'stopped_undervolt',
    // 3-phase electrical
    phaseVoltageRY: 438, phaseVoltageYB: 441, phaseVoltageBR: 439,
    currentR: 10.2, currentY: 9.8, currentB: 10.1,
    phaseSequence: 'RYB',
    // Scheduler — restored from localStorage
    schedulerMode:     _agriStorage['ap1']?.schedulerMode  ?? 'cyclic',
    runtimeSet:        _agriStorage['ap1']?.runtimeSet     ?? 20,
    offtimeSet:        _agriStorage['ap1']?.offtimeSet     ?? 20,
    runtimeCurrent: 0,
    runtimeRemaining:  _agriStorage['ap1']?.runtimeSet     ?? 20,
    offtimeRemaining:  _agriStorage['ap1']?.offtimeSet     ?? 20,
    currentCycle: 'on',
    // History
    lastStart: '10/May/2026 - 10:20', lastStop: '10/May/2026 - 10:30',
    todayRunHours: 2.5, todayCycles: 4,
    totalRunHours: 48, totalCycles: 127,
    // Setpoints — restored from localStorage
    phaseAllowed:       _agriStorage['ap1']?.phaseAllowed       ?? '3',
    autoStartEnabled:   _agriStorage['ap1']?.autoStartEnabled   ?? true,
    autoDelay:          _agriStorage['ap1']?.autoDelay          ?? 3,
    highVoltage2P:      _agriStorage['ap1']?.highVoltage2P      ?? 260,
    lowVoltage2P:       _agriStorage['ap1']?.lowVoltage2P       ?? 180,
    voltageImbalance2P: _agriStorage['ap1']?.voltageImbalance2P ?? 10,
    overload2P:         _agriStorage['ap1']?.overload2P         ?? 12,
    dryRun2P:           _agriStorage['ap1']?.dryRun2P           ?? 5,
    availablePhase3P:   _agriStorage['ap1']?.availablePhase3P   ?? 'RY',
    highVoltage3P:      _agriStorage['ap1']?.highVoltage3P      ?? 460,
    lowVoltage3P:       _agriStorage['ap1']?.lowVoltage3P       ?? 380,
    voltageImbalance3P: _agriStorage['ap1']?.voltageImbalance3P ?? 5,
    overload3P:         _agriStorage['ap1']?.overload3P         ?? 15,
    dryRun3P:           _agriStorage['ap1']?.dryRun3P           ?? 5,
    // Switch style — restored from localStorage
    switchType:         _agriStorage['ap1']?.switchType         || 'round',
  },
];

// Occupancy Sensor demo devices
const initialOccupancySensors = [
  {
    id: 'os1',
    deviceId: null,
    virtual: true,
    type: 'Occupancy Sensor',
    kind: 'occupancy',
    name: 'Living Room Sensor',
    location: 'Living Room',
    site: 'Home',
    online: false,
    fw: '—', signal: 0, lastSeen: '—',
    // Live state
    occupied: false,
    countToday: 12,
    duration: 0,
    runtimeToday: 3720,
    relayOn: false,
    relayMode: 'auto',
    sensitivity: 5,
    // Setpoints
    osVacancyTimeout: 300,
    osHoldTime: 60,
    osSensitivity: 5,
    osRelayMode: 'auto',
    osNightModeStart: '22:00',
    osNightModeEnd: '06:00',
    osNightSensitivity: 3,
    osZone: 'Living Room',
  },
];

// Smart Plug demo devices — restore schedules/timer/settings from localStorage on page load
const _plugStorage = (() => { try { return JSON.parse(localStorage.getItem('velonics_plug_data') || '{}'); } catch { return {}; } })();
const initialPlugs = [
  {
    id: 'p1',
    deviceId: null,
    virtual: true,
    type: 'Smart Plug',
    name: 'Geyser — Master Bath',
    appliance: 'Geyser',
    location: 'Master Bathroom',
    on: false,
    online: false,
    voltage: 232, current: 0, power: 0,
    energyToday: 2.6, energyTotal: 184.3,
    runtimeToday: 78,
    switchType:    _plugStorage['p1']?.switchType    || 'round',
    overload:      _plugStorage['p1']?.overload      ?? 12,
    overloadAlert: _plugStorage['p1']?.overloadAlert !== false,
    childLock:     !!_plugStorage['p1']?.childLock,
    ledIndicator:  _plugStorage['p1']?.ledIndicator  !== false,
    timer: (_plugStorage['p1']?.timer && _plugStorage['p1'].timer.endsAt > Date.now()) ? _plugStorage['p1'].timer : null,
    schedules: _plugStorage['p1']?.schedules || [
      { id: 's1', label: 'Morning geyser',   start: '06:00', end: '06:30', days: [1,1,1,1,1,0,0], action: 'on',  repeat: 'weekdays', enabled: true  },
      { id: 's2', label: 'Weekend warm-up',  start: '07:30', end: '08:15', days: [0,0,0,0,0,1,1], action: 'on',  repeat: 'custom',   enabled: true  },
      { id: 's3', label: 'Safety auto-off',  start: '23:00', end: '',      days: [1,1,1,1,1,1,1], action: 'off', repeat: 'daily',    enabled: false },
    ],
    fw: '2.3.0', signal: 4, lastSeen: '—',
  },
  {
    id: 'p2',
    deviceId: null,
    virtual: true,
    type: 'Smart Plug',
    name: 'Living Room TV',
    appliance: 'TV',
    location: 'Living Room',
    on: false,
    online: false,
    voltage: 228, current: 0, power: 0,
    energyToday: 0.8, energyTotal: 56.2,
    runtimeToday: 22,
    switchType:    _plugStorage['p2']?.switchType    || 'toggle',
    overload:      _plugStorage['p2']?.overload      ?? 10,
    overloadAlert: _plugStorage['p2']?.overloadAlert !== false,
    childLock:     !!_plugStorage['p2']?.childLock,
    ledIndicator:  _plugStorage['p2']?.ledIndicator  !== false,
    timer: (_plugStorage['p2']?.timer && _plugStorage['p2'].timer.endsAt > Date.now()) ? _plugStorage['p2'].timer : null,
    schedules: _plugStorage['p2']?.schedules || [],
    fw: '2.3.1', signal: 3, lastSeen: '—',
  },
];

// 24h area chart sample data (Detail view mini-chart)
function gen24h() {
  const out = [];
  let lvl = 60;
  for (let h = 0; h < 24; h++) {
    if (h === 5 || h === 6 || h === 18 || h === 19) lvl += 14 + Math.random() * 4;
    else lvl -= 2 + Math.random() * 3;
    lvl = Math.max(20, Math.min(95, lvl));
    out.push({ t: `${String(h).padStart(2, '0')}:00`, level: Math.round(lvl) });
  }
  return out;
}

const days7 = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
const volumeWeek = [
  { d:'Mon', L: 1200 }, { d:'Tue', L: 980 },  { d:'Wed', L: 1350 },
  { d:'Thu', L: 1100 }, { d:'Fri', L: 1500 }, { d:'Sat', L: 1800 }, { d:'Sun', L: 1650 }
];
const energyWeek = volumeWeek.map(x => ({ d: x.d, kWh: +(x.L / 290).toFixed(2) }));
const motorWeek  = volumeWeek.map((x,i) => ({ d: x.d, runMin: 60 + i*8 + (i%2?20:0), cycles: 2 + (i%3) }));
const vcDay = Array.from({length: 24}, (_,h) => ({
  t: `${String(h).padStart(2,'0')}:00`,
  V: 215 + Math.round(Math.sin(h/3)*15 + (Math.random()*8)),
  A: +(2 + Math.sin(h/4)*1.5 + Math.random()).toFixed(2),
}));
const tankCompare = [
  { tank: 'Overhead', L: 850 }, { tank: 'Underground', L: 410 },
  { tank: 'Garden', L: 220 },   { tank: 'Terrace', L: 0 },
];

const initialAlerts = [
  { id:'a1',  sev:'critical', title:'Low Water Level Alert', desc:'Overhead Tank — Main dropped below 15%', tank:'Overhead Tank — Main', time:'2 min ago', ack:false },
  { id:'a2',  sev:'critical', title:'Motor Overload Detected', desc:'Current exceeded 8A on Underground Sump', tank:'Underground Sump', time:'15 min ago', ack:false },
  { id:'a3',  sev:'warning',  title:'High Voltage Alert', desc:'Voltage spike to 255V detected on Garden Tank', tank:'Garden Tank', time:'1 hour ago', ack:false },
  { id:'a4',  sev:'warning',  title:'Unusual Consumption', desc:'Garden Tank consuming 3× normal rate. Possible leak?', tank:'Garden Tank', time:'2 hours ago', ack:false },
  { id:'a5',  sev:'info',     title:'Motor Auto-Started', desc:'Overhead Tank level reached 25%, motor started', tank:'Overhead Tank — Main', time:'3 hours ago', ack:true },
  { id:'a6',  sev:'info',     title:'Tank Full', desc:'Underground Sump reached 90%, motor stopped', tank:'Underground Sump', time:'4 hours ago', ack:true },
  { id:'a7',  sev:'critical', title:'Device Offline', desc:'Terrace Tank controller lost connection', tank:'Terrace Tank', time:'5 hours ago', ack:false },
  { id:'a8',  sev:'warning',  title:'Dry Run Warning', desc:'No flow detected despite motor running for 5 min', tank:'Overhead Tank — Main', time:'6 hours ago', ack:true },
  { id:'a9',  sev:'info',     title:'Setpoint Changed', desc:'Auto-stop level changed from 85% to 90%', tank:'Overhead Tank — Main', time:'8 hours ago', ack:true },
  { id:'a10', sev:'info',     title:'Motor Stopped', desc:'Manual stop command executed', tank:'Underground Sump', time:'10 hours ago', ack:true },
  { id:'a11', sev:'warning',  title:'Low Voltage', desc:'Voltage dropped to 185V', tank:'Overhead Tank — Main', time:'12 hours ago', ack:true },
  { id:'a12', sev:'info',     title:'Firmware Update Available', desc:'v2.3.1 available for Overhead Tank controller', tank:'Overhead Tank — Main', time:'1 day ago', ack:false },
  { id:'a13', sev:'info',     title:'Motor Cycle Complete', desc:'Garden Tank fill cycle finished in 18 min', tank:'Garden Tank', time:'1 day ago', ack:true },
  { id:'a14', sev:'warning',  title:'Schedule Skipped', desc:'Morning Fill skipped — already above setpoint', tank:'Overhead Tank — Main', time:'1 day ago', ack:true },
];

const initialEM = [
  {
    id: 'em1',
    deviceId: null,
    type: 'Energy Meter',
    name: 'Main Panel Monitor',
    location: 'Electrical Panel',
    site: 'Home',
    virtual: true,
    online: false,
    fw: '—', signal: 0, lastSeen: '—',
    voltage: 232, current: 4.2, power: 974, energy: 0,
    energyToday: 3.8, freq: 50.0, pf: 0.94,
  },
];

const initialRO = [
  {
    id: 'ro1',
    deviceId: null,
    type: 'Smart RO',
    name: 'Kitchen RO',
    location: 'Kitchen',
    site: 'Home',
    virtual: true,
    online: false,
    fw: '—', signal: 0, lastSeen: '—',
    motor: false,
    tds: 0, outletTDS: 22,
    saltRejection: 96.2,
    purifiedToday: 14.5,
    inletPressure: 3.2, outletPressure: 6.1, wasteFlow: 0.8,
    filterLife: 78,
    inletTDS: 820, inletFlow: 0, outletFlow: 0,
    recoveryRate: 0, temp: 26, cycles: 0, rssi: 0, inletVolTotal: 1250,
  },
];

const _acStorage = (() => { try { return JSON.parse(localStorage.getItem('velonics_ac_data') || '{}'); } catch { return {}; } })();
const initialAC = [
  {
    id: 'ac1', deviceId: null, virtual: true,
    type: 'Smart AC', kind: 'smart_ac',
    name: 'Living Room AC', appliance: 'Split AC', location: 'Living Room', site: 'Home',
    on: false, temp: _acStorage['ac1']?.temp ?? 24,
    mode: _acStorage['ac1']?.mode ?? 'cool',
    fanSpeed: _acStorage['ac1']?.fanSpeed ?? 'auto',
    brand: _acStorage['ac1']?.brand ?? null, model: _acStorage['ac1']?.model ?? null,
    irLearned: false, ecoMode: false, online: false,
    voltage: 232, current: 0, power: 0, energyToday: 1.8, runtimeToday: 0,
    switchType: _acStorage['ac1']?.switchType || 'round',
    presets: _acStorage['ac1']?.presets || [
      { id: 'pr1', name: 'Sleep', temp: 26, mode: 'cool', fanSpeed: 'low'  },
      { id: 'pr2', name: 'Work',  temp: 24, mode: 'cool', fanSpeed: 'auto' },
      { id: 'pr3', name: 'Turbo', temp: 18, mode: 'cool', fanSpeed: 'high' },
    ],
    schedules: _acStorage['ac1']?.schedules || [],
    timer: (_acStorage['ac1']?.timer && _acStorage['ac1'].timer.endsAt > Date.now()) ? _acStorage['ac1'].timer : null,
    sleepCurve: _acStorage['ac1']?.sleepCurve || null,
    wakeTimer: _acStorage['ac1']?.wakeTimer || null,
    fw: '—', signal: 0, lastSeen: '—',
    vLow: 180, vHigh: 260, iMax: 10, powerMax: 2500,
  },
];

window.AC = { fmtNum, initialTanks, initialPlugs, initialOccupancySensors, initialEM, initialRO, initialAC, initialAlerts, gen24h, days7, volumeWeek, energyWeek, motorWeek, vcDay, tankCompare };
