// Gridome Hour v2 — Gridome design language, evcc-inspired structure.
// Teal primary, Space Grotesk, deep dark surfaces, tier colors: teal/blue/orange/red.

function HourV2App() {
  const [tab, setTab] = React.useState('home');
  const [scenario, setScenario] = React.useState(TWEAK_DEFAULTS.scenario || 'midday');
  const [safeMode, setSafeMode] = React.useState(false);
  const [showTweaks, setShowTweaks] = React.useState(false);

  React.useEffect(() => {
    const saved = localStorage.getItem('hourv2-tab');
    if (saved) setTab(saved);
    const savedS = localStorage.getItem('hourv2-scenario');
    if (savedS && SCENARIOS[savedS]) setScenario(savedS);
  }, []);

  React.useEffect(() => {
    localStorage.setItem('hourv2-tab', tab);
  }, [tab]);

  React.useEffect(() => {
    const onMsg = (e) => {
      if (!e.data) return;
      if (e.data.type === '__activate_edit_mode') setShowTweaks(true);
      if (e.data.type === '__deactivate_edit_mode') setShowTweaks(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const s = SCENARIOS[scenario];
  const tabs = [
    { key: 'home' },
    { key: 'plan' },
    { key: 'forecast' },
    { key: 'optimizer' },
    { key: 'battery' },
    { key: 'ev' },
    { key: 'sessions' },
    { key: 'devices' },
    { key: 'settings' },
  ];

  return (
    <LocaleProvider>
    <div style={{ minHeight: '100vh', background: T.bg, color: T.textPrimary, fontFamily: T.fontUI }}>
      <V2TopBar tabs={tabs} current={tab} setCurrent={setTab} safeMode={safeMode} />
      {safeMode && (
        <div style={{
          background: `${T.red}18`, color: T.red, padding: '9px 32px',
          fontSize: 11, fontWeight: 600, letterSpacing: 0.8,
          borderBottom: `1px solid ${T.red}33`, display: 'flex', alignItems: 'center', gap: 12,
          textTransform: 'uppercase',
        }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: T.red, display: 'inline-block' }} />
          Safe mode — hardware writes blocked
          <button onClick={() => setSafeMode(false)} style={{
            marginLeft: 'auto', background: 'transparent',
            border: `1px solid ${T.red}66`, color: T.red,
            padding: '3px 10px', borderRadius: 6, fontSize: 10, fontWeight: 700,
            cursor: 'pointer', letterSpacing: 0.5, textTransform: 'uppercase',
          }}>Lift</button>
        </div>
      )}

      <div style={{ padding: '28px 36px', maxWidth: 1440, margin: '0 auto' }}>
        {tab === 'home' && <V2Home s={s} safeMode={safeMode} setCurrent={setTab} />}
        {tab === 'plan' && <V2Plan s={s} setCurrent={setTab} />}
        {tab === 'forecast' && <V2Forecast s={s} />}
        {tab === 'optimizer' && <V2Optimizer s={s} />}
        {tab === 'battery' && <V2Battery s={s} />}
        {tab === 'ev' && <V2Auto s={s} />}
        {tab === 'sessions' && <V2Sessions />}
        {tab === 'devices' && <V2DevicesTab s={s}/>}
        {tab === 'settings' && <V2Settings safeMode={safeMode} setSafeMode={setSafeMode}/>}
      </div>

      {/* Tweaks panel */}
      <div className={'tweaks-v2' + (showTweaks ? ' on' : '')}>
        <div style={{ fontSize: 10, letterSpacing: 1.2, color: T.textMuted, fontWeight: 700, textTransform: 'uppercase', marginBottom: 14 }}>Tweaks</div>
        <TweakRow label="Scenario">
          {Object.keys(SCENARIOS).map(k => (
            <TweakChip key={k} active={scenario === k} onClick={() => {
              setScenario(k);
              localStorage.setItem('hourv2-scenario', k);
              window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { scenario: k } }, '*');
            }}>{SCENARIOS[k].label}</TweakChip>
          ))}
        </TweakRow>
        <TweakRow label="Screen">
          {tabs.map(t2 => (
            <TweakChip key={t2.key} active={tab === t2.key} onClick={() => setTab(t2.key)}>{t2.key}</TweakChip>
          ))}

        </TweakRow>
        <TweakRow label="State">
          <TweakChip active={safeMode} onClick={() => setSafeMode(v => !v)}>Safe mode</TweakChip>
        </TweakRow>
      </div>
    </div>
    </LocaleProvider>
  );
}

function TweakRow({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 9, color: T.textMuted, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 700, marginBottom: 7 }}>{label}</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>{children}</div>
    </div>
  );
}

