// Battery screen — Gridome Hour v2 style.
// Ports EVCC's /battery layout logic (priority zones, SOC display) with Gridome's
// own aesthetic. All writes locked — GRIDOME_BATTERY_LIVE unset on pilot2.

// Stub priority settings (would come from state.battery_settings in real backend)
const BATTERY_STUB = {
  bufferSoc: 80,     // above this → charge EVs preferentially
  prioritySoc: 20,   // below this → reserve for home backup
  capacity: 10.24,   // kWh (Deye BOS-G × 2, pilot2) — not yet in state, hardcoded
  devices: [
    { name: 'BOS-G #1', soc: null, capacity: 5.12 },
    { name: 'BOS-G #2', soc: null, capacity: 5.12 },
  ],
};

function V2Battery({ s }) {
  const { t } = useLocale();
  // Live values from state.inverter (real pilot2 registers 586/588/590/591)
  const soc = s.batterySOC;                         // battery_soc_pct
  const powerKw = s.battery;                         // battery_power_w converted to kW (+ = charging)
  const powerW = Math.round(powerKw * 1000);
  const voltage = 51.2 + (soc / 100) * 3.8;         // ~51–55V realistic for LFP, stub (no battery_voltage_v in scenarios)
  const estimatedKwh = ((soc / 100) * BATTERY_STUB.capacity).toFixed(1);

  const isCharging = powerKw < 0;                    // sign convention: negative battery = charging (per shared.jsx)
  const isDischarging = powerKw > 0;
  const isIdle = Math.abs(powerKw) < 0.05;

  const statusColor = isCharging ? T.green : isDischarging ? T.blue : T.textMuted;
  const statusLabel = isCharging ? t('battery.status.charging') : isDischarging ? t('battery.status.discharging') : t('battery.status.idle');

  // Jitter on power
  const livePower = useLiveJitter(powerW, 0.03);

  return (
    <div>
      {/* Read-only notice */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, marginBottom: 22,
        padding: '10px 14px', background: T.raised,
        borderRadius: 10, border: `1px solid ${T.border}`,
        fontSize: 12, color: T.textMuted,
      }}>
        <span style={{
          width: 7, height: 7, borderRadius: '50%',
          background: T.amber, flexShrink: 0,
        }}/>
        <span>
          <strong style={{ color: T.textSecondary, fontWeight: 600 }}>Read-only — </strong>
          Modbus writes locked until <code style={{ fontFamily: T.fontMono, fontSize: 11, color: T.amber }}>GRIDOME_BATTERY_LIVE=1</code> is set {t('battery.readOnlyNote')} (2× Deye BOS-G, registers 586–591).
        </span>
      </div>

      {/* Row 1 — hero SOC + priority zones */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.15fr 1fr', gap: 18, marginBottom: 18 }}>

        {/* Hero SOC card */}
        <Surface padding={32}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
            <span style={{
              width: 8, height: 8, borderRadius: '50%', background: statusColor,
              display: 'inline-block', flexShrink: 0,
              boxShadow: !isIdle ? `0 0 10px ${statusColor}` : 'none',
            }}/>
            <SurfaceLabel color={statusColor}>{statusLabel}</SurfaceLabel>
          </div>

          {/* Giant SOC number */}
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, lineHeight: 1 }}>
            <span style={{
              fontFamily: T.fontBrand, fontWeight: 700, fontSize: 148,
              letterSpacing: -6, color: T.textPrimary, fontVariantNumeric: 'tabular-nums',
            }}>{soc}</span>
            <span style={{ fontSize: 26, color: T.textSecondary, fontWeight: 600 }}>%</span>
          </div>

          {/* Horizontal SOC bar */}
          <div style={{ marginTop: 16, height: 8, background: T.raised, borderRadius: 99, overflow: 'hidden', position: 'relative' }}>
            <div style={{
              width: `${soc}%`, height: '100%', borderRadius: 99, transition: 'width 600ms',
              background: soc > 60 ? T.green : soc > 30 ? T.blue : T.orange,
            }}/>
          </div>
          <div style={{
            display: 'flex', justifyContent: 'space-between', marginTop: 6,
            fontFamily: T.fontMono, fontSize: 10, color: T.textMuted,
          }}>
            <span>0%</span>
            <span style={{ color: T.textSecondary }}>↓ {t('battery.reserveZone')} {BATTERY_STUB.prioritySoc}%</span>
            <span style={{ color: T.textSecondary }}>{t('battery.bufferZone')} ↑ {BATTERY_STUB.bufferSoc}%</span>
            <span>100%</span>
          </div>

          {/* Stats row */}
          <div style={{
            marginTop: 22, paddingTop: 18, borderTop: `1px solid ${T.border}`,
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16,
          }}>
            <BatteryStat
              label="Moc"
              value={isIdle ? '—' : `${isCharging ? '+' : '−'}${Math.abs(livePower).toFixed(0)}`}
              unit="W"
              color={statusColor}
            />
            <BatteryStat
              label="Napięcie"
              value={voltage.toFixed(1)}
              unit="V"
              color={T.textPrimary}
            />
            <BatteryStat
              label="Energia"
              value={estimatedKwh}
              unit={`/ ${BATTERY_STUB.capacity} kWh`}
              color={T.textPrimary}
            />
          </div>

          {/* 2 × BOS-G device breakdown */}
          <div style={{
            marginTop: 18, paddingTop: 14, borderTop: `1px solid ${T.border}`,
            display: 'flex', gap: 10,
          }}>
            {BATTERY_STUB.devices.map((d, i) => (
              <div key={i} style={{
                flex: 1, background: T.raised, borderRadius: 10, padding: '10px 12px',
                border: `1px solid ${T.border}`,
              }}>
                <div style={{ fontSize: 10, color: T.textMuted, fontWeight: 600, letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 6 }}>
                  {d.name}
                </div>
                <div style={{ fontFamily: T.fontMono, fontSize: 14, color: T.textSecondary }}>
                  {d.capacity} kWh
                </div>
                <div style={{
                  fontSize: 10, color: T.textMuted, marginTop: 4, display: 'flex', alignItems: 'center', gap: 5,
                }}>
                  <span style={{
                    display: 'inline-block', width: 6, height: 6, borderRadius: '50%',
                    background: T.amber,
                  }}/>
                  {t('battery.pendingPerUnit')}
                </div>
              </div>
            ))}
          </div>
        </Surface>

        {/* Priority zones — EVCC layout logic, Gridome skin */}
        <Surface padding={28}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 20 }}>
            <SurfaceLabel>{t('battery.zonesTitle')}</SurfaceLabel>
            <span style={{
              fontSize: 9, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase',
              color: T.amber, background: `${T.amber}18`,
              border: `1px solid ${T.amber}33`, padding: '3px 8px', borderRadius: 4,
            }}>{t('battery.readOnlyBadge')}</span>
          </div>

          <div style={{ display: 'flex', gap: 20, height: 320 }}>
            {/* Vertical zone bar */}
            <BatteryZoneBar soc={soc} bufferSoc={BATTERY_STUB.bufferSoc} prioritySoc={BATTERY_STUB.prioritySoc}/>

            {/* Legend */}
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', paddingTop: 4, paddingBottom: 4 }}>
              <ZoneLegendItem
                icon="zap" color={T.green}
                title={t('battery.bufferZone')}
                desc={t('battery.bufferDesc', { pct: BATTERY_STUB.bufferSoc })}
                soc={`${BATTERY_STUB.bufferSoc}%`}
                locked
              />
              <ZoneLegendItem
                icon="gauge" color={T.blue}
                title={t('battery.mixedZone')}
                desc={t('battery.mixedDesc', { low: BATTERY_STUB.prioritySoc, high: BATTERY_STUB.bufferSoc })}
                soc={`${BATTERY_STUB.prioritySoc}–${BATTERY_STUB.bufferSoc}%`}
                locked
              />
              <ZoneLegendItem
                icon="home" color={T.amber}
                title={t('battery.reserveZone')}
                desc={t('battery.reserveDesc', { pct: BATTERY_STUB.prioritySoc })}
                soc={`${BATTERY_STUB.prioritySoc}%`}
                locked
              />
            </div>
          </div>

          <div style={{
            marginTop: 18, paddingTop: 14, borderTop: `1px solid ${T.border}`,
            fontSize: 12, color: T.textMuted, lineHeight: 1.6,
          }}>
            {t('battery.strategyNote')} <strong style={{ color: T.textSecondary }}>{t('battery.strategyName')}</strong>.
          </div>
        </Surface>
      </div>

      {/* Row 2 — SOC history + grid charge stub */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18 }}>

        {/* SOC history — stub */}
        <Surface>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <SurfaceLabel>{t('battery.historyTitle')}</SurfaceLabel>
            <span style={{
              fontSize: 9, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase',
              color: T.blue, background: `${T.blue}18`,
              border: `1px solid ${T.blue}33`, padding: '3px 8px', borderRadius: 4,
            }}>{t('battery.historyBadge')}</span>
          </div>
          <SocHistoryStub soc={soc}/>
          <div style={{
            marginTop: 12, fontSize: 11, color: T.textMuted, lineHeight: 1.5,
          }}>
            {t('battery.historyNote')} Potrzebny <code style={{ fontFamily: T.fontMono, color: T.blue }}>energy_accumulator.py</code> → SOC snapshots co 15 min w <code style={{ fontFamily: T.fontMono, color: T.blue }}>soc_history.json</code>.
          </div>
        </Surface>

        {/* Grid charge strategy */}
        <Surface>
          <SurfaceLabel style={{ marginBottom: 16 }}>{t('battery.gridChargeTitle')}</SurfaceLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <GridChargeRow
              label={t('battery.priceTreshold')}
              value="≤ 45 gr/kWh"
              color={T.green}
              desc="Ładuj baterię gdy cena poniżej progu"
              locked
            />
            <GridChargeRow
              label={t('battery.targetSoc')}
              value="80%"
              color={T.blue}
              desc="Naładuj do tego poziomu podczas taniej okienki"
              locked
            />
            <GridChargeRow
              label="Okienko G14"
              value="Pstryk · dynamiczna"
              color={T.textSecondary}
              desc="Ceny godzinowe z API Pstryk"
            />
          </div>
          <div style={{
            marginTop: 20, paddingTop: 14, borderTop: `1px solid ${T.border}`,
            fontSize: 11, color: T.textMuted, lineHeight: 1.5,
          }}>
            {t('battery.gridLockedNote')} Logika istnieje w <code style={{ fontFamily: T.fontMono, color: T.textMuted }}>battery_orchestrator.py</code>.
          </div>
        </Surface>
      </div>
    </div>
  );
}

