// Auto screen — Gridome Hour v2 aesthetic.
// EVCC loadpoint layout logic, fully reskinned.
// Sources: ocpp_server.py, ev_scheduler.py, charge_plans.py, state.ev_status
// OCPP writes can go live per-control — all locked for now, unlock per-button.

// ── EV state per scenario ─────────────────────────────────────────────────
const EV_LIVE = {
  midday:    {
    ocppStatus: 'Available', chargeKw: 0, sessionKwh: 0, sessionMin: 0,
    soc: 62, socLimit: 80, range: 280, solar: 0, avgPriceGr: 0, sessionZl: 0,
    profile: null,
  },
  evening:   {
    ocppStatus: 'SuspendedEVSE', chargeKw: 0, sessionKwh: 0, sessionMin: 12,
    soc: 54, socLimit: 80, range: 243, solar: 0, avgPriceGr: 0, sessionZl: 0,
    profile: 'auto.profile.waiting',
  },
  overnight: {
    ocppStatus: 'Charging', chargeKw: 7.0, sessionKwh: 12.4, sessionMin: 106,
    soc: 71, socLimit: 80, range: 320, solar: 0, avgPriceGr: 29, sessionZl: 3.60,
    profile: 'auto.profile.charging',
  },
  morning:   {
    ocppStatus: 'Finishing', chargeKw: 0, sessionKwh: 18.2, sessionMin: 274,
    soc: 80, socLimit: 80, range: 360, solar: 12, avgPriceGr: 31, sessionZl: 5.64,
    profile: 'auto.profile.done',
  },
};

const OCPP_LABEL = {
  Available:    { key: 'auto.status.available',  color: null },
  Preparing:    { key: 'auto.status.available',  color: null },
  Charging:     { key: 'auto.status.charging',   color: 'blue' },
  SuspendedEVSE:{ key: 'auto.status.suspended',  color: 'amber' },
  SuspendedEV:  { key: 'auto.status.suspended',  color: 'amber' },
  Finishing:    { key: 'auto.status.finishing',  color: 'green' },
};

// Weekday charge plan stub (from charge_plans.py repeating plans)
const WEEKLY_PLAN = [
  { dayKey: 0, window: [1, 6], active: true  },
  { dayKey: 1, window: [1, 6], active: true  },
  { dayKey: 2, window: [2, 5], active: true  },
  { dayKey: 3, window: [1, 6], active: true  },
  { dayKey: 4, window: [1, 5], active: true  },
  { dayKey: 5, window: [0, 0], active: false },
  { dayKey: 6, window: [0, 0], active: false },
];

// Smart Charging profile: 24h amp curve (stub from OCPP TxDefaultProfile)
function buildChargingCurve(scenario) {
  const s = SCENARIOS[scenario];
  return Array.from({ length: 24 }, (_, h) => {
    const absH = (Math.floor(s.hour) + h) % 24;
    if (scenario === 'overnight' && absH >= 1 && absH <= 6) return 32; // full 32A
    if (scenario === 'overnight' && absH === 0) return 16;              // ramp up
    if (scenario === 'evening' && absH >= 23) return 32;                // scheduled
    return 0;
  });
}

// Dynamic load balancing (whole-house load breakdown)
function buildLoadBalance(s) {
  const circuit = 25 * 230 * 3 / 1000; // 25A 3-phase = 17.25 kW
  const evLoad = Math.abs(s.ev) || 0;
  const homeLoad = s.home;
  const battLoad = s.battery < 0 ? -s.battery : 0;
  const other = Math.max(0, circuit - evLoad - homeLoad - battLoad - 2);
  const headroom = Math.max(0, circuit - evLoad - homeLoad - battLoad);
  return { circuit, evLoad, homeLoad, battLoad, other, headroom };
}

