// Sessions screen — Gridome Hour v2 aesthetic.
// EVCC Sessions.vue layout logic ported: period switcher, summary hero,
// session list, drill-in modal with kW+tariff+amp curves.
// Backend gap: ev_sessions.json persistence not built yet.

const PL_DAYS = ['nd','pn','wt','śr','cz','pt','sb'];
const PERIODS_PL = [
  { key: 'month', labelKey: 'sessions.periodMonth' },
  { key: 'year',  labelKey: 'sessions.periodYear' },
  { key: 'all',   labelKey: 'sessions.periodAll' },
];

// ── Stub session data (mirrors ev_sessions.json schema) ───────────────────
function buildSessions() {
  const base = new Date('2026-04-19');
  const sessions = [];
  // ~30 sessions, mostly weeknight overnight charging
  const days = [
    [18, 18.2, 274, 29, 5.28, 8],
    [17, 22.6, 340, 31, 7.01, 0],
    [16, 24.1, 363, 30, 7.23, 6],
    [14, 18.4, 276, 33, 6.07, 0],
    [13, 20.3, 305, 29, 5.89, 12],
    [12, 31.2, 468, 38,11.86, 0],
    [11, 14.8, 222, 35, 5.18, 0],
    [10, 19.7, 296, 30, 5.91, 7],
    [9,  22.6, 339, 31, 7.01, 0],
    [7,  28.0, 420, 48,13.44, 0],
    [6,  20.3, 305, 29, 5.89,11],
    [5,  18.4, 276, 32, 5.89, 0],
    [4,  24.1, 362, 30, 7.23, 8],
    [3,  22.6, 340, 29, 6.55, 0],
    [2,  18.2, 273, 28, 5.10,15],
    [1,  20.3, 305, 29, 5.89, 9],
    // March (year view)
    [-12, 31.2, 468, 42,13.10, 0],
    [-14, 18.4, 276, 44, 8.10, 0],
    [-16, 22.6, 340, 38, 8.59, 5],
    [-18, 20.3, 305, 36, 7.31, 8],
    [-20, 24.1, 362, 35, 8.44, 0],
    [-22, 19.7, 296, 37, 7.29, 0],
    [-24, 18.2, 273, 40, 7.28, 4],
    [-26, 28.0, 420, 45,12.60, 0],
    [-28, 14.8, 222, 48, 7.10, 0],
  ];
  days.forEach(([daysAgo, kwh, mins, avgGr, cost, solar], i) => {
    const d = new Date(base);
    d.setDate(d.getDate() - (daysAgo < 0 ? -daysAgo : daysAgo));
    sessions.push({
      id: i + 1,
      date: d,
      kwh, mins, avgGr, cost, solar,
      peakCost: parseFloat((kwh * 1.42).toFixed(2)), // cost if always charged at 142gr peak
    });
  });
  return sessions.sort((a,b) => b.date - a.date);
}

const ALL_SESSIONS = buildSessions();

function filterSessions(sessions, period) {
  const now = new Date('2026-04-19');
  if (period === 'month') {
    return sessions.filter(s =>
      s.date.getFullYear() === now.getFullYear() &&
      s.date.getMonth() === now.getMonth()
    );
  }
  if (period === 'year') {
    return sessions.filter(s => s.date.getFullYear() === now.getFullYear());
  }
  return sessions;
}

