/* global React, MEMBERS, DAY_TYPES, PROGRAMS, SCHEDULE, LOGS, PERIOD_START, PERIOD_WEEKS, TODAY,
   Eyebrow, Avatar, Card, Pill, DayBadge, Button, Tick, SectionHeader, Segmented,
   addDays, dKey, getDayType, getLog, setLog, setDayType, fmtDate, weekNumber */
const { useState, useMemo } = React;

function LoggScreen({ memberId, tweaks, programs }) {
  const [date, setDate] = useState(TODAY);
  const [view, setView] = useState('day'); // day | grid
  const [, force] = useState(0);
  const refresh = () => force(x => x + 1);
  const member = MEMBERS.find(m => m.id === memberId);

  return (
    <div style={{ padding: '32px 32px 80px', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 28, gap: 24 }}>
        <div>
          <Eyebrow style={{ marginBottom: 10 }}>{member.name} · {PERIOD_WEEKS} veckors program</Eyebrow>
          <h1 style={{ margin: 0, fontFamily: 'var(--font-sans)', fontSize: 36, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1.1 }}>
            Träningslogg
          </h1>
          <p style={{ margin: '10px 0 0', maxWidth: 560, fontSize: 14, color: 'var(--fg-muted)' }}>
            Markera vad som blev gjort. Inga krav på perfektion — delvis räknas också.
          </p>
        </div>
        <Segmented
          options={[
            { value: 'day',   label: 'Dag' },
            { value: 'grid',  label: 'Veckor' },
            { value: 'table', label: 'Tabell' },
          ]}
          value={view}
          onChange={setView}
        />
      </div>

      {view === 'day'   && <DayView   memberId={memberId} date={date} setDate={setDate} refresh={refresh} programs={programs} />}
      {view === 'grid'  && <GridView  memberId={memberId} onPick={(d) => { setDate(d); setView('day'); }} />}
      {view === 'table' && <TableView memberId={memberId} refresh={refresh} />}
    </div>
  );
}

