// Shared nav shell, food metaphors, safe-mode banner, extra icons,
// price-curve "cheap-windows" helpers. Used by both Prototype A and C.

// Food / spend translations — scale to a zł amount.
// Source rough prices (Apr 2026, Warszawa cafe/bakery ballpark): kawa 14 zł,
// croissant 9 zł, pierogi ruskie plate 28 zł, bochenek żytni 12 zł,
// paczka (donut) 7 zł, obiad (lunch) 45 zł, taxi ride 18 zł.
const FOOD_ITEMS = [
  { zl: 14, emoji: '', sing: 'kawa', plural: 'kaw', en: 'coffee' },
  { zl: 9,  emoji: '', sing: 'croissant', plural: 'croissantów', en: 'croissants' },
  { zl: 7,  emoji: '', sing: 'pączek', plural: 'pączków', en: 'pączki' },
  { zl: 12, emoji: '', sing: 'bochenek żytni', plural: 'bochenki żytnie', en: 'rye loaves' },
  { zl: 28, emoji: '', sing: 'talerz pierogów', plural: 'talerze pierogów', en: 'pierogi plates' },
  { zl: 45, emoji: '', sing: 'obiad', plural: 'obiady', en: 'lunches' },
  { zl: 18, emoji: '', sing: 'kurs taxi', plural: 'kursy taxi', en: 'taxi rides' },
];

function foodFor(zl) {
  const locale = (() => {
    try { return localStorage.getItem('gridome.locale') || 'pl'; } catch { return 'pl'; }
  })();
  const candidates = FOOD_ITEMS
    .map(it => ({...it, n: zl / it.zl}))
    .filter(it => it.n >= 1.2 && it.n <= 8);
  const pool = candidates.length ? candidates : FOOD_ITEMS.map(it => ({...it, n: zl/it.zl}));
  const idx = Math.floor(zl * 7) % pool.length;
  const it = pool[idx];
  const n = it.n >= 10 ? Math.round(it.n) : Math.round(it.n * 2) / 2;
  const label = locale === 'en' ? it.en : (n === 1 ? it.sing : it.plural);
  const nStr = Number.isInteger(n) ? n : n.toFixed(1);
  return { text: `≈ ${nStr} ${label}`, emoji: it.emoji };
}

// Multiple food pills — for the "why you saved" area
function foodsFor(zl, count = 3) {
  const out = [];
  for (let i = 0; i < count; i++) {
    const adj = zl * (0.6 + (i * 0.2));
    out.push(foodFor(adj));
  }
  // de-dupe emoji
  const seen = new Set();
  return out.filter(f => { if (seen.has(f.emoji)) return false; seen.add(f.emoji); return true; });
}

// Cheap-window finder from a 24h curve
function cheapestWindow(curve, length = 3) {
  let best = { sum: Infinity, start: 0 };
  for (let i = 0; i <= curve.length - length; i++) {
    const sum = curve.slice(i, i+length).reduce((a,c)=>a+c.price, 0);
    if (sum < best.sum) best = { sum, start: i };
  }
  return { start: best.start, end: best.start + length, avg: best.sum / length };
}

// ── Nav shell ──────────────────────────────────────────────────────────────
function NavShell({ tabs, current, setCurrent, brand, accent, onSafeToggle, safeMode, scenarioChip, theme = 'dark' }) {
  return (
    <div style={{
      display:'flex', alignItems:'center', justifyContent:'space-between',
      padding: '16px 32px', borderBottom: `1px solid ${T.borderSubtle}`,
      background: theme === 'warm' ? '#17161B' : T.bg, position:'relative', zIndex: 2,
    }}>
      <div style={{display:'flex', alignItems:'center', gap: 28}}>
        <div style={{display:'flex', alignItems:'center', gap: 10}}>
          <GridomeMark size={20}/>
          <span style={{fontFamily: T.fontBrand, fontWeight: 600, fontSize: 15, letterSpacing: -0.3}}>
            {brand || 'Gridome'}
          </span>
        </div>
        <div style={{display:'flex', gap: 4}}>
          {tabs.map(t => (
            <button key={t.key} onClick={() => setCurrent(t.key)}
              style={{
                background: current === t.key ? (accent + '22') : 'transparent',
                color: current === t.key ? accent : T.textSecondary,
                border: 'none', padding:'7px 14px', borderRadius: 8,
                fontFamily: T.fontUI, fontSize: 12, fontWeight: 500,
                cursor:'pointer', transition:'all 140ms',
              }}>
              {t.label}
            </button>
          ))}
        </div>
      </div>
      <div style={{display:'flex', alignItems:'center', gap: 14, fontSize: 11, color: T.textMuted}}>
        {scenarioChip}
        <button onClick={onSafeToggle} style={{
          background: safeMode ? T.red + '22' : 'transparent',
          color: safeMode ? T.red : T.textMuted,
          border: `1px solid ${safeMode ? T.red + '44' : T.border}`,
          padding:'5px 10px', borderRadius: 6, fontSize: 10, cursor:'pointer',
          fontFamily: T.fontMono, letterSpacing: 0.5,
        }}>{safeMode ? 'SAFE MODE' : 'kill-switch'}</button>
        <Mono size={11} color={T.textMuted}>gridome.local</Mono>
      </div>
    </div>
  );
}

// ── Safe-mode banner ──────────────────────────────────────────────────────
function SafeModeBanner({ onLift }) {
  return (
    <div style={{
      background: `linear-gradient(90deg, ${T.red}18, ${T.red}05)`,
      borderBottom: `1px solid ${T.red}44`,
      padding: '10px 32px', display:'flex', alignItems:'center', gap: 12,
      fontSize: 12, color: T.textPrimary,
    }}>
      <span style={{
        display:'inline-block', width: 8, height: 8, borderRadius: '50%',
        background: T.red, animation: 'dot-pulse 1.4s ease-out infinite',
        boxShadow: `0 0 0 0 ${T.red}`,
      }}/>
      <strong style={{color: T.red, fontWeight: 600}}>Safe mode engaged</strong>
      <span style={{color: T.textSecondary}}>
        · Hardware writes blocked (inverter, relays, OCPP). Reads & metrics keep flowing.
      </span>
      <button onClick={onLift} style={{
        marginLeft:'auto', background:'transparent',
        color: T.textPrimary, border:`1px solid ${T.red}44`,
        padding:'5px 12px', borderRadius: 6, fontSize: 11, cursor:'pointer',
        fontFamily: T.fontUI,
      }}>Lift kill-switch</button>
    </div>
  );
}

// Food pill component
function FoodPill({ text, emoji, color = T.green }) {
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap:6,
      background: `${color}14`, border: `1px solid ${color}26`,
      borderRadius: 999, padding:'4px 11px 4px 9px',
      fontSize: 12, color: T.textSecondary,
    }}>
      <span>{text}</span>
    </span>
  );
}

// EV state — shared between prototypes
const EV_STATE = {
  midday:    { plugged: false, soc: 62, target: 80, schedule: '23:00 · cheap window' },
  evening:   { plugged: true, soc: 62, target: 80, waiting: true, schedule: '23:00 · 4h session' },
  overnight: { plugged: true, soc: 71, target: 80, charging: true, power: 7.0, eta: '06:30', schedule: 'active' },
  morning:   { plugged: true, soc: 80, target: 80, done: true, schedule: 'full · unplug any time' },
};

Object.assign(window, {
  FOOD_ITEMS, foodFor, foodsFor, cheapestWindow,
  NavShell, SafeModeBanner, FoodPill, EV_STATE,
});