function TweakChip({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      background: active ? T.green : 'transparent',
      color: active ? T.bg : T.textSecondary,
      border: `1.5px solid ${active ? T.green : T.border}`,
      padding: '4px 10px', borderRadius: 99,
      fontFamily: T.fontUI, fontSize: 10, fontWeight: 600,
      cursor: 'pointer', transition: 'all 160ms', letterSpacing: 0.3,
    }}>{children}</button>
  );
}

// ── Top bar ────────────────────────────────────────────────────────────────
function V2TopBar({ tabs, current, setCurrent, safeMode }) {
  const { t } = useLocale();
  return (
    <div style={{
      background: T.surface, borderBottom: `1px solid ${T.border}`,
    }}>
      <div style={{
        padding: '0 36px', display: 'flex', alignItems: 'stretch', height: 62,
        maxWidth: 1440, margin: '0 auto',
      }}>
      <div style={{ display: 'flex', alignItems: 'center', marginRight: 40 }}>
        <img src={window.__resources && window.__resources.gridomeLogo ? window.__resources.gridomeLogo : "gridome-lockup-dark.svg"} alt="Gridome" style={{ display: 'block', height: 64, width: 'auto' }}/>
      </div>
      <div style={{ display: 'flex', alignItems: 'stretch', gap: 0 }}>
        {tabs.map(tab => (
          <button key={tab.key} onClick={() => setCurrent(tab.key)} style={{
            background: 'transparent', border: 'none',
            color: current === tab.key ? T.textPrimary : T.textMuted,
            fontFamily: T.fontUI, fontSize: 13, fontWeight: current === tab.key ? 600 : 400,
            cursor: 'pointer', padding: '0 14px',
            borderBottom: `2px solid ${current === tab.key ? T.green : 'transparent'}`,
            transition: 'all 160ms',
          }}>{t('nav.' + tab.key)}</button>
        ))}
      </div>
      <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 14, fontSize: 11, color: T.textMuted }}>
        {safeMode
          ? <span style={{ color: T.red, fontWeight: 600, fontFamily: T.fontMono, fontSize: 10, letterSpacing: 0.5 }}>SAFE MODE</span>
          : <span>{t('status.bar')}</span>
        }
        <div style={{
          width: 6, height: 6, borderRadius: '50%',
          background: safeMode ? T.red : T.green,
          boxShadow: `0 0 8px ${safeMode ? T.red : T.green}`,
        }} />
      </div>
      </div>
    </div>
  );
}

// ── Surface (box) primitives ───────────────────────────────────────────────
function Surface({ children, style, padding = 20 }) {
  return (
    <div style={{ background: T.surface, borderRadius: 14, border: `1px solid ${T.border}`, padding, ...style }}>
      {children}
    </div>
  );
}

function SurfaceLabel({ children, color, style }) {
  return (
    <div style={{
      fontFamily: T.fontUI, fontWeight: 600, fontSize: 10,
      textTransform: 'uppercase', letterSpacing: 1.1,
      color: color || T.textMuted, ...style,
    }}>{children}</div>
  );
}

function PrimaryBtn({ children, onClick, disabled, style }) {
  return (
    <button onClick={onClick} disabled={disabled} style={{
      background: disabled ? T.raised : T.green,
      color: disabled ? T.textMuted : T.bg,
      border: 'none', borderRadius: 10,
      padding: '10px 18px',
      fontFamily: T.fontUI, fontWeight: 700, fontSize: 12,
      cursor: disabled ? 'not-allowed' : 'pointer', transition: 'all 200ms',
      letterSpacing: 0.3, ...style,
    }}>{children}</button>
  );
}

function GhostBtn({ children, onClick, style }) {
  return (
    <button onClick={onClick} style={{
      background: 'transparent', color: T.green,
      border: `1.5px solid ${T.border}`, borderRadius: 10,
      padding: '10px 18px',
      fontFamily: T.fontUI, fontWeight: 600, fontSize: 12,
      cursor: 'pointer', transition: 'all 200ms',
      letterSpacing: 0.3, ...style,
    }}>{children}</button>
  );
}

// (SCENE_ACTION_PL removed — labels now via t())
// (SCENE_REC_PL removed — labels now via t())