function DayView({ memberId, date, setDate, refresh, programs }) {
  const type = getDayType(memberId, date);
  const log = getLog(memberId, date) || {};
  const program = programs[type] || programs.normal;

  const update = (patch) => {
    const next = { ...log, ...patch };
    setLog(memberId, date, next);
    refresh();
  };

  return (
    <div>
      {/* Date nav */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
        <button onClick={() => setDate(addDays(date, -1))} style={navBtn}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6" /></svg>
        </button>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <Eyebrow>Vecka {weekNumber(date)} · dag {Math.floor((date - PERIOD_START) / 86400000) + 1} av {PERIOD_WEEKS * 7}</Eyebrow>
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 24, fontWeight: 500, letterSpacing: '-0.015em' }}>
            {fmtDate(date)}
          </div>
        </div>
        <button onClick={() => setDate(addDays(date, 1))} style={navBtn}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6" /></svg>
        </button>
        <div style={{ flex: 1 }} />
        <button
          onClick={() => setDate(TODAY)}
          style={{ ...navBtn, padding: '6px 12px', width: 'auto' }}
        >
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Idag</span>
        </button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24 }}>
        {/* LEFT: program checklist */}
        <Card pad={0}>
          <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <Eyebrow>Dagtyp</Eyebrow>
              <div style={{ marginTop: 6, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {DAY_TYPES.map(dt => {
                  const sel = dt.id === type;
                  return (
                    <button
                      key={dt.id}
                      onClick={() => { setDayType(memberId, date, dt.id); refresh(); }}
                      style={{
                        display: 'inline-flex', alignItems: 'center', gap: 6,
                        padding: '6px 10px', borderRadius: 4,
                        border: '1px solid ' + (sel ? 'var(--ink-950)' : 'var(--border)'),
                        background: sel ? 'var(--ink-950)' : 'var(--bg-raised)',
                        color: sel ? '#fff' : 'var(--fg-muted)',
                        fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: sel ? 500 : 400,
                        cursor: 'pointer',
                      }}
                    >
                      <span style={{ width: 6, height: 6, borderRadius: 999, background: dt.dot }} />
                      {dt.label}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Done switch */}
          <div style={{ padding: '14px 24px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid var(--border-faint)' }}>
            <Eyebrow style={{ flexShrink: 0 }}>Genomförd</Eyebrow>
            <Segmented
              options={[
                { value: 'ja', label: 'Ja' },
                { value: 'delvis', label: 'Delvis' },
                { value: 'nej', label: 'Nej' },
              ]}
              value={log.done || 'nej'}
              onChange={(v) => update({ done: v })}
              size="sm"
            />
          </div>

          {/* Block checks */}
          {[
            { key: 'sn', dataKey: 'snabbhet',  label: 'Snabbhet' },
            { key: 'st', dataKey: 'styrka',    label: 'Styrka' },
            { key: 'ko', dataKey: 'kondition', label: 'Kondition' },
            { key: 'ro', dataKey: 'rorlighet', label: 'Rörlighet' },
          ].map((b, i, arr) => {
            const blk = program[b.dataKey];
            return (
              <div key={b.key} style={{
                padding: '16px 24px',
                borderBottom: i < arr.length - 1 ? '1px solid var(--border-faint)' : 'none',
                display: 'flex', gap: 14,
              }}>
                <button
                  onClick={() => update({ [b.key]: !log[b.key] })}
                  style={{
                    width: 24, height: 24, flexShrink: 0, marginTop: 2,
                    borderRadius: 4, cursor: 'pointer',
                    border: `1.5px solid ${log[b.key] ? 'var(--signal)' : 'var(--border-strong)'}`,
                    background: log[b.key] ? 'var(--signal)' : 'transparent',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  }}
                >
                  {log[b.key] && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>}
                </button>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
                    <Eyebrow>{b.label}</Eyebrow>
                    {log[b.key] && <Pill bg="var(--success-tint)" color="var(--success)" dot="var(--success)">Klar</Pill>}
                  </div>
                  {blk.intro && <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 6, fontStyle: 'italic' }}>{blk.intro}</div>}
                  <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 3 }}>
                    {blk.exercises.map(e => (
                      <li key={e.id} style={{ fontSize: 13, color: 'var(--fg)', lineHeight: 1.45 }}>
                        • {window.exerciseLine(e)}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            );
          })}
        </Card>

        {/* RIGHT: feel + comment */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          <Card pad={20}>
            <Eyebrow style={{ marginBottom: 14 }}>Energi (1–5)</Eyebrow>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 6 }}>
              {[1, 2, 3, 4, 5].map(n => {
                const sel = log.energi === n;
                return (
                  <button
                    key={n}
                    onClick={() => update({ energi: n })}
                    style={{
                      padding: '12px 0', borderRadius: 4,
                      border: '1px solid ' + (sel ? 'var(--ink-950)' : 'var(--border)'),
                      background: sel ? 'var(--ink-950)' : 'var(--bg-raised)',
                      color: sel ? '#fff' : 'var(--fg)',
                      fontFamily: 'var(--font-mono)', fontSize: 14, fontWeight: 500,
                      fontVariantNumeric: 'tabular-nums', cursor: 'pointer',
                      transition: 'all 120ms',
                    }}
                  >{n}</button>
                );
              })}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-subtle)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
              <span>Slut</span><span>Pigg</span>
            </div>
          </Card>

          <Card pad={20}>
            <Eyebrow style={{ marginBottom: 14 }}>Sömn (timmar)</Eyebrow>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
              <input
                type="number" step="0.5" min="0" max="14"
                value={log.somn ?? ''}
                onChange={e => update({ somn: e.target.value === '' ? null : parseFloat(e.target.value) })}
                placeholder="—"
                style={{
                  fontFamily: 'var(--font-mono)', fontSize: 32, fontWeight: 500,
                  fontVariantNumeric: 'tabular-nums',
                  width: 100, padding: '6px 8px',
                  border: '1px solid var(--border-strong)', borderRadius: 4,
                  outline: 'none', background: 'var(--bg-raised)', color: 'var(--fg)',
                  letterSpacing: '-0.02em',
                }}
              />
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--fg-muted)' }}>h</span>
            </div>
          </Card>

          <Card pad={20}>
            <Eyebrow style={{ marginBottom: 10 }}>Kommentar</Eyebrow>
            <textarea
              value={log.kom ?? ''}
              onChange={e => update({ kom: e.target.value })}
              placeholder="Hur kändes passet? Något att komma ihåg…"
              rows={5}
              style={{
                width: '100%', resize: 'vertical',
                fontFamily: 'var(--font-sans)', fontSize: 13, lineHeight: 1.5,
                color: 'var(--fg)', background: 'transparent',
                border: '1px solid var(--border)', borderRadius: 4,
                padding: '10px 12px', outline: 'none',
              }}
            />
          </Card>
        </div>
      </div>
    </div>
  );
}