// ── Main component ─────────────────────────────────────────────────────────
function V2Auto({ s }) {
  const { t } = useLocale();
  const ev = EV_LIVE[s.key];
  const status = OCPP_LABEL[ev.ocppStatus];
  const statusLabel = t(status.key);
  const statusColor = status.color ? T[status.color] : T.textMuted;
  const isCharging = ev.ocppStatus === 'Charging';
  const isDone = ev.ocppStatus === 'Finishing';
  const isConnected = ev.ocppStatus !== 'Available';

  const liveKw = useLiveJitter(ev.chargeKw, 0.025);
  const curve = buildChargingCurve(s.key);
  const lb = buildLoadBalance(s);

  // ETA calc: remaining kWh ÷ charge rate
  const remainKwh = ((ev.socLimit - ev.soc) / 100 * 77).toFixed(1); // 77 kWh capacity Enyaq
  const etaMin = ev.chargeKw > 0 ? Math.round((parseFloat(remainKwh) / ev.chargeKw) * 60) : 0;
  const etaStr = etaMin > 0
    ? `${String(Math.floor((Math.floor(s.hour) + Math.floor(etaMin/60)) % 24)).padStart(2,'0')}:${String(etaMin%60).padStart(2,'0')}`
    : null;

  // Croissant
  const rangeKm = Math.round((ev.sessionKwh / 77) * 570); // 570km WLTP
  const kmFood = rangeKm > 0
    ? `🚗 ≈ ${rangeKm} km zasięgu, koszt ${ev.sessionZl.toFixed(2)} zł`
    : null;

  return (
    <div>
      {/* Row 1: hero + vehicle */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 18, marginBottom: 18 }}>

        {/* Hero card */}
        <Surface padding={32} style={{
          background: isCharging
            ? `linear-gradient(135deg, ${T.tintBlue}, ${T.surface})`
            : isDone
            ? `linear-gradient(135deg, ${T.tintGreen}, ${T.surface})`
            : T.surface,
          border: `1px solid ${isCharging ? T.blue + '44' : isDone ? T.green + '44' : T.border}`,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <span style={{
              width: 8, height: 8, borderRadius: '50%', background: statusColor,
              display: 'inline-block',
              boxShadow: isCharging ? `0 0 12px ${statusColor}` : 'none',
              animation: isCharging ? 'dot-pulse 1.6s ease-out infinite' : 'none',
            }}/>
            <SurfaceLabel color={statusColor}>{statusLabel}</SurfaceLabel>
            <span style={{ marginLeft: 'auto', fontSize: 10, color: T.textMuted, fontFamily: T.fontMono }}>
              EO EM301 · OCPP 1.6 · WSS
            </span>
          </div>

          {isCharging ? (
            <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',
              }}>{liveKw.toFixed(1)}</span>
              <span style={{ fontSize: 26, color: T.textSecondary, fontWeight: 600 }}>kW</span>
            </div>
          ) : (
            <div style={{
              fontFamily: T.fontBrand, fontWeight: 700, fontSize: 72,
              letterSpacing: -2, color: statusColor, lineHeight: 1, marginBottom: 8,
            }}>{statusLabel}</div>
          )}

          {/* Session stats strip */}
          {isConnected && (
            <div style={{
              marginTop: 20, paddingTop: 16, borderTop: `1px solid ${T.border}`,
              display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14,
            }}>
              <AutoStat label={t('auto.labelEnergy')} value={ev.sessionKwh.toFixed(1)} unit="kWh" color={T.blue}/>
              <AutoStat label={t('auto.labelTime')} value={`${Math.floor(ev.sessionMin/60)}h${ev.sessionMin%60}m`} unit="" color={T.textPrimary}/>
              {etaStr
                ? <AutoStat label={t('auto.sessionEnd')} value={etaStr} unit="" color={T.green}/>
                : <AutoStat label={t('home.flow.solar')} value={`${ev.solar}%`} unit="" color={T.amber}/>
              }
              <AutoStat label={t('auto.sessionAvgPrice')} value={ev.avgPriceGr > 0 ? ev.avgPriceGr : '—'} unit={ev.avgPriceGr > 0 ? "gr/kWh" : ""} color={T.textMuted}/>
            </div>
          )}

          {/* Croissant */}
          {kmFood && (
            <div style={{
              marginTop: 14, padding: '10px 14px',
              background: `${T.green}14`, border: `1px solid ${T.green}30`,
              borderRadius: 10, fontSize: 12, color: T.textSecondary, lineHeight: 1.5,
            }}>
              {t('auto.croissant', { kwh: ev.sessionKwh.toFixed(1), km: rangeKm, cost: ev.sessionZl.toFixed(2) })}
            </div>
          )}
        </Surface>

        {/* Vehicle card */}
        <Surface padding={24}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12,
              background: isCharging ? `${T.blue}22` : T.raised,
              border: `1px solid ${isCharging ? T.blue + '44' : T.border}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><LI name="car" size={22} color={ev.charging ? T.blue : T.textMuted}/></div>
            <div>
              <div style={{ fontFamily: T.fontBrand, fontSize: 16, fontWeight: 700 }}>Škoda Enyaq iV 80</div>
              <div style={{ fontSize: 11, color: T.textMuted, marginTop: 2 }}>77 kWh · WLTP 570 km</div>
            </div>
          </div>

          {/* SOC display */}
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 12 }}>
            <span style={{ fontFamily: T.fontBrand, fontWeight: 700, fontSize: 56, lineHeight: 0.9, fontVariantNumeric: 'tabular-nums' }}>
              {ev.soc}
            </span>
            <span style={{ fontSize: 18, color: T.textSecondary, fontWeight: 600 }}>%</span>
            <span style={{ fontSize: 12, color: T.textMuted, marginLeft: 6 }}>→ limit {ev.socLimit}%</span>
          </div>

          {/* SOC bar */}
          <div style={{ height: 8, background: T.raised, borderRadius: 99, overflow: 'visible', position: 'relative', marginBottom: 6 }}>
            <div style={{
              width: `${ev.soc}%`, height: '100%', borderRadius: 99, transition: 'width 600ms',
              background: isDone ? T.green : isCharging ? T.blue : T.textMuted,
            }}/>
            <div style={{ position: 'absolute', left: `${ev.socLimit}%`, top: -3, width: 1.5, height: 14, background: T.textSecondary }}/>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: T.fontMono, fontSize: 10, color: T.textMuted, marginBottom: 20 }}>
            <span>0</span><span>Limit {ev.socLimit}%</span><span>100</span>
          </div>

          {/* Range + cost */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div style={{ background: T.raised, borderRadius: 10, padding: '10px 12px', border: `1px solid ${T.border}` }}>
              <SurfaceLabel style={{ fontSize: 9, marginBottom: 5 }}>{t('auto.range')}</SurfaceLabel>
              <div style={{ fontFamily: T.fontMono, fontSize: 18, fontWeight: 700, color: T.textPrimary }}>{ev.range} <span style={{ fontSize: 11, color: T.textMuted }}>km</span></div>
            </div>
            <div style={{ background: T.raised, borderRadius: 10, padding: '10px 12px', border: `1px solid ${T.border}` }}>
              <SurfaceLabel style={{ fontSize: 9, marginBottom: 5 }}>{t('auto.sessionCost')}</SurfaceLabel>
              <div style={{ fontFamily: T.fontMono, fontSize: 18, fontWeight: 700, color: T.green }}>{ev.sessionZl > 0 ? `${ev.sessionZl.toFixed(2)}` : '—'} <span style={{ fontSize: 11, color: T.textMuted }}>zł</span></div>
            </div>
          </div>

          {ev.profile && (
            <div style={{ marginTop: 14, fontSize: 11, color: T.textMuted, fontFamily: T.fontMono, padding: '8px 10px', background: T.raised, borderRadius: 8, border: `1px solid ${T.border}` }}>
              {t(ev.profile) || ev.profile}
            </div>
          )}
        </Surface>
      </div>

      {/* Row 2: Smart Charging curve + load balance */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18, marginBottom: 18 }}>
        <Surface>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
            <SurfaceLabel>{t('auto.smartTitle')}</SurfaceLabel>
            <span style={{ fontSize: 10, color: T.textMuted, fontFamily: T.fontMono }}>TxDefaultProfile · 32A max</span>
          </div>
          <ChargingProfileCurve curve={curve} scenario={s}/>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontFamily: T.fontMono, fontSize: 10, color: T.textMuted }}>
            <span>{t('auto.now')}</span>
            {[6,12,18,23].map(h => <span key={h}>{String((Math.floor(s.hour)+h)%24).padStart(2,'0')}:00</span>)}
          </div>
          <div style={{ marginTop: 10, fontSize: 11, color: T.textMuted, lineHeight: 1.5 }}>
            {t('auto.profileDesc')}
          </div>
        </Surface>

        <Surface>
          <SurfaceLabel style={{ marginBottom: 14 }}>{t('auto.loadBalanceTitle')}</SurfaceLabel>
          <LoadBalanceBar lb={lb}/>
          <div style={{ marginTop: 16, fontSize: 11, color: T.textMuted, lineHeight: 1.5 }}>
            Headroom do{' '}
            <strong style={{ color: headroomColor(lb.headroom, lb.circuit) }}>
              {lb.headroom.toFixed(1)} kW
            </strong>
            {' '}— {t('auto.headroomNote')} {' '}
            <span style={{ fontFamily: T.fontMono }}>headroom ≤ 1.4 kW</span>.
          </div>
        </Surface>
      </div>

      {/* Row 3: Weekly charge plan */}
      <Surface>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <SurfaceLabel>{t('auto.weeklyTitle')}</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('auto.readOnlyBadge')}</span>
        </div>
        <WeeklyPlanStrip plan={WEEKLY_PLAN}/>
      </Surface>
    </div>
  );
}

// ── Smart Charging profile curve ──────────────────────────────────────────
function ChargingProfileCurve({ curve, scenario }) {
  const nowIdx = 0;
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 2, height: 60 }}>
      {curve.map((amps, i) => {
        const h = amps > 0 ? 8 + (amps / 32) * 50 : 4;
        const isNow = i === nowIdx;
        const active = amps > 0;
        return (
          <div key={i} style={{
            flex: 1, height: h, borderRadius: 2,
            background: active ? (isNow ? T.blue : `${T.blue}55`) : T.raised,
            border: isNow ? `1px solid ${T.textSecondary}44` : 'none',
            boxShadow: isNow && active ? `0 0 12px ${T.blue}66` : 'none',
          }}/>
        );
      })}
    </div>
  );
}

// ── Dynamic load balance bar ─────────────────────────────────────────────
function LoadBalanceBar({ lb }) {
  const { t } = useLocale();
  const segs = [
    { label: t('home.flow.ev'),      val: lb.evLoad,   color: T.blue },
    { label: t('home.flow.home'),    val: lb.homeLoad, color: T.textSecondary },
    { label: t('home.flow.battery'), val: lb.battLoad, color: T.green },
    { label: 'Headroom',val: lb.headroom, color: T.raised, muted: true },
  ].filter(s => s.val > 0);

  return (
    <div>
      <div style={{ display: 'flex', height: 28, borderRadius: 8, overflow: 'hidden', gap: 1 }}>
        {segs.map((seg, i) => (
          <div key={i} style={{
            flex: seg.val,
            background: seg.muted ? T.raised : seg.color,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 10, fontWeight: 700, color: T.bg,
            border: seg.muted ? `1px solid ${T.border}` : 'none',
          }}>
            {seg.val >= 1 && !seg.muted ? `${seg.val.toFixed(1)}` : ''}
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 14, marginTop: 8, flexWrap: 'wrap' }}>
        {segs.map((seg, i) => (
          <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, color: T.textMuted }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: seg.muted ? T.border : seg.color, display: 'inline-block' }}/>
            {seg.label} · <span style={{ color: seg.muted ? T.textMuted : T.textPrimary, fontFamily: T.fontMono }}>{seg.val.toFixed(1)} kW</span>
          </span>
        ))}
      </div>
    </div>
  );
}

function headroomColor(headroom, circuit) {
  const ratio = headroom / circuit;
  if (ratio > 0.3) return T.green;
  if (ratio > 0.15) return T.amber;
  return T.red;
}

// ── Weekly charge plan strip ──────────────────────────────────────────────
function WeeklyPlanStrip({ plan }) {
  const { t } = useLocale();
  const totalH = 24;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 8 }}>
      {plan.map((day, i) => {
        const [start, end] = day.window;
        const height = day.active ? Math.max(4, ((end - start) / 8) * 80) : 0;
        const topPct = day.active ? (start / totalH) * 100 : 0;

        return (
          <div key={i}>
            <div style={{
              height: 80, background: T.raised, borderRadius: 8,
              border: `1px solid ${T.border}`, position: 'relative', overflow: 'hidden',
            }}>
              {day.active && (
                <div style={{
                  position: 'absolute', left: 4, right: 4,
                  top: `${topPct}%`, height: height,
                  background: `${T.blue}88`, borderRadius: 4,
                  boxShadow: `0 0 8px ${T.blue}44`,
                }}/>
              )}
              {/* midnight line */}
              <div style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 1, background: T.border }}/>
            </div>
            <div style={{ textAlign: 'center', marginTop: 6, fontSize: 10, color: day.active ? T.textSecondary : T.textMuted, fontWeight: 600 }}>
              {t('auto.day.' + day.dayKey)}
            </div>
            {day.active && (
              <div style={{ textAlign: 'center', fontSize: 9, color: T.textMuted, fontFamily: T.fontMono }}>
                {String(start).padStart(2,'0')}–{String(end).padStart(2,'0')}h
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ── AutoStat atom ──────────────────────────────────────────────────────────
function AutoStat({ label, value, unit, color }) {
  return (
    <div>
      <SurfaceLabel style={{ fontSize: 9, marginBottom: 5 }}>{label}</SurfaceLabel>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 3 }}>
        <span style={{ fontFamily: T.fontMono, fontSize: 18, fontWeight: 700, color, fontVariantNumeric: 'tabular-nums' }}>{value}</span>
        {unit && <span style={{ fontSize: 10, color: T.textMuted }}>{unit}</span>}
      </div>
    </div>
  );
}

Object.assign(window, {
  V2Auto, AutoStat, ChargingProfileCurve, LoadBalanceBar, WeeklyPlanStrip,
  headroomColor, EV_LIVE, OCPP_LABEL, WEEKLY_PLAN, buildChargingCurve, buildLoadBalance,
});