// ── Home screen ────────────────────────────────────────────────────────────
function V2Home({ s, safeMode, setCurrent }) {
  const { t, locale } = useLocale();
  const price = useLiveJitter(s.priceNow, 0.008);
  const tierC = TIER_COLOR[s.tier];
  const tierT = TIER_TINT[s.tier];
  const curve = React.useMemo(() => buildPriceCurve(s), [s]);
  const food = foodFor(s.savedToday);
  const action = { cta: t('home.cta.' + s.key), sub: t('home.sub.' + s.key) };

  // Croissant: t()-driven, scenario-specific
  const croissantLine = t('home.croissant.' + s.key, { saved: s.savedToday.toFixed(2), emoji: food.emoji, food: food.text });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18, marginBottom: 18 }}>
        {/* Price hero — internal 2-col: left=price, right=vertical flow stack */}
        <Surface padding={32} style={{
          background: `linear-gradient(135deg, ${tierT}, ${T.surface})`,
          border: `1px solid ${tierC}44`,
        }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 24 }}>
            {/* Left: price + status + buttons */}
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <span style={{
                  width: 8, height: 8, borderRadius: '50%', background: tierC,
                  display: 'inline-block', boxShadow: `0 0 10px ${tierC}`,
                  animation: 'dot-pulse 1.6s ease-out infinite',
                }} />
                <SurfaceLabel color={tierC}>{getTierLabel(s.tier, t)} · {t('tier.priceNow')}</SurfaceLabel>
              </div>
              <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',
                }}>{Math.round(price)}</span>
                <span style={{ fontSize: 26, color: T.textSecondary, fontWeight: 600 }}>gr/kWh</span>
              </div>
              <div style={{ color: T.textSecondary, fontSize: 14, marginTop: 14, lineHeight: 1.6, maxWidth: 480 }}>
                {t('home.rec.' + s.key)}
              </div>
              <div style={{ display: 'flex', gap: 10, marginTop: 22, alignItems: 'center' }}>
                <PrimaryBtn disabled={safeMode} onClick={() => setCurrent && setCurrent('optimizer')}>
                  {safeMode ? t('home.blockedBtn') : t('home.cta.' + s.key)}
                </PrimaryBtn>
                <GhostBtn onClick={() => setCurrent && setCurrent('optimizer')}>{t('home.laterBtn')}</GhostBtn>
                {action.sub && (
                  <span style={{ fontSize: 11, color: T.textMuted, marginLeft: 4 }}>{action.sub}</span>
                )}
              </div>
            </div>
            {/* Right: compact vertical power flow */}
            <div style={{ width: 220, borderLeft: `1px solid ${T.border}`, padding: 0 }}>
              <V2FlowStack s={s} setCurrent={setCurrent}/>
            </div>
          </div>
        </Surface>

        {/* Savings card — cross-links to Sessions */}
        <Surface padding={28} style={{ cursor: 'pointer' }}
          onClick={() => setCurrent && setCurrent('sessions')}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <SurfaceLabel>{t('home.savedToday')}</SurfaceLabel>
            <span style={{ fontSize: 10, color: T.textMuted }}>{t('home.historyLink')}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 14 }}>
            <span style={{
              fontFamily: T.fontBrand, fontWeight: 700, fontSize: 60, lineHeight: 1,
              color: T.green, fontVariantNumeric: 'tabular-nums',
            }}>{s.savedToday.toFixed(2)}</span>
            <span style={{ fontSize: 18, color: T.textSecondary, fontWeight: 600 }}>zł</span>
          </div>
          <div style={{ fontSize: 13, color: T.textSecondary, marginTop: 10, lineHeight: 1.5 }}>
            {croissantLine}
          </div>
          <div style={{ marginTop: 22, paddingTop: 18, borderTop: `1px solid ${T.border}` }}>
            <SurfaceLabel style={{ fontSize: 9 }}>{t('home.thisMonth')}</SurfaceLabel>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 8 }}>
              <span style={{
                fontFamily: T.fontMono, fontSize: 24, fontWeight: 600,
                color: T.textPrimary, fontVariantNumeric: 'tabular-nums',
              }}>{s.savedMonth.toFixed(2)}</span>
              <span style={{ fontSize: 12, color: T.textMuted }}>zł</span>
            </div>
          </div>
          <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {[
              { l: t('home.pvSelfUse'), v: '3.2 kWh', c: T.green },
              { l: t('home.battArbitrage'), v: '1.8 kWh', c: T.blue },
              { l: t('home.shiftedLoads'), v: '2.4 kWh', c: T.amber },
              { l: t('home.exportRevenue'), v: '4.1 kWh', c: T.violet },
            ].map((it, i) => (
              <div key={i} style={{
                background: T.raised, borderRadius: 8, padding: '8px 10px',
                border: `1px solid ${T.border}`,
              }}>
                <div style={{ fontSize: 9, color: T.textMuted, letterSpacing: 0.8, textTransform: 'uppercase', fontWeight: 600 }}>{it.l}</div>
                <div style={{ fontFamily: T.fontMono, fontSize: 13, color: it.c, marginTop: 4, fontWeight: 600 }}>{it.v}</div>
              </div>
            ))}
          </div>
        </Surface>
      </div>

      {/* 24h strip — cross-links to Prognoza */}
      <Surface style={{ marginBottom: 18, cursor: 'pointer' }}
        onClick={() => setCurrent && setCurrent('forecast')}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <SurfaceLabel>{t('home.priceStrip')}</SurfaceLabel>
          <span style={{ fontSize: 10, color: T.textMuted }}>{t('home.strip48h')}</span>
        </div>
        <V2PriceStrip curve={curve} nowHour={s.hour} />
      </Surface>

      {/* Flow bar — horizontal IN/OUT bar, cross-links to Battery */}
      <V2FlowBar scenario={s} onClick={() => setCurrent && setCurrent('battery')} />
    </div>
  );
}