function tweaksDensity() {
  return 'comfortable'; // placeholder; density is read at app level
}

function GridView({ memberId, onPick }) {
  // Render the full 12-week grid
  const weeks = [];
  for (let w = 0; w < PERIOD_WEEKS; w++) {
    const days = [];
    for (let d = 0; d < 7; d++) {
      const date = addDays(PERIOD_START, w * 7 + d);
      days.push(date);
    }
    weeks.push(days);
  }
  return (
    <Card pad={0}>
      <div style={{ padding: '14px 24px', display: 'grid', gridTemplateColumns: '80px repeat(7, 1fr)', gap: 6, borderBottom: '1px solid var(--border)', background: 'var(--ink-25)' }}>
        <div><Eyebrow>Vecka</Eyebrow></div>
        {['Mån', 'Tis', 'Ons', 'Tor', 'Fre', 'Lör', 'Sön'].map(d => (
          <div key={d}><Eyebrow>{d}</Eyebrow></div>
        ))}
      </div>
      {weeks.map((days, wi) => (
        <div key={wi} style={{
          padding: '10px 24px',
          display: 'grid', gridTemplateColumns: '80px repeat(7, 1fr)', gap: 6,
          borderBottom: wi < weeks.length - 1 ? '1px solid var(--border-faint)' : 'none',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-muted)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
            v {wi + 1}
          </div>
          {days.map(d => {
            const t = getDayType(memberId, d);
            const dt = DAY_TYPES.find(x => x.id === t);
            const log = getLog(memberId, d);
            const isToday = dKey(d) === dKey(TODAY);
            const isFuture = d > TODAY;
            return (
              <button
                key={dKey(d)}
                onClick={() => onPick(d)}
                style={{
                  textAlign: 'left', cursor: 'pointer',
                  padding: '10px 10px',
                  border: `1px solid ${isToday ? 'var(--signal)' : 'var(--border)'}`,
                  background: isToday ? 'var(--signal-tint)' : isFuture ? 'var(--ink-25)' : 'var(--bg-raised)',
                  borderRadius: 4,
                  display: 'flex', flexDirection: 'column', gap: 6,
                  opacity: isFuture ? 0.7 : 1,
                }}
              >
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 500, fontVariantNumeric: 'tabular-nums', color: 'var(--fg)' }}>
                    {d.getDate()}/{d.getMonth() + 1}
                  </span>
                  <span style={{ width: 6, height: 6, borderRadius: 999, background: dt?.dot || 'var(--ink-150)' }} />
                </div>
                <span style={{ fontFamily: 'var(--font-sans)', fontSize: 11, color: 'var(--fg-muted)' }}>
                  {dt?.label}
                </span>
                {log && (
                  <span style={{
                    fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.08em', textTransform: 'uppercase',
                    color: log.done === 'ja' ? 'var(--success)' : log.done === 'delvis' ? 'var(--warning)' : 'var(--fg-faint)',
                    fontWeight: 500,
                  }}>
                    {log.done === 'ja' ? '✓ klar' : log.done === 'delvis' ? '~ delvis' : '— miss'}
                  </span>
                )}
              </button>
            );
          })}
        </div>
      ))}
    </Card>
  );
}

const navBtn = {
  width: 36, height: 36,
  border: '1px solid var(--border-strong)', borderRadius: 4,
  background: 'var(--bg-raised)', cursor: 'pointer',
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  color: 'var(--fg)',
};