// ── Sub-components ─────────────────────────────────────────────────────────

function BatteryStat({ label, value, unit, color }) {
  return (
    <div>
      <SurfaceLabel style={{ fontSize: 9, marginBottom: 6 }}>{label}</SurfaceLabel>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
        <span style={{ fontFamily: T.fontMono, fontSize: 20, fontWeight: 600, color, fontVariantNumeric: 'tabular-nums' }}>
          {value}
        </span>
        <span style={{ fontSize: 11, color: T.textMuted }}>{unit}</span>
      </div>
    </div>
  );
}

function BatteryZoneBar({ soc, bufferSoc, prioritySoc }) {
  // Heights as % of 320px bar
  const topH = (100 - bufferSoc);       // buffer zone (green) — above bufferSoc
  const midH = (bufferSoc - prioritySoc); // mixed zone (blue) — between
  const botH = prioritySoc;             // reserve zone (amber) — below prioritySoc

  // SOC marker from top: (100 - soc)%
  const socTop = 100 - soc;

  return (
    <div style={{ width: 64, position: 'relative', height: '100%', flexShrink: 0 }}>
      {/* Zone segments */}
      <div style={{
        position: 'absolute', inset: 0, borderRadius: 12, overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
        border: `1px solid ${T.border}`,
      }}>
        {/* Top — buffer (green tint) */}
        <div style={{
          height: `${topH}%`, background: `${T.green}30`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          borderBottom: `1px dashed ${T.border}`,
        }}>
          {topH > 8 && <LI name="zap" size={16} color={T.green}/>}
        </div>
        {/* Mid — EV priority (blue tint) */}
        <div style={{
          height: `${midH}%`, background: `${T.blue}22`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          borderBottom: `1px dashed ${T.border}`,
        }}>
          {midH > 8 && <LI name="gauge" size={16} color={T.blue}/>}
        </div>
        {/* Bot — home reserve (amber tint) */}
        <div style={{
          height: `${botH}%`, background: `${T.amber}22`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {botH > 8 && <LI name="home" size={16} color={T.amber}/>}
        </div>
      </div>

      {/* SOC indicator line + pill */}
      <div style={{
        position: 'absolute', left: -8, right: -8, top: `${socTop}%`,
        transform: 'translateY(-50%)', zIndex: 2,
      }}>
        <div style={{ height: 2, background: T.textPrimary, borderRadius: 1, opacity: 0.9 }}/>
        <div style={{
          position: 'absolute', left: '50%', top: '50%',
          transform: 'translate(-50%, -50%)',
          background: T.textPrimary, color: T.bg,
          fontFamily: T.fontMono, fontWeight: 700, fontSize: 10,
          padding: '2px 6px', borderRadius: 99, whiteSpace: 'nowrap',
        }}>{soc}%</div>
      </div>
    </div>
  );
}

function ZoneLegendItem({ icon, color, title, desc, soc, locked }) {
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
      <IconBox name={icon} size={16} color={color} boxSize={32} radius={8}/>
      <div style={{ flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: T.textPrimary }}>{title}</span>
          <span style={{ fontFamily: T.fontMono, fontSize: 10, color, fontWeight: 700 }}>{soc}</span>
          {locked && (
            <LI name="lock" size={10} color={T.textMuted}/>
          )}
        </div>
        <div style={{ fontSize: 11, color: T.textMuted, lineHeight: 1.5 }}>{desc}</div>
      </div>
    </div>
  );
}

function SocHistoryStub({ soc }) {
  // Generate a plausible-looking SOC curve for the stub
  // Morning: low SOC, rises with solar midday, drops evening
  const hours = Array.from({ length: 24 }, (_, h) => {
    let v;
    if (h < 6)  v = 30 + h * 2;           // overnight charging
    if (h >= 6 && h < 8)  v = 38 + (h-6) * 5;
    if (h >= 8 && h < 14) v = 48 + (h-8) * 5;  // solar charging
    if (h >= 14 && h < 20) v = 78 - (h-14) * 4; // discharge evening
    if (h >= 20) v = 54 - (h-20) * 3;
    // Clamp
    v = Math.max(20, Math.min(95, v));
    return { h, v };
  });

  // Overlay current SOC at current hour
  const W = 600, H = 100, padY = 8;
  const pts = hours.map(({ h, v }) => ({
    x: (h / 23) * W,
    y: H - padY - ((v - 20) / 75) * (H - padY * 2),
  }));
  const path = pts.reduce((acc, { x, y }, i) => {
    if (i === 0) return `M${x} ${y}`;
    const prev = pts[i-1];
    const mx = (prev.x + x) / 2, my = (prev.y + y) / 2;
    return acc + ` Q${prev.x} ${prev.y} ${mx} ${my}`;
  }, '') + ` T${pts[23].x} ${pts[23].y}`;

  return (
    <div>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none" style={{ display: 'block', opacity: 0.5 }}>
        <defs>
          <linearGradient id="socGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={T.green} stopOpacity="0.35"/>
            <stop offset="100%" stopColor={T.green} stopOpacity="0"/>
          </linearGradient>
        </defs>
        {[25, 50, 75].map(pct => {
          const y = H - padY - ((pct - 20) / 75) * (H - padY * 2);
          return <line key={pct} x1={0} y1={y} x2={W} y2={y} stroke={T.border} strokeDasharray="2 4"/>;
        })}
        <path d={path + ` L${W} ${H} L0 ${H} Z`} fill="url(#socGrad)"/>
        <path d={path} fill="none" stroke={T.green} strokeWidth="2" strokeLinecap="round"/>
      </svg>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontFamily: T.fontMono, fontSize: 10, color: T.textMuted }}>
        <span>00:00</span><span>06:00</span><span>12:00</span><span>18:00</span><span>23:00</span>
      </div>
      <div style={{ marginTop: 6, fontSize: 10, color: T.textMuted, fontStyle: 'italic' }}>
        Stub — dane modelowane, nie z pilota. Po wdrożeniu historii backend wyświetli rzeczywiste dane.
      </div>
    </div>
  );
}

function GridChargeRow({ label, value, color, desc, locked }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
      padding: '12px 14px', background: T.raised, borderRadius: 10,
      border: `1px solid ${T.border}`,
    }}>
      <div>
        <div style={{ fontSize: 11, color: T.textMuted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 3 }}>{label}</div>
        <div style={{ fontSize: 11, color: T.textMuted, lineHeight: 1.4 }}>{desc}</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0, marginLeft: 12 }}>
        <span style={{ fontFamily: T.fontMono, fontSize: 13, fontWeight: 700, color }}>{value}</span>
        {locked && <span style={{ fontSize: 10, color: T.textMuted }}>🔒</span>}
      </div>
    </div>
  );
}

Object.assign(window, { V2Battery, BatteryZoneBar, BatteryStat, ZoneLegendItem, SocHistoryStub, GridChargeRow });