// ── Main component ─────────────────────────────────────────────────────────
function V2Sessions() {
  const { t, locale } = useLocale();
  const [period, setPeriod] = React.useState('month');
  const [selected, setSelected] = React.useState(null); // drill-in session
  const sessions = React.useMemo(() => filterSessions(ALL_SESSIONS, period), [period]);

  const totalKwh = sessions.reduce((a,s) => a + s.kwh, 0);
  const totalCost = sessions.reduce((a,s) => a + s.cost, 0);
  const avgGr = sessions.length ? Math.round(sessions.reduce((a,s) => a + s.avgGr, 0) / sessions.length) : 0;
  const solarPct = sessions.length ? Math.round(sessions.reduce((a,s) => a + s.solar, 0) / sessions.length) : 0;
  const peakTotal = sessions.reduce((a,s) => a + s.peakCost, 0);
  const saved = Math.max(0, peakTotal - totalCost);
  const savedFood = saved > 0 ? foodFor(saved) : null;

  return (
    <div>
      {/* Backend gap notice */}
      <div style={{
        marginBottom: 18, padding: '10px 14px', background: T.raised, borderRadius: 10,
        border: `1px solid ${T.border}`, fontSize: 12, color: T.textMuted,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <span style={{ width: 7, height: 7, borderRadius: '50%', background: T.blue, flexShrink: 0 }}/>
        <span>
          <strong style={{ color: T.textSecondary }}>Stub — </strong>
          {t('sessions.backendNotice')}{' '}
          {t('sessions.backendNeed')}: <code style={{ fontFamily: T.fontMono, fontSize: 11, color: T.blue }}>{t('sessions.backendPath')}</code>
          {' '}({t('sessions.backendPatternLabel')}: <code style={{ fontFamily: T.fontMono, fontSize: 11, color: T.blue }}>{t('sessions.backendPattern')}</code>)
          {' '}+ <code style={{ fontFamily: T.fontMono, fontSize: 11, color: T.blue }}>{t('sessions.backendApi')}</code>.
        </span>
      </div>

      {/* Period switcher */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 20 }}>
        {PERIODS_PL.map(p => (
          <button key={p.key} onClick={() => setPeriod(p.key)} style={{
            background: period === p.key ? T.textPrimary : 'transparent',
            color: period === p.key ? T.bg : T.textSecondary,
            border: `1.5px solid ${period === p.key ? T.textPrimary : T.border}`,
            padding: '7px 16px', borderRadius: 8, cursor: 'pointer',
            fontFamily: T.fontUI, fontSize: 12, fontWeight: 600, transition: 'all 160ms',
          }}>{t(p.labelKey)}</button>
        ))}
        <a href="#" onClick={e => e.preventDefault()} style={{
          marginLeft: 'auto', alignSelf: 'center',
          fontSize: 11, color: T.textMuted, textDecoration: 'none',
          display: 'inline-flex', alignItems: 'center', gap: 6,
        }}>
          ↓ {t('sessions.csv')}
        </a>
      </div>

      {/* Hero summary */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 18, marginBottom: 18 }}>
        <Surface padding={28} style={{
          background: `linear-gradient(135deg, ${T.tintGreen}, ${T.surface})`,
          border: `1px solid ${T.green}33`,
        }}>
          <SurfaceLabel>{t('sessions.heroTitle')} · {period === 'month' ? t('sessions.periodApril') : period === 'year' ? '2026' : t('sessions.periodAllTime')}</SurfaceLabel>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginTop: 12, lineHeight: 1 }}>
            <span style={{
              fontFamily: T.fontBrand, fontWeight: 700, fontSize: 120,
              letterSpacing: -4, color: T.textPrimary, fontVariantNumeric: 'tabular-nums',
            }}>{totalCost.toFixed(2)}</span>
            <span style={{ fontSize: 24, color: T.textSecondary, fontWeight: 600 }}>zł</span>
          </div>
          <div style={{ fontSize: 13, color: T.textSecondary, marginTop: 12 }}>
            {totalKwh.toFixed(1)} kWh · śr. {avgGr} gr/kWh · ☀ {solarPct}% solar
          </div>
          {saved > 0 && savedFood && (
            <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.6,
            }}>
              {t('sessions.savingsCompare', {
                period: period === 'month' ? t('sessions.periodMonth') : t('sessions.periodYear'),
                peakCost: peakTotal.toFixed(2),
                saved: saved.toFixed(2),
                food: savedFood.text,
              })}
            </div>
          )}
        </Surface>

        {/* Period sparkline chart */}
        <Surface padding={20}>
          <SurfaceLabel style={{ marginBottom: 12 }}>{t('sessions.sparklineTitle')} · {period === 'month' ? t('sessions.periodApril') : t('sessions.periodYear')}</SurfaceLabel>
          <SessionSparkline sessions={sessions} period={period}/>
        </Surface>
      </div>

      {/* Session table */}
      {sessions.length === 0 ? (
        <Surface>
          <div style={{ padding: '40px 20px', textAlign: 'center', color: T.textMuted, fontSize: 14 }}>
            {t('sessions.emptyState')}
          </div>
        </Surface>
      ) : (
        <Surface padding={0}>
          <div style={{ padding: '14px 18px 10px', borderBottom: `1px solid ${T.border}` }}>
            <div style={{ display: 'grid', gridTemplateColumns: '160px 1fr 80px 80px 70px 80px', gap: 12, fontSize: 9, color: T.textMuted, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase' }}>
              <span>{t('sessions.colDate')}</span><span>{t('sessions.colEnergy')}</span><span>{t('sessions.colTime')}</span>
              <span>{t('sessions.colAvgPrice')}</span><span>{t('sessions.colSolar')}</span><span style={{ textAlign: 'right' }}>Koszt</span>
            </div>
          </div>
          {sessions.slice(0, 16).map((s, i) => (
            <SessionRow key={s.id} session={s} isLast={i === Math.min(sessions.length, 16) - 1}
                        onClick={() => setSelected(s)}/>
          ))}
          {sessions.length > 16 && (
            <div style={{ padding: '12px 18px', fontSize: 11, color: T.textMuted, textAlign: 'center', borderTop: `1px solid ${T.border}` }}>
              + {sessions.length - 16} starszych sesji
            </div>
          )}
        </Surface>
      )}

      {/* Drill-in modal */}
      {selected && <SessionModal session={selected} onClose={() => setSelected(null)}/>}
    </div>
  );
}