function V2PriceStrip({ curve, nowHour }) {
  const { t } = useLocale();
  const max = Math.max(...curve.map(c => c.price));
  const min = Math.min(...curve.map(c => c.price));
  const d = barDensity(curve.length);
  const nowIdx = nowSlotIndex(nowHour, curve.length, 0);
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: d.gap, height: 64 }}>
        {curve.map((c, i) => {
          const h = 8 + ((c.price - min) / (max - min)) * 54;
          const isNow = i === nowIdx;
          const tc = TIER_COLOR[c.tier];
          return (
            <div key={i} style={{
              flex: 1, height: h,
              background: isNow ? tc : `${tc}55`,
              borderRadius: d.radius,
              boxShadow: isNow ? `0 0 14px ${tc}` : 'none',
              transition: 'all 160ms',
            }} />
          );
        })}
      </div>
      <div style={{
        display: 'flex', justifyContent: 'space-between', marginTop: 8,
        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={{ display: 'flex', gap: 18, marginTop: 12, fontSize: 11, color: T.textMuted }}>
        {[['cheap', t('tier.cheap')], ['standard', t('tier.standard')], ['peak', t('tier.peak')], ['high', t('tier.high')]].map(([k, l]) => (
          <span key={k} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: TIER_COLOR[k] }} />{l}
          </span>
        ))}
      </div>
    </div>
  );
}

function V2FlowBar({ scenario: s, onClick }) {
  const { t } = useLocale();
  const ins = [
    s.pv > 0 && { label: 'Solar', val: s.pv, color: T.green },
    s.battery > 0 && { label: 'Battery', val: s.battery, color: T.blue },
    s.grid > 0 && { label: 'Grid', val: s.grid, color: T.textMuted },
  ].filter(Boolean);
  const outs = [
    { label: 'Home', val: s.home, color: T.textSecondary },
    s.ev && { label: 'Car', val: s.ev, color: T.green },
    s.battery < 0 && { label: 'Battery', val: -s.battery, color: T.blue },
    s.grid < 0 && { label: 'Export', val: -s.grid, color: T.amber },
  ].filter(Boolean);

  return (
    <Surface style={{ cursor: onClick ? 'pointer' : 'default' }} onClick={onClick}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <SurfaceLabel>{t('home.flowTitle')}</SurfaceLabel>
        {onClick && <span style={{ fontSize: 10, color: T.textMuted }}>{t('home.batteryLink')}</span>}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
        <div>
          <SurfaceLabel style={{ marginBottom: 10 }}>{t('home.flowIn')}</SurfaceLabel>
          <FlowV2Row entries={ins} />
        </div>
        <div>
          <SurfaceLabel style={{ marginBottom: 10 }}>{t('home.flowOut')}</SurfaceLabel>
          <FlowV2Row entries={outs} />
        </div>
      </div>
      <div style={{
        marginTop: 16, paddingTop: 14, borderTop: `1px solid ${T.border}`,
        display: 'flex', justifyContent: 'space-between', fontSize: 12, color: T.textMuted,
      }}>
        <span>{t('home.socLabel')} · <span style={{ color: T.textPrimary, fontFamily: T.fontMono, fontWeight: 600 }}>{s.batterySOC}%</span></span>
        <span>{s.grid < 0 ? t('home.export') : t('home.import')} · <span style={{ color: T.textPrimary, fontFamily: T.fontMono, fontWeight: 600 }}>{Math.abs(s.grid).toFixed(1)} kW</span></span>
      </div>
    </Surface>
  );
}

