// Energy Meter detail — Monitor | History | Settings tabs
const EmDetail = ({ tank, onBack, updateTank, issueCmd, pendingCmds }) => {
  const { BarChart, Bar, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } = window.Recharts;

  const [tab,          setTab]          = useState('monitor');
  const [period,       setPeriod]       = useState('day');
  const [energyHours,  setEnergyHours]  = useState([]);
  const [energyDays,   setEnergyDays]   = useState([]);
  const [pwrBuf,       setPwrBuf]       = useState([]);
  const [draftSet,     setDraftSet]     = useState({
    vLow:     tank.vLow     ?? 180,
    vHigh:    tank.vHigh    ?? 260,
    iMax:     tank.iMax     ?? 16,
    powerMax: tank.powerMax ?? 3000,
  });

  const tankPending   = (pendingCmds && pendingCmds[tank.id]) || {};
  const _isVirtualEM  = !tank.deviceId || !!tank.virtual;
  const controlsReady = _isVirtualEM || (tank.online && tank.mqttReceived);
  const tariff        = parseFloat(window.PREFS?.rate ?? 7.50);
  const currency      = window.PREFS?.currency ?? '₹';

  const lastTelRef = useRef(null);
  useEffect(() => {
    if (!tank._lastTelemetryMs || tank._lastTelemetryMs === lastTelRef.current) return;
    lastTelRef.current = tank._lastTelemetryMs;
    const now = new Date();
    const hh = String(now.getHours()).padStart(2, '0');
    const mm = String(now.getMinutes()).padStart(2, '0');
    const ss = String(now.getSeconds()).padStart(2, '0');
    setPwrBuf(prev => {
      const next = [...prev, { t: `${hh}:${mm}:${ss}`, w: Math.round(tank.power ?? 0) }];
      return next.length > 60 ? next.slice(-60) : next;
    });
  }, [tank._lastTelemetryMs]);

  const _emRef = useRef(tank);
  useEffect(() => { _emRef.current = tank; });
  useEffect(() => {
    if (tank.deviceId && !tank.virtual) return;
    const id = setInterval(() => {
      const t = _emRef.current;
      if (t.deviceId && !t.virtual) return;
      const baseW = t.power || 974;
      const watt = Math.round(baseW + (Math.random() - 0.5) * 80);
      const volt = 230 + Math.round((Math.random() - 0.5) * 10);
      const amps = parseFloat((watt / volt).toFixed(2));
      const pf   = parseFloat((0.92 + Math.random() * 0.06).toFixed(2));
      const now = new Date();
      const ts = `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}:${String(now.getSeconds()).padStart(2,'0')}`;
      updateTank(t.id, { power: watt, voltage: volt, current: amps, pf });
      setPwrBuf(prev => {
        const next = [...prev, { t: ts, w: watt }];
        return next.length > 60 ? next.slice(-60) : next;
      });
    }, 2000);
    return () => clearInterval(id);
  }, [tank.deviceId, tank.virtual]); // eslint-disable-line

  useEffect(() => {
    if (!tank.deviceId || !window.API) return;
    const id = encodeURIComponent(tank.deviceId);
    Promise.all([
      API.get(`/api/tanks/energy?deviceId=${id}&groupBy=hour&limit=168`),
      API.get(`/api/tanks/energy?deviceId=${id}&groupBy=day&limit=365`),
    ]).then(([hours, days]) => {
      setEnergyHours(Array.isArray(hours) ? hours : []);
      setEnergyDays(Array.isArray(days)   ? days  : []);
    }).catch(() => {});
  }, [tank.deviceId]);

  const todayStr = new Date().toLocaleDateString('sv');
  const monthStr = todayStr.slice(0, 7);
  const todayKwh = energyDays.find(r => r.period === todayStr)?.kwh ?? 0;
  const monthKwh = energyDays
    .filter(r => r.period?.startsWith(monthStr))
    .reduce((s, r) => s + (r.kwh || 0), 0);
  const monthBill = monthKwh * tariff;

  const chartData = useMemo(() => {
    const now = new Date();
    if (period === 'day') {
      return Array.from({ length: 24 }, (_, i) => {
        const padH = String(i).padStart(2, '0');
        const key  = `${todayStr} ${padH}:00`;
        const row  = energyHours.find(r => r.period === key);
        return { label: `${padH}`, kwh: row?.kwh ?? 0 };
      });
    }
    if (period === 'month') {
      const dim = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
      return Array.from({ length: dim }, (_, i) => {
        const dStr = `${monthStr}-${String(i + 1).padStart(2, '0')}`;
        const row  = energyDays.find(r => r.period === dStr);
        return { label: String(i + 1), kwh: row?.kwh ?? 0 };
      });
    }
    const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    const yr = now.getFullYear();
    return Array.from({ length: 12 }, (_, i) => {
      const mStr = `${yr}-${String(i + 1).padStart(2, '0')}`;
      const kwh  = energyDays
        .filter(r => r.period?.startsWith(mStr))
        .reduce((s, r) => s + (r.kwh || 0), 0);
      return { label: MONTHS[i], kwh };
    });
  }, [period, energyHours, energyDays]);

  const periodTotal = chartData.reduce((s, d) => s + (d.kwh || 0), 0);
  const periodLabel = period === 'day'   ? "Today's Total"
                    : period === 'month' ? `${new Date().toLocaleString('default', { month: 'long' })} Total`
                    : `${new Date().getFullYear()} Total`;

  const calMonths = useMemo(() => {
    const MON = ['January','February','March','April','May','June',
                 'July','August','September','October','November','December'];
    const now = new Date();
    return Array.from({ length: 3 }, (_, m) => {
      const d   = new Date(now.getFullYear(), now.getMonth() - m, 1);
      const y   = d.getFullYear();
      const mo  = d.getMonth();
      const mStr = `${y}-${String(mo + 1).padStart(2, '0')}`;
      const dim  = new Date(y, mo + 1, 0).getDate();
      const fdow = new Date(y, mo, 1).getDay();
      const days = Array.from({ length: dim }, (_, i) => {
        const dStr = `${mStr}-${String(i + 1).padStart(2, '0')}`;
        const row  = energyDays.find(r => r.period === dStr);
        return { d: i + 1, kwh: row?.kwh ?? null };
      });
      const mKwh = days.reduce((s, d) => s + (d.kwh ?? 0), 0);
      return { name: `${MON[mo]} ${y}`, fdow, days, mKwh, mStr };
    });
  }, [energyDays]);

  const saveSetpoints = () => {
    updateTank(tank.id, draftSet);
    if (window.API) API.put(`/api/tanks/${tank.id}/setpoints`, draftSet).catch(() => {});
    if (tank.deviceId && issueCmd)
      issueCmd(tank.id, 'setpoints', () => MQ.publishSetpoints(tank.deviceId, draftSet));
    window.__toast?.('Setpoints saved', { kind: 'success' });
  };

  const tabs = [
    { key: 'monitor',  label: 'Monitor'  },
    { key: 'history',  label: 'History'  },
    { key: 'settings', label: 'Settings' },
  ];
  const swipe = useSwipeTabs(tabs, tab, setTab, onBack);

  return (
    <div onTouchStart={swipe.onTouchStart} onTouchEnd={swipe.onTouchEnd} style={{
      position: 'fixed', inset: 0, zIndex: 50,
      background: 'linear-gradient(180deg, var(--bg-1) 0%, var(--bg-2) 100%)',
      overflowY: 'auto', animation: 'slide-up 300ms ease-out', paddingBottom: 32,
    }}>
      {/* Header */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 10,
        display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
        background: 'rgba(10,14,39,0.88)', backdropFilter: 'blur(14px)',
        borderBottom: '1px solid var(--border)',
      }}>
        <button onClick={onBack} style={{ background: 'rgba(255,255,255,0.06)', border: '1px solid var(--border)', borderRadius: 10, width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', cursor: 'pointer' }}>
          <Ic name="chevronLeft" size={18}/>
        </button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 16, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{tank.name}</div>
          <div style={{ fontSize: 11, color: 'var(--text-3)' }}>{tank.location} · Energy Meter</div>
        </div>
        <Badge color={_isVirtualEM ? 'amber' : controlsReady ? 'green' : !tank.online ? 'red' : 'gray'}>
          <StatusDot kind={_isVirtualEM ? 'amber' : controlsReady ? 'green' : !tank.online ? 'red' : 'gray'} size={6} pulse={!_isVirtualEM && controlsReady}/>
          {_isVirtualEM ? 'Virtual' : !tank.online ? 'Offline' : !tank.mqttReceived ? 'Waiting…' : 'Online'}
        </Badge>
      </div>

      {/* Tab bar */}
      <div style={{ display:'flex', borderBottom:'1px solid var(--border)', background:'var(--bg)',
        position:'sticky', top:53, zIndex:9 }}>
        {tabs.map(t => (
          <button key={t.key} onClick={() => setTab(t.key)} style={{
            flex:1, padding:'12px 0', border:'none', background:'none', cursor:'pointer',
            fontSize:13, fontWeight: tab === t.key ? 700 : 500,
            color: tab === t.key ? 'var(--cyan)' : 'var(--text-3)',
            borderBottom: `2px solid ${tab === t.key ? 'var(--cyan)' : 'transparent'}`,
            transition: 'all 150ms',
          }}>{t.label}</button>
        ))}
      </div>

      <div style={{ padding: '16px 16px 0' }}>

        {tab === 'monitor' && (
          <>
            {/* Big watts hero */}
            <Card style={{ padding: '28px 16px 24px', textAlign: 'center', marginBottom: 14 }}>
              <div className="num" style={{ fontSize: 60, fontWeight: 700, color: 'var(--cyan)', lineHeight: 1, letterSpacing: -2 }}>
                {controlsReady ? Math.round(tank.power ?? 0).toLocaleString() : '—'}
              </div>
              <div style={{ fontSize: 13, color: 'var(--text-3)', marginTop: 6, letterSpacing: 0.4 }}>WATTS</div>

              <div style={{ display: 'flex', justifyContent: 'center', gap: 0, marginTop: 22, borderTop: '1px solid var(--border)', paddingTop: 18 }}>
                {[
                  { label: 'VOLTS',   val: controlsReady ? `${Math.round(tank.voltage ?? 0)}` : '—',         unit: 'V'  },
                  { label: 'AMPS',    val: controlsReady ? `${(tank.current ?? 0).toFixed(2)}` : '—',        unit: 'A'  },
                  { label: 'P.F.',    val: controlsReady ? `${(tank.pf ?? 0).toFixed(2)}` : '—',             unit: ''   },
                  { label: 'FREQ',    val: controlsReady ? `${(tank.freq ?? 0).toFixed(1)}` : '—',           unit: 'Hz' },
                ].map(({ label, val, unit }, idx, arr) => (
                  <div key={label} style={{
                    flex: 1, textAlign: 'center',
                    borderRight: idx < arr.length - 1 ? '1px solid var(--border)' : 'none',
                    padding: '0 8px',
                  }}>
                    <div className="num" style={{ fontSize: 20, fontWeight: 600 }}>{val}<span style={{ fontSize: 11, color: 'var(--text-3)', marginLeft: 2 }}>{unit}</span></div>
                    <div style={{ fontSize: 9, color: 'var(--text-3)', letterSpacing: 0.8, marginTop: 4 }}>{label}</div>
                  </div>
                ))}
              </div>
            </Card>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 }}>
              <Metric icon="zap"      label="Device Total"   value={controlsReady ? (tank.energyToday ?? 0).toFixed(3) : '—'} unit="kWh"/>
              <Metric icon="bolt"     label="Today's Energy" value={todayKwh.toFixed(3)} unit="kWh"/>
              <Metric icon="activity" label="Monthly Energy" value={monthKwh.toFixed(2)}  unit="kWh"/>
              <Metric icon="sparkle"  label="Est. Bill"      value={`${currency}${monthBill.toFixed(0)}`}/>
            </div>

            <SectionTitle>Live Power — last 5 min</SectionTitle>
            <Card style={{ padding: '14px 8px 8px 0', marginBottom: 8 }}>
              {pwrBuf.length < 2 ? (
                <div style={{ height: 140, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <div style={{
                    padding: '8px 14px', borderRadius: 999, fontSize: 12, fontWeight: 600, color: 'var(--cyan)',
                    border: '1px solid rgba(0,212,255,0.28)',
                    background: 'rgba(0,212,255,0.08)', letterSpacing: 0.2,
                  }}>Waiting for live data…</div>
                </div>
              ) : (
                <ResponsiveContainer width="100%" height={140}>
                  <AreaChart data={pwrBuf} margin={{ top: 4, right: 12, bottom: 0, left: 8 }}>
                    <defs>
                      <linearGradient id="emPwrFill" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%"   stopColor="#00d4ff" stopOpacity={0.45}/>
                        <stop offset="100%" stopColor="#00d4ff" stopOpacity={0}/>
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" vertical={false}/>
                    <XAxis dataKey="t" tickLine={false} axisLine={false}
                      tick={{ fontSize: 9, fill: 'var(--text-3)' }} interval={9}/>
                    <YAxis tickLine={false} axisLine={false} width={40}
                      tick={{ fontSize: 9, fill: 'var(--text-3)' }}
                      tickFormatter={v => `${v}W`}/>
                    <Tooltip
                      contentStyle={{ background: 'rgba(15,20,48,0.95)', border: '1px solid rgba(255,255,255,0.12)', borderRadius: 10, fontSize: 12 }}
                      formatter={v => [`${v} W`, 'Power']}
                    />
                    <Area type="monotone" dataKey="w" stroke="var(--cyan)" strokeWidth={2} fill="url(#emPwrFill)" dot={false}/>
                  </AreaChart>
                </ResponsiveContainer>
              )}
            </Card>
          </>
        )}

        {tab === 'history' && (
          <>
            <Card style={{ padding: 0, marginBottom: 14, display: 'flex', overflow: 'hidden' }}>
              <div style={{ flex: 1, padding: '14px 10px', borderRight: '1px solid var(--border)', textAlign: 'center' }}>
                <div style={{ fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: 0.6, marginBottom: 5 }}>Today</div>
                <div className="num" style={{ fontSize: 20, fontWeight: 700, color: 'var(--cyan)' }}>{todayKwh.toFixed(3)}</div>
                <div style={{ fontSize: 10, color: 'var(--text-3)', marginTop: 2 }}>kWh</div>
              </div>
              <div style={{ flex: 1, padding: '14px 10px', borderRight: '1px solid var(--border)', textAlign: 'center' }}>
                <div style={{ fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: 0.6, marginBottom: 5 }}>This Month</div>
                <div className="num" style={{ fontSize: 20, fontWeight: 700, color: 'var(--cyan)' }}>{monthKwh.toFixed(2)}</div>
                <div style={{ fontSize: 10, color: 'var(--text-3)', marginTop: 2 }}>kWh</div>
              </div>
              <div style={{ flex: 1, padding: '14px 10px', textAlign: 'center' }}>
                <div style={{ fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: 0.6, marginBottom: 5 }}>Est. Bill</div>
                <div className="num" style={{ fontSize: 20, fontWeight: 700, color: 'var(--text)' }}>{currency}{monthBill.toFixed(0)}</div>
                <div style={{ fontSize: 10, color: 'var(--text-3)', marginTop: 2 }}>{currency}{tariff}/kWh</div>
              </div>
            </Card>

            <Card style={{ padding: 16, marginBottom: 14 }}>
              <div style={{ display: 'flex', gap: 3, background: 'rgba(255,255,255,0.04)', borderRadius: 10, padding: 3, marginBottom: 14 }}>
                {['day', 'month', 'year'].map(p => (
                  <button key={p} onClick={() => setPeriod(p)} style={{
                    flex: 1, padding: '7px 0', borderRadius: 8, border: 'none', cursor: 'pointer',
                    background: period === p ? 'rgba(255,255,255,0.12)' : 'transparent',
                    color: period === p ? 'var(--text)' : 'var(--text-3)',
                    fontWeight: period === p ? 600 : 400, fontSize: 13,
                    transition: 'all 160ms ease',
                  }}>{p.charAt(0).toUpperCase() + p.slice(1)}</button>
                ))}
              </div>

              <div className="num" style={{ fontSize: 30, fontWeight: 700, color: 'var(--cyan)', lineHeight: 1 }}>
                {periodTotal.toFixed(3)}
                <span style={{ fontSize: 14, color: 'var(--text-2)', fontWeight: 400, marginLeft: 6 }}>kWh</span>
              </div>
              <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 4, marginBottom: 14 }}>{periodLabel}</div>

              <ResponsiveContainer width="100%" height={180}>
                <BarChart data={chartData} margin={{ top: 4, right: 0, bottom: 0, left: -12 }}>
                  <CartesianGrid strokeDasharray="3 3" vertical={false}/>
                  <XAxis dataKey="label" tickLine={false} axisLine={false}
                    tick={{ fontSize: 10, fill: 'var(--text-3)' }}
                    interval={period === 'day' ? 3 : period === 'month' ? 4 : 0}/>
                  <YAxis tickLine={false} axisLine={false} width={36}
                    tick={{ fontSize: 10, fill: 'var(--text-3)' }}
                    tickFormatter={v => v >= 1 ? v.toFixed(1) : v.toFixed(2)}/>
                  <Tooltip
                    contentStyle={{ background: 'rgba(15,20,48,0.95)', border: '1px solid rgba(255,255,255,0.12)', borderRadius: 10, fontSize: 12 }}
                    formatter={v => [`${Number(v).toFixed(3)} kWh`, 'Energy']}
                    labelStyle={{ color: '#fff', fontWeight: 600 }}
                  />
                  <Bar dataKey="kwh" fill="var(--cyan)" opacity={0.85} radius={[3, 3, 0, 0]}/>
                </BarChart>
              </ResponsiveContainer>
            </Card>

            <SectionTitle>Energy Calendar</SectionTitle>
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 14, fontSize: 11, color: 'var(--text-3)', alignItems: 'center' }}>
              {[
                { bg: '#1d4ed8',              label: '≤ 1 kWh' },
                { bg: '#b45309',              label: '1–2 kWh' },
                { bg: '#9f1239',              label: '> 2 kWh' },
                { bg: 'rgba(255,255,255,0.05)', label: 'No data' },
              ].map(({ bg, label }) => (
                <span key={label} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: bg, flexShrink: 0 }}/>
                  {label}
                </span>
              ))}
            </div>
            {calMonths.map(({ name, fdow, days, mKwh, mStr }) => (
              <div key={mStr} style={{ marginBottom: 24 }}>
                <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4 }}>{name}</div>
                <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 10, display: 'flex', gap: 16 }}>
                  <span>Used <span style={{ color: 'var(--cyan)', fontWeight: 600 }}>{mKwh.toFixed(2)} kWh</span></span>
                  <span>Bill <span style={{ color: 'var(--text)', fontWeight: 600 }}>{currency}{(mKwh * tariff).toFixed(0)}</span></span>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 3 }}>
                  {['Su','Mo','Tu','We','Th','Fr','Sa'].map(d => (
                    <div key={d} style={{ textAlign: 'center', fontSize: 9, color: 'var(--text-3)', paddingBottom: 4 }}>{d}</div>
                  ))}
                  {Array(fdow).fill(null).map((_, i) => <div key={`ep${i}`}/>)}
                  {days.map(({ d, kwh }) => {
                    const bg = kwh == null ? 'rgba(255,255,255,0.05)'
                             : kwh === 0   ? 'rgba(255,255,255,0.03)'
                             : kwh <= 1    ? '#1d4ed8'
                             : kwh <= 2    ? '#b45309'
                             :               '#9f1239';
                    return (
                      <div key={d} style={{
                        aspectRatio: '1', borderRadius: 6, background: bg, position: 'relative',
                        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                      }}>
                        <span style={{ position: 'absolute', top: 2, left: 3, fontSize: 7, color: 'rgba(255,255,255,0.5)' }}>{d}</span>
                        {kwh != null && kwh > 0 && (
                          <span style={{ fontWeight: 700, color: '#fff', fontSize: 7, marginTop: 4 }}>{kwh.toFixed(1)}</span>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
          </>
        )}

        {tab === 'settings' && (
          <>
            <SectionTitle>Protection Thresholds</SectionTitle>
            <Card style={{ padding: 16 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <NumField label="V Low Alarm"   suffix="V" value={draftSet.vLow}     onChange={v => setDraftSet(s => ({ ...s, vLow: v }))}/>
                <NumField label="V High Alarm"  suffix="V" value={draftSet.vHigh}    onChange={v => setDraftSet(s => ({ ...s, vHigh: v }))}/>
                <NumField label="Current Limit" suffix="A" value={draftSet.iMax}     onChange={v => setDraftSet(s => ({ ...s, iMax: v }))}/>
                <NumField label="Power Limit"   suffix="W" value={draftSet.powerMax} onChange={v => setDraftSet(s => ({ ...s, powerMax: v }))}/>
              </div>
              <div style={{ marginTop: 14, padding: '10px 12px', borderRadius: 10, background: 'rgba(255,171,64,0.08)', border: '1px solid rgba(255,171,64,0.2)' }}>
                <div style={{ fontSize: 11, color: 'var(--amber)', fontWeight: 500, marginBottom: 2 }}>Electricity tariff</div>
                <div style={{ fontSize: 11, color: 'var(--text-3)' }}>Set in <span style={{ color: 'var(--cyan)' }}>Settings → Units &amp; Display → Electricity rate</span></div>
              </div>
            </Card>
            <Btn full variant="primary" icon="check" onClick={saveSetpoints} style={{ marginTop: 16 }}>Save</Btn>
          </>
        )}
      </div>
    </div>
  );
};

window.EmDetail = EmDetail;