// ── Session row ────────────────────────────────────────────────────────────
function SessionRow({ session: s, isLast, onClick }) {
  const { t } = useLocale();
  const [hovered, setHovered] = React.useState(false);
  const dow = getDayAbbr(s.date.getDay(), t);
  const dd = String(s.date.getDate()).padStart(2,'0');
  const mm = String(s.date.getMonth()+1).padStart(2,'0');

  return (
    <div
      onClick={onClick}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        display: 'grid', gridTemplateColumns: '160px 1fr 80px 80px 70px 80px', gap: 12,
        padding: '14px 18px', cursor: 'pointer', fontSize: 13,
        borderBottom: isLast ? 'none' : `1px solid ${T.border}`,
        background: hovered ? T.hover : 'transparent', transition: 'background 120ms',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ fontFamily: T.fontMono, fontSize: 10, color: T.textMuted, width: 18 }}>{dow}</span>
        <span style={{ color: T.textPrimary }}>{dd}.{mm}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ width: 60, height: 4, background: T.raised, borderRadius: 2 }}>
          <div style={{ width: `${Math.min(100, s.kwh / 35 * 100)}%`, height: '100%', background: T.blue, borderRadius: 2 }}/>
        </div>
        <span style={{ fontFamily: T.fontMono, color: T.textPrimary }}>{s.kwh.toFixed(1)} kWh</span>
      </div>
      <span style={{ fontFamily: T.fontMono, color: T.textMuted }}>
        {Math.floor(s.mins/60)}h{String(s.mins%60).padStart(2,'0')}m
      </span>
      <span style={{ fontFamily: T.fontMono, color: T.textSecondary }}>{s.avgGr} gr</span>
      <span style={{ fontFamily: T.fontMono, color: s.solar > 0 ? T.amber : T.textMuted }}>
        {s.solar > 0 ? `${s.solar}%` : '—'}
      </span>
      <span style={{ fontFamily: T.fontMono, fontWeight: 700, color: T.green, textAlign: 'right' }}>
        {s.cost.toFixed(2)} zł
      </span>
    </div>
  );
}