// ============================================================================
// TableView — one row per day, all log fields inline-editable for bulk editing.
// ============================================================================
function TableView({ memberId, refresh }) {
  const [scope, setScope] = useState('past');  // 'past' | 'all'
  const [, bump] = useState(0);
  const tick = () => { bump(b => b + 1); refresh?.(); };

  const allDays = useMemo(() => {
    const out = [];
    for (let i = 0; i < window.PERIOD_WEEKS * 7; i++) {
      out.push(window.addDays(window.PERIOD_START, i));
    }
    return out;
  }, [memberId]);

  const days = scope === 'past'
    ? allDays.filter(d => d <= window.TODAY)
    : allDays;

  const update = (date, patch) => {
    const current = window.getLog(memberId, date) || {};
    window.setLog(memberId, date, { ...current, ...patch });
    tick();
  };

  const setType = (date, t) => { window.setDayType(memberId, date, t); tick(); };

  // Grid template: Datum (62) · Vecka (28) · Dagtyp (96) · Klar (96) ·
  // 4 block checks (28 each = 112) · Energi (88) · Sömn (60) · Kommentar (flex)
  const grid = '62px 28px 96px 96px 28px 28px 28px 28px 88px 60px minmax(140px, 1fr)';

  return (
    <div>
      {/* Scope toggle */}
      <div style={{ marginBottom: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
        <Segmented
          options={[
            { value: 'past', label: 'Hittills' },
            { value: 'all',  label: 'Hela säsongen' },
          ]}
          value={scope}
          onChange={setScope}
          size="sm"
        />
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-subtle)', letterSpacing: '0.04em' }}>
          {days.length} dagar · klicka i celler för att ändra
        </div>
      </div>

      <Card pad={0} style={{ overflow: 'hidden' }}>
        {/* Header */}
        <div style={{
          display: 'grid', gridTemplateColumns: grid, gap: 0,
          padding: '10px 16px',
          borderBottom: '1px solid var(--border)',
          background: 'var(--ink-25)',
          alignItems: 'center',
          position: 'sticky', top: 0, zIndex: 1,
        }}>
          <ColH>Datum</ColH>
          <ColH align="center">V</ColH>
          <ColH>Dagtyp</ColH>
          <ColH>Klar</ColH>
          <ColH align="center" title="Snabbhet">Sn</ColH>
          <ColH align="center" title="Styrka">St</ColH>
          <ColH align="center" title="Kondition">Ko</ColH>
          <ColH align="center" title="Rörlighet">Rö</ColH>
          <ColH>Energi</ColH>
          <ColH>Sömn</ColH>
          <ColH>Kommentar</ColH>
        </div>

        {/* Rows */}
        <div style={{ maxHeight: '70vh', overflowY: 'auto' }}>
          {days.map((d, i) => {
            const log = window.getLog(memberId, d) || {};
            const type = window.getDayType(memberId, d);
            const dt = DAY_TYPES.find(x => x.id === type);
            const isToday = dKey(d) === dKey(window.TODAY);
            const isFuture = d > window.TODAY;
            const wk = window.weekNumber(d);
            return (
              <div key={dKey(d)} style={{
                display: 'grid', gridTemplateColumns: grid, gap: 0,
                padding: '8px 16px',
                alignItems: 'center',
                borderBottom: i < days.length - 1 ? '1px solid var(--border-faint)' : 'none',
                background: isToday ? 'var(--signal-tint, rgba(14,133,67,0.06))' : isFuture ? 'var(--ink-25)' : 'transparent',
                opacity: isFuture ? 0.65 : 1,
              }}>
                {/* Datum */}
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontVariantNumeric: 'tabular-nums', color: 'var(--fg)' }}>
                  <div style={{ fontWeight: isToday ? 600 : 500 }}>{d.getDate()}/{d.getMonth() + 1}</div>
                  <div style={{ fontSize: 10, color: 'var(--fg-subtle)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                    {['sön','mån','tis','ons','tor','fre','lör'][d.getDay()]}
                  </div>
                </div>

                {/* Vecka */}
                <div style={{ textAlign: 'center', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-muted)', fontVariantNumeric: 'tabular-nums' }}>
                  {wk}
                </div>

                {/* Dagtyp */}
                <div>
                  <select
                    value={type || 'normal'}
                    onChange={e => setType(d, e.target.value)}
                    style={selectStyle(dt?.dot)}
                  >
                    {DAY_TYPES.map(x => (
                      <option key={x.id} value={x.id}>{x.label}</option>
                    ))}
                  </select>
                </div>

                {/* Klar — 3 tiny pill buttons */}
                <DoneCell value={log.done} onChange={v => update(d, { done: v })} />

                {/* 4 block checks */}
                <CheckCell checked={!!log.sn} onClick={() => update(d, { sn: !log.sn })} />
                <CheckCell checked={!!log.st} onClick={() => update(d, { st: !log.st })} />
                <CheckCell checked={!!log.ko} onClick={() => update(d, { ko: !log.ko })} />
                <CheckCell checked={!!log.ro} onClick={() => update(d, { ro: !log.ro })} />

                {/* Energi 1–5 dots */}
                <EnergiCell value={log.energi} onChange={v => update(d, { energi: v })} />

                {/* Sömn */}
                <input
                  type="number" step="0.5" min="0" max="14"
                  value={log.somn ?? ''}
                  onChange={e => update(d, { somn: e.target.value === '' ? null : parseFloat(e.target.value) })}
                  placeholder="—"
                  style={{
                    width: 50, padding: '4px 6px', textAlign: 'right',
                    fontFamily: 'var(--font-mono)', fontSize: 12, fontVariantNumeric: 'tabular-nums',
                    border: '1px solid var(--border)', borderRadius: 3,
                    background: 'var(--bg-raised)', color: 'var(--fg)', outline: 'none',
                  }}
                />

                {/* Kommentar */}
                <input
                  type="text"
                  value={log.kom ?? ''}
                  onChange={e => update(d, { kom: e.target.value })}
                  placeholder="—"
                  style={{
                    width: '100%', padding: '4px 8px',
                    fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--fg)',
                    border: '1px solid transparent', borderRadius: 3,
                    background: 'transparent', outline: 'none',
                  }}
                  onFocus={e => { e.target.style.borderColor = 'var(--signal)'; e.target.style.background = 'var(--bg-raised)'; }}
                  onBlur={e => { e.target.style.borderColor = 'transparent'; e.target.style.background = 'transparent'; }}
                />
              </div>
            );
          })}
        </div>
      </Card>
    </div>
  );
}

function ColH({ children, align = 'left', title }) {
  return (
    <div title={title} style={{
      fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 500,
      letterSpacing: '0.10em', textTransform: 'uppercase',
      color: 'var(--fg-subtle)', textAlign: align,
      paddingRight: 8,
    }}>{children}</div>
  );
}

function selectStyle(dot) {
  return {
    width: '100%', maxWidth: 88, padding: '4px 6px',
    fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--fg)',
    border: '1px solid var(--border)', borderRadius: 3,
    background: 'var(--bg-raised)', outline: 'none', cursor: 'pointer',
    backgroundImage: dot ? `linear-gradient(${dot}, ${dot})` : undefined,
    backgroundSize: dot ? '6px 6px' : undefined,
    backgroundRepeat: 'no-repeat',
    backgroundPosition: '8px center',
    paddingLeft: dot ? 20 : 6,
  };
}