function FlowV2Row({ entries }) {
  const total = entries.reduce((a, e) => a + e.val, 0);
  return (
    <div>
      <div style={{ display: 'flex', gap: 3, height: 28, borderRadius: 8, overflow: 'hidden' }}>
        {entries.map((e, i) => (
          <div key={i} style={{
            flex: Math.max(e.val, 0.1),
            background: e.color,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: T.bg, fontSize: 10, fontWeight: 700, fontFamily: T.fontMono,
          }}>
            {e.val >= 0.6 ? `${e.val.toFixed(1)}` : ''}
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 3, marginTop: 5 }}>
        {entries.map((e, i) => (
          <div key={i} style={{ flex: Math.max(e.val, 0.1), fontSize: 10, color: T.textMuted, textAlign: 'center' }}>
            {e.label}
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Plan screen ────────────────────────────────────────────────────────────
const PLAN_LOADS_DEFAULT = [
  { id: 1, nameKey: 'plan.load.dishwasher', iconName: 'utensils', time: '13:00', save: '2.10', kwh: 1.2 },
  { id: 2, nameKey: 'plan.load.washer',     iconName: 'shirt', time: '23:00', save: '3.40', kwh: 2.1 },
  { id: 3, nameKey: 'plan.load.car',        iconName: 'car', time: '01:00', save: '6.80', kwh: 14.0 },
];

function V2Plan({ s, setCurrent }) {
  const { t } = useLocale();
  const curve = React.useMemo(() => buildPriceCurve(s), [s]);
  const [selected, setSelected] = React.useState(Math.floor(s.hour));
  const [queue, setQueue] = React.useState(PLAN_LOADS_DEFAULT);
  const [toast, setToast] = React.useState(null);
  const win = cheapestWindow(curve, 3);
  const c = curve[selected];
  const tc = TIER_COLOR[c.tier];

  const totalSave = queue.reduce((a, l) => a + parseFloat(l.save), 0);
  const totalKwh  = queue.reduce((a, l) => a + l.kwh, 0);
  const totalCo2  = Math.round(totalKwh * 0.22 * 1000);
  const queueFood = queue.length > 0 ? foodFor(totalSave) : null;

  const scheduleSelected = () => {
    const hh = String(selected).padStart(2, '0');
    setToast(`Zaplanowano na ${hh}:00 ✓`);
    setTimeout(() => setToast(null), 2400);
  };
  const dismissLoad = (id) => setQueue(q => q.filter(l => l.id !== id));

  return (
    <div style={{ position: 'relative' }}>
      {toast && (
        <div style={{
          position: 'fixed', top: 72, left: '50%', transform: 'translateX(-50%)',
          background: T.green, color: T.bg, padding: '10px 22px', borderRadius: 999,
          fontFamily: T.fontUI, fontWeight: 700, fontSize: 13, zIndex: 50,
          boxShadow: `0 8px 32px ${T.green}44`,
        }}>{toast}</div>
      )}

      <Surface style={{ marginBottom: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <SurfaceLabel>{t('plan.header')}</SurfaceLabel>
            <span style={{ fontSize: 11, color: T.textMuted }}>
              {t('plan.cheapWindow')}:
              <span style={{ color: T.green, fontWeight: 700, fontFamily: T.fontMono, marginLeft: 5 }}>
                {String(win.start).padStart(2, '0')}–{String(win.end).padStart(2, '0')}h
              </span>
            </span>
          </div>
          <button onClick={() => setCurrent && setCurrent('optimizer')} style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            fontSize: 11, color: T.textMuted, fontFamily: T.fontUI,
          }}>{t('plan.autoLink')}</button>
        </div>
        <V2PriceBars curve={curve} selected={selected} setSelected={setSelected} nowHour={s.hour} />
      </Surface>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16 }}>
        <Surface style={{ borderLeft: `3px solid ${tc}` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
            <span style={{
              width: 7, height: 7, borderRadius: '50%', background: tc,
              display: 'inline-block', flexShrink: 0, boxShadow: `0 0 8px ${tc}`,
              animation: 'dot-pulse 1.6s ease-out infinite',
            }}/>
            <SurfaceLabel color={tc}>{String(selected).padStart(2, '0')}:00 · {getTierLabel(c.tier, t)}</SurfaceLabel>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <span style={{ fontFamily: T.fontBrand, fontWeight: 700, fontSize: 48, color: tc, fontVariantNumeric: 'tabular-nums' }}>{c.price}</span>
            <span style={{ fontSize: 14, color: T.textMuted, fontWeight: 600 }}>gr/kWh</span>
          </div>
          <div style={{ fontSize: 12, color: T.textMuted, marginTop: 8 }}>
            {c.price < s.priceNow
              ? <><span style={{ color: T.green }}>{s.priceNow - c.price} gr taniej</span> niż teraz</>
              : c.price > s.priceNow
              ? <><span style={{ color: T.red }}>{c.price - s.priceNow} gr drożej</span> niż teraz</>
              : t('plan.same')}
          </div>
          <PrimaryBtn onClick={scheduleSelected} style={{ marginTop: 20, width: '100%' }}>
            {t('plan.scheduleBtn', { hour: String(selected).padStart(2, '0') })}
          </PrimaryBtn>
          {queueFood && (
            <div style={{
              marginTop: 14, padding: '9px 12px',
              background: `${T.green}12`, border: `1px solid ${T.green}28`,
              borderRadius: 10, fontSize: 11, color: T.textSecondary, lineHeight: 1.5,
            }}>
              {t('plan.croissant', { total: '', emoji: '', food: '' }).split(' ')[0]+' '+t('plan.croissant', { total: '', emoji: '', food: '' }).split(' ')[1]} <strong style={{ color: T.green }}>{totalSave.toFixed(2)} zł</strong>
              , czyli {queueFood.emoji} {queueFood.text}.
            </div>
          )}
        </Surface>

        <Surface>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
            <SurfaceLabel color={T.green}>{t('plan.queueTitle')}</SurfaceLabel>
            <button onClick={() => setCurrent && setCurrent('sessions')} style={{
              background: 'transparent', border: 'none', cursor: 'pointer',
              fontSize: 10, color: T.textMuted, fontFamily: T.fontUI,
            }}>{t('plan.historyLink')}</button>
          </div>
          {queue.length === 0 ? (
            <div style={{ padding: '20px 0', fontSize: 12, color: T.textMuted, lineHeight: 1.6, textAlign: 'center' }}>
              {t('plan.emptyQueue')}
            </div>
          ) : queue.map((l, i) => (
            <div key={l.id} style={{
              display: 'flex', alignItems: 'center', padding: '11px 0',
              borderBottom: i < queue.length - 1 ? `1px solid ${T.border}` : 'none', gap: 8,
            }}>
              <LI name={l.iconName} size={16} color={T.textMuted}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, color: T.textPrimary, fontWeight: 600 }}>{t(l.nameKey)}</div>
                <div style={{ fontFamily: T.fontMono, fontSize: 10, color: T.textMuted, marginTop: 2 }}>
                  {l.time} · <span style={{ color: T.green }}>−{l.save} zł</span>
                </div>
              </div>
              <button onClick={() => dismissLoad(l.id)} style={{
                background: 'transparent', border: 'none', cursor: 'pointer',
                color: T.textMuted, fontSize: 14, lineHeight: 1, padding: '2px 6px', borderRadius: 4,
              }}>×</button>
            </div>
          ))}
        </Surface>

        <Surface>
          <SurfaceLabel style={{ marginBottom: 16 }}>{t('plan.savingsTitle')}</SurfaceLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <QueueSavingRow label={t('plan.totalRow')} value={`${totalSave.toFixed(2)} zł`}
              sub={t('plan.totalSub')} color={T.green}
              pct={Math.min(100, (totalSave / 15) * 100)} />
            <QueueSavingRow label={t('plan.shiftedRow')} value={`${totalKwh.toFixed(1)} kWh`}
              sub={t('plan.shiftedSub')} color={T.blue}
              pct={Math.min(100, (totalKwh / 20) * 100)} />
            <QueueSavingRow label={t('plan.co2Row')} value={`${totalCo2} g`}
              sub={t('plan.co2Sub')} color={T.violet}
              pct={Math.min(100, (totalCo2 / 3000) * 100)} />
          </div>
          <div style={{
            marginTop: 18, paddingTop: 14, borderTop: `1px solid ${T.border}`,
            fontSize: 10, color: T.textMuted, lineHeight: 1.5,
          }}>
            {t('plan.optimizerNote')}
          </div>
        </Surface>
      </div>
    </div>
  );
}

function QueueSavingRow({ label, value, sub, color, pct }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
        <span style={{ fontSize: 12, color: T.textPrimary, fontWeight: 600 }}>{label}</span>
        <span style={{ fontFamily: T.fontMono, fontSize: 13, fontWeight: 700, color }}>{value}</span>
      </div>
      <div style={{ height: 4, background: T.raised, borderRadius: 2, marginBottom: 3 }}>
        <div style={{ width: `${pct}%`, height: '100%', background: color, borderRadius: 2 }} />
      </div>
      <div style={{ fontSize: 10, color: T.textMuted }}>{sub}</div>
    </div>
  );
}

function V2PriceBars({ curve, selected, setSelected, nowHour }) {
  const max = Math.max(...curve.map(c => c.price));
  const d = barDensity(curve.length);
  const nowIdx = nowSlotIndex(nowHour, curve.length, 0);
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: d.gap + 1, height: 130 }}>
        {curve.map((c, i) => {
          const isSel = selected === i;
          const isNow = i === nowIdx;
          const tc = TIER_COLOR[c.tier];
          return (
            <button key={i} onClick={() => setSelected(i)} style={{
              flex: 1, height: 16 + (c.price / max) * 110,
              background: isSel ? tc : `${tc}44`,
              border: isNow ? `1.5px solid ${T.textPrimary}` : `1.5px solid transparent`,
              borderRadius: d.radius + 1, cursor: 'pointer', padding: 0, transition: 'all 140ms',
              boxShadow: isSel ? `0 0 16px ${tc}60` : 'none',
            }} />
          );
        })}
      </div>
      <div style={{
        display: 'flex', justifyContent: 'space-between', marginTop: 8,
        fontFamily: T.fontMono, fontSize: 10, color: T.textMuted,
      }}>
        <span>00</span><span>06</span><span>12</span><span>18</span><span>23</span>
      </div>
    </div>
  );
}