// ── Sparkline chart ────────────────────────────────────────────────────────
function SessionSparkline({ sessions, period }) {
  // Group by day (month view) or by month (year view)
  const grouped = {};
  sessions.forEach(s => {
    const key = period === 'month'
      ? s.date.getDate()
      : s.date.getMonth();
    grouped[key] = (grouped[key] || 0) + s.cost;
  });
  const entries = Object.entries(grouped).map(([k,v]) => ({ k: parseInt(k), v }));
  entries.sort((a,b) => a.k - b.k);
  if (!entries.length) return <div style={{ height: 80, display:'flex', alignItems:'center', justifyContent:'center', color: T.textMuted, fontSize: 12 }}>{t('sessions.noData')}</div>;
  const max = Math.max(...entries.map(e => e.v));

  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height: 80 }}>
      {entries.map((e, i) => {
        const h = 6 + (e.v / max) * 70;
        return (
          <div key={i} style={{
            flex: 1, height: h, borderRadius: 3,
            background: `${T.green}88`, minWidth: 4,
          }}/>
        );
      })}
    </div>
  );
}

// ── Session detail modal ───────────────────────────────────────────────────
function SessionModal({ session: s, onClose }) {
  const { t } = useLocale();
  // Generate kW curve (charging session, overnight)
  const curve = buildSessionCurve(s);
  const priceCurve = buildPriceCurveForSession(s);

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.72)', backdropFilter: 'blur(8px)',
      zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 32,
    }} onClick={onClose}>
      <div style={{
        background: T.surface, border: `1px solid ${T.border}`, borderRadius: 20,
        padding: 32, maxWidth: 760, width: '100%', maxHeight: '90vh', overflow: 'auto',
      }} onClick={e => e.stopPropagation()}>
        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
          <div>
            <div style={{ fontFamily: T.fontBrand, fontSize: 22, fontWeight: 700, letterSpacing: -0.5 }}>
              {getDayFull(s.date.getDay(), t)}
              {', '}{s.date.getDate()}.{String(s.date.getMonth()+1).padStart(2,'0')}.{s.date.getFullYear()}
            </div>
            <div style={{ fontSize: 12, color: T.textMuted, marginTop: 4, fontFamily: T.fontMono }}>
              EO EM301 · Škoda Enyaq iV 80
            </div>
          </div>
          <button onClick={onClose} style={{
            background: T.raised, border: `1px solid ${T.border}`, color: T.textMuted,
            width: 32, height: 32, borderRadius: 8, cursor: 'pointer', fontSize: 16,
          }}>×</button>
        </div>

        {/* Summary stats */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 24 }}>
          {[
            { l: t('auto.sessionEnergy'), v: `${s.kwh.toFixed(1)} kWh`, c: T.blue },
            { l: t('auto.sessionTime'), v: `${Math.floor(s.mins/60)}h ${s.mins%60}m`, c: T.textPrimary },
            { l: t('auto.sessionAvgPrice'), v: `${s.avgGr} gr/kWh`, c: T.textSecondary },
            { l: t('sessions.colCost'), v: `${s.cost.toFixed(2)} zł`, c: T.green },
          ].map((it, i) => (
            <div key={i} style={{ background: T.raised, borderRadius: 10, padding: '12px 14px', border: `1px solid ${T.border}` }}>
              <SurfaceLabel style={{ fontSize: 9, marginBottom: 5 }}>{it.l}</SurfaceLabel>
              <div style={{ fontFamily: T.fontMono, fontSize: 18, fontWeight: 700, color: it.c }}>{it.v}</div>
            </div>
          ))}
        </div>

        {/* kW charge curve */}
        <div style={{ marginBottom: 20 }}>
          <SurfaceLabel style={{ marginBottom: 12 }}>{t('sessions.modalKwCurve')}</SurfaceLabel>
          <SessionKwCurve curve={curve}/>
        </div>

        {/* Tariff curve in parallel */}
        <div style={{ marginBottom: 20 }}>
          <SurfaceLabel style={{ marginBottom: 12 }}>{t('sessions.modalTariffCurve')}</SurfaceLabel>
          <SessionTariffCurve curve={priceCurve}/>
        </div>

        {/* Amp profile */}
        <div>
          <SurfaceLabel style={{ marginBottom: 12 }}>{t('sessions.modalAmpProfile')}</SurfaceLabel>
          <SessionAmpProfile curve={curve}/>
        </div>

        {/* Peak comparison */}
        <div style={{
          marginTop: 20, padding: '14px 16px',
          background: `${T.green}14`, border: `1px solid ${T.green}30`,
          borderRadius: 12, fontSize: 12, color: T.textSecondary, lineHeight: 1.6,
        }}>
          {t('sessions.peakComparison')} <strong style={{ color: T.textPrimary }}>{s.peakCost.toFixed(2)} zł</strong>.
          {t('sessions.optimizerSaved')} <strong style={{ color: T.green }}>{(s.peakCost - s.cost).toFixed(2)} zł</strong>{' '}
          ({foodFor(s.peakCost - s.cost).text}).
        </div>
      </div>
    </div>
  );
}