function DoneCell({ value, onChange }) {
  const opts = [
    { v: 'ja',     label: '✓', tip: 'Klar',  color: 'var(--success)' },
    { v: 'delvis', label: '~', tip: 'Delvis', color: 'var(--warning)' },
    { v: 'nej',    label: '–', tip: 'Miss',   color: 'var(--fg-faint)' },
  ];
  return (
    <div style={{ display: 'flex', gap: 3 }}>
      {opts.map(o => {
        const sel = value === o.v;
        return (
          <button
            key={o.v}
            title={o.tip}
            onClick={() => onChange(sel ? null : o.v)}
            style={{
              width: 26, height: 24, padding: 0,
              border: `1px solid ${sel ? o.color : 'var(--border)'}`,
              background: sel ? o.color : 'var(--bg-raised)',
              color: sel ? '#fff' : 'var(--fg-muted)',
              borderRadius: 3, cursor: 'pointer',
              fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }}
          >{o.label}</button>
        );
      })}
    </div>
  );
}

function CheckCell({ checked, onClick }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'center' }}>
      <button
        onClick={onClick}
        style={{
          width: 20, height: 20, padding: 0,
          border: `1.5px solid ${checked ? 'var(--signal)' : 'var(--border-strong)'}`,
          background: checked ? 'var(--signal)' : 'transparent',
          borderRadius: 3, cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}
      >
        {checked && (
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="20 6 9 17 4 12" />
          </svg>
        )}
      </button>
    </div>
  );
}

function EnergiCell({ value, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 2 }}>
      {[1, 2, 3, 4, 5].map(n => {
        const sel = value === n;
        return (
          <button
            key={n}
            onClick={() => onChange(sel ? null : n)}
            title={`${n}`}
            style={{
              width: 14, height: 16, padding: 0,
              border: '1px solid ' + (sel ? 'var(--ink-950)' : 'var(--border)'),
              background: sel ? 'var(--ink-950)' : 'var(--bg-raised)',
              color: sel ? '#fff' : 'var(--fg-muted)',
              borderRadius: 2, cursor: 'pointer',
              fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 500,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }}
          >{n}</button>
        );
      })}
    </div>
  );
}

window.LoggScreen = LoggScreen;