// ── Car screen ─────────────────────────────────────────────────────────────
function V2Car({ s, safeMode }) {
  const ev = EV_STATE[s.key];
  const curve = React.useMemo(() => buildPriceCurve(s), [s]);
  const win = cheapestWindow(curve, 4);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 18, marginBottom: 18 }}>
        <Surface padding={28}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12,
              background: ev.charging ? `${T.green}22` : T.raised,
              border: `1px solid ${ev.charging ? T.green : T.border}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20,
            }}>🚗</div>
            <div>
              <div style={{ fontSize: 16, fontWeight: 700, color: T.textPrimary, fontFamily: T.fontBrand }}>Škoda Enyaq iV 80</div>
              <div style={{ fontSize: 11, color: T.textMuted, marginTop: 2 }}>go-eCharger · OCPP 1.6 · 11 kW max</div>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 16 }}>
            <span style={{
              fontFamily: T.fontBrand, fontWeight: 700, fontSize: 84, lineHeight: 0.9,
              color: T.textPrimary, fontVariantNumeric: 'tabular-nums',
            }}>{ev.soc}</span>
            <span style={{ fontSize: 22, color: T.textMuted, fontWeight: 600 }}>%</span>
          </div>
          <div style={{ height: 8, background: T.raised, borderRadius: 6, overflow: 'visible', position: 'relative', marginBottom: 6 }}>
            <div style={{ width: `${ev.soc}%`, height: '100%', background: T.green, borderRadius: 6, transition: 'width 500ms' }} />
            <div style={{ position: 'absolute', left: `${ev.target}%`, top: -4, width: 1.5, height: 16, 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>Target {ev.target}%</span><span>100</span>
          </div>
          <div style={{
            background: T.raised, borderRadius: 10, padding: '14px 16px',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            border: `1px solid ${T.border}`,
          }}>
            <div>
              <SurfaceLabel style={{ fontSize: 9 }}>Status</SurfaceLabel>
              <div style={{ fontSize: 14, fontWeight: 600, color: T.textPrimary, marginTop: 4 }}>
                {ev.done ? 'Fully charged ✓' :
                 ev.charging ? `Charging at ${ev.power} kW` :
                 ev.waiting ? 'Waiting for cheap window' : 'Unplugged'}
              </div>
              {ev.eta && <div style={{ fontSize: 11, color: T.textMuted, marginTop: 2 }}>Done by {ev.eta}</div>}
            </div>
            <div style={{
              width: 10, height: 10, borderRadius: '50%',
              background: ev.charging ? T.green : ev.done ? T.blue : T.textMuted,
              boxShadow: ev.charging ? `0 0 12px ${T.green}` : 'none',
            }} />
          </div>
        </Surface>
        <Surface padding={24}>
          <SurfaceLabel>Tonight's charge plan</SurfaceLabel>
          <div style={{ marginTop: 16 }}>
            <V2ChargeBars curve={curve} window={win} />
          </div>
          <div style={{ marginTop: 14, fontSize: 12, color: T.textMuted, lineHeight: 1.6 }}>
            Auto-picked cheapest 4h window. Waking up full.
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
            <PrimaryBtn disabled={safeMode} style={{ flex: 1 }}>Charge now</PrimaryBtn>
            <GhostBtn style={{ flex: 1 }}>Edit plan</GhostBtn>
          </div>
        </Surface>
      </div>
      <Surface>
        <SurfaceLabel style={{ marginBottom: 16 }}>Last 30 sessions</SurfaceLabel>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24 }}>
          {[
            { l: 'Energy', v: '412', u: 'kWh', c: T.textPrimary },
            { l: 'Cost', v: '148.20', u: 'zł', c: T.textPrimary },
            { l: 'Avg price', v: '36', u: 'gr/kWh', c: T.green },
            { l: 'vs off-peak', v: '−84.40', u: 'zł', c: T.green },
          ].map((k, i) => (
            <div key={i}>
              <SurfaceLabel style={{ fontSize: 9 }}>{k.l}</SurfaceLabel>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 10 }}>
                <span style={{ fontFamily: T.fontBrand, fontWeight: 700, fontSize: 28, color: k.c, fontVariantNumeric: 'tabular-nums' }}>{k.v}</span>
                <span style={{ fontSize: 11, color: T.textMuted }}>{k.u}</span>
              </div>
            </div>
          ))}
        </div>
      </Surface>
    </div>
  );
}

function V2ChargeBars({ curve, window }) {
  const min = Math.min(...curve.map(c => c.price));
  const max = Math.max(...curve.map(c => c.price));
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height: 80 }}>
        {curve.map((c, i) => {
          const h = 8 + ((c.price - min) / (max - min)) * 68;
          const active = i >= window.start && i < window.end;
          return (
            <div key={i} style={{
              flex: 1, height: h, borderRadius: 3,
              background: active ? T.green : `${TIER_COLOR[c.tier]}33`,
              boxShadow: active ? `0 0 8px ${T.green}66` : 'none',
            }} />
          );
        })}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontFamily: T.fontMono, fontSize: 10, color: T.textMuted }}>
        <span>00</span><span>06</span><span>12</span><span>18</span><span>23</span>
      </div>
      <div style={{ marginTop: 10, fontSize: 12, color: T.textMuted }}>
        Window · <span style={{ color: T.green, fontWeight: 700, fontFamily: T.fontMono }}>
          {String(window.start).padStart(2, '0')}–{String(window.end).padStart(2, '0')}h
        </span>
      </div>
    </div>
  );
}

// ── Sessions ───────────────────────────────────────────────────────────────
// ── Settings ───────────────────────────────────────────────────────────────
// V2Settings moved to settings-v2.jsx

// ── Devices tab ─────────────────────────────────────────────────────────
// Wraps V2Devices (defined in devices-v2.jsx) with a 4-variant switcher
// so the user can preview each layout direction side by side.
function V2DevicesTab({ s }) {
  const [variant, setVariant] = React.useState(() => {
    try { return localStorage.getItem('gridome.devices.variant') || 'rooms'; }
    catch { return 'rooms'; }
  });
  const setV = (v) => {
    setVariant(v);
    try { localStorage.setItem('gridome.devices.variant', v); } catch {}
  };
  const variants = [
    { key:'rooms',   label:'By room',   sub:'Default · group by location' },
    { key:'table',   label:'Table',     sub:'Dense fleet list' },
    { key:'circuit', label:'Circuit',   sub:'Branching from the main panel' },
    { key:'health',  label:'Health',    sub:'Sorted by issues first' },
  ];
  return (
    <div>
      <div style={{
        display:'flex', alignItems:'baseline', justifyContent:'space-between',
        marginBottom: 18,
      }}>
        <div>
          <div style={{ fontSize: 24, fontWeight: 600, fontFamily: T.fontBrand, letterSpacing: -0.3 }}>Devices</div>
          <div style={{ fontSize: 12, color: T.textSecondary, marginTop: 4 }}>
            Plugs, relays, meters and sensors feeding the optimizer. Pick a layout for the dashboard card.
          </div>
        </div>
        <a href="Gridome - Devices.html" style={{
          background: T.green, color: T.bg, padding:'8px 14px', borderRadius: 6,
          fontSize: 12, fontWeight: 600, textDecoration:'none',
        }}>Open full page →</a>
      </div>

      <div style={{
        display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap: 8, marginBottom: 18,
      }}>
        {variants.map(v => (
          <button key={v.key} onClick={() => setV(v.key)} style={{
            background: variant === v.key ? `${T.green}15` : T.surface,
            border: `1.5px solid ${variant === v.key ? T.green : T.border}`,
            borderRadius: 8, padding: '10px 14px', textAlign:'left', cursor:'pointer',
            color:'inherit',
          }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: variant === v.key ? T.green : T.textPrimary }}>
              {v.label}
            </div>
            <div style={{ fontSize: 10, color: T.textMuted, marginTop: 3 }}>{v.sub}</div>
          </button>
        ))}
      </div>

      <V2Devices s={s} variant={variant}/>
    </div>
  );
}

Object.assign(window, { HourV2App });