function buildSessionCurve(s) {
  // Simulate kW charging profile for the session duration
  const steps = Math.ceil(s.mins / 15); // 15-min intervals
  return Array.from({ length: steps }, (_, i) => {
    const t = i / steps;
    // Ramp up at start, throttle if headroom shrinks, taper at end
    if (t < 0.05) return s.kwh / (s.mins/60) * 0.5;    // ramp
    if (t > 0.92) return s.kwh / (s.mins/60) * 0.6;    // taper
    if (t > 0.6 && t < 0.7) return s.kwh / (s.mins/60) * 0.7; // throttle dip
    return s.kwh / (s.mins/60) + (Math.random() - 0.5) * 0.4; // ~full rate
  });
}

function buildPriceCurveForSession(s) {
  // Realistic overnight prices
  const base = [29,28,27,26,27,28,30,32,35,38,42,46,50,52,54,58,62,68,72];
  const steps = Math.ceil(s.mins / 15);
  return Array.from({ length: steps }, (_, i) => base[Math.min(i, base.length - 1)]);
}

function SessionKwCurve({ curve }) {
  const max = Math.max(...curve, 1);
  const W = 700, H = 80;
  const pts = curve.map((v, i) => ({ x: (i/(curve.length-1))*W, y: H - 8 - (v/max)*(H-16) }));
  const path = pts.reduce((acc, {x,y}, i) => {
    if (i===0) return `M${x} ${y}`;
    const p = pts[i-1];
    return acc + ` Q${p.x} ${p.y} ${(p.x+x)/2} ${(p.y+y)/2}`;
  }, '') + ` T${pts[pts.length-1].x} ${pts[pts.length-1].y}`;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none" style={{ display: 'block' }}>
      <defs>
        <linearGradient id="kwGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={T.blue} stopOpacity="0.35"/>
          <stop offset="100%" stopColor={T.blue} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={path + ` L${W} ${H} L0 ${H} Z`} fill="url(#kwGrad)"/>
      <path d={path} fill="none" stroke={T.blue} strokeWidth="2" strokeLinecap="round"/>
    </svg>
  );
}

function SessionTariffCurve({ curve }) {
  const max = Math.max(...curve, 1);
  const min = Math.min(...curve);
  const W = 700, H = 60;
  const pts = curve.map((v, i) => ({
    x: (i/(curve.length-1))*W,
    y: H - 6 - ((v-min)/(max-min||1))*(H-12),
  }));
  const path = pts.reduce((acc, {x,y}, i) => {
    if (i===0) return `M${x} ${y}`;
    return acc + ` L${x} ${y}`;
  }, '');

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none" style={{ display: 'block' }}>
      <path d={path} fill="none" stroke={T.amber} strokeWidth="1.5" strokeLinecap="round"/>
    </svg>
  );
}

function SessionAmpProfile({ curve }) {
  // Amps = kW / (3phases × 230V / 1000)
  const amps = curve.map(kw => Math.round(kw / (3 * 0.23)));
  const max = 32;
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 1.5, height: 44 }}>
      {amps.map((a, i) => (
        <div key={i} style={{
          flex: 1, height: 4 + (a/max)*38, borderRadius: 2,
          background: `${T.green}88`, minWidth: 2,
        }}/>
      ))}
    </div>
  );
}

Object.assign(window, {
  V2Sessions, SessionRow, SessionSparkline, SessionModal,
  SessionKwCurve, SessionTariffCurve, SessionAmpProfile,
  buildSessionCurve, buildPriceCurveForSession, buildSessions,
});
