// screens2.jsx — Log + Library

// Big +/- stepper
function Stepper({ label, value, onChange, step = 1, unit, accentVal }) {
  const c = useTheme();
  const btn = (dir) => (
    <button onClick={() => onChange(Math.max(0, value + dir * step))} style={{
      width: 44, height: 44, borderRadius: 'var(--radius-sm)', border: '1px solid var(--border)',
      background: 'var(--surface-2)', color: 'var(--text)', cursor: 'pointer',
      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      <Icon name={dir < 0 ? 'minus' : 'plus'} size={20} />
    </button>
  );
  return (
    <div style={{ flex: 1 }}>
      <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase', color: 'var(--muted)', textAlign: 'center', marginBottom: 8 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        {btn(-1)}
        <div style={{ flex: 1, textAlign: 'center' }}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 38, color: accentVal ? c.accent : 'var(--text)', lineHeight: 0.9 }}>{value}</span>
          {unit && <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 700, color: 'var(--muted)', marginLeft: 3 }}>{unit}</span>}
        </div>
        {btn(1)}
      </div>
    </div>
  );
}

function RestTimer() {
  const c = useTheme();
  const [left, setLeft] = React.useState(0);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (left <= 0) { clearInterval(ref.current); return; }
    ref.current = setInterval(() => setLeft(l => l <= 1 ? 0 : l - 1), 1000);
    return () => clearInterval(ref.current);
  }, [left > 0]);
  const running = left > 0;
  const mm = String(Math.floor(left / 60)).padStart(1, '0');
  const ss = String(left % 60).padStart(2, '0');
  return (
    <button onClick={() => setLeft(running ? 0 : 90)} style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '8px 13px',
      borderRadius: 999, border: '1px solid ' + (running ? 'transparent' : 'var(--border)'),
      background: running ? c.accent : 'var(--surface-2)', color: running ? c.accentInk : 'var(--text)', cursor: 'pointer' }}>
      <Icon name="timer" size={16} />
      <span style={{ fontFamily: 'var(--font-display)', fontSize: 15, minWidth: running ? 34 : 'auto' }}>{running ? `${mm}:${ss}` : 'Rest'}</span>
    </button>
  );
}

function LogScreen({ plan, addSet, toggleSet, removeSet, go }) {
  const c = useTheme();
  const [sel, setSel] = React.useState(0);
  const ex = plan.exercises[sel] ? exById(plan.exercises[sel].id) : null;
  const last = plan.exercises[sel]?.sets.slice(-1)[0];
  const [reps, setReps] = React.useState(last?.reps || 10);
  const [weight, setWeight] = React.useState(() => c.toDisp(last?.weight || 45));

  React.useEffect(() => {
    const l = plan.exercises[sel]?.sets.slice(-1)[0];
    setReps(l?.reps || 10); setWeight(c.toDisp(l?.weight || 45));
  }, [sel, c.unit]);

  const cur = plan.exercises[sel];
  const vol = cur ? cur.sets.reduce((s, x) => s + x.reps * x.weight, 0) : 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <ScreenHeader eyebrow="Active session" title="Log" right={<RestTimer />} />

      {/* exercise selector */}
      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', margin: '0 -20px', padding: '0 20px 2px', WebkitOverflowScrolling: 'touch' }}>
        {plan.exercises.map((e, i) => {
          const x = exById(e.id);
          const allDone = e.sets.every(s => s.done);
          return (
            <Chip key={e.id} active={i === sel} onClick={() => setSel(i)}
              style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              {allDone && <span style={{ display: 'flex' }}><Icon name="check" size={13} /></span>}{x.name}
            </Chip>
          );
        })}
        <Chip onClick={() => go('library')} style={{ display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="plus" size={14} />Add</Chip>
      </div>

      {ex && cur && (
        <Card pad={18} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <Display size={26}>{ex.name}</Display>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 600, color: 'var(--muted)', marginTop: 4 }}>{ex.muscle} · {ex.gear}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, color: c.accent }}>{c.abbrWt(vol)}</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 10, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', color: 'var(--dim)' }}>{c.wtLabel} volume</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 14 }}>
            <Stepper label="Reps" value={reps} onChange={setReps} step={1} accentVal />
            <div style={{ width: 1, background: 'var(--border)' }} />
            <Stepper label="Weight" value={weight} onChange={setWeight} step={c.wtStep} unit={c.wtLabel} />
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            {c.wtPresets.map(w => (
              <button key={w} onClick={() => setWeight(w)} style={{ flex: 1, padding: '8px 0', borderRadius: 8, cursor: 'pointer',
                border: '1px solid var(--border)', background: weight === w ? 'var(--surface-3)' : 'transparent',
                fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 700, color: weight === w ? 'var(--text)' : 'var(--muted)' }}>{w}</button>
            ))}
          </div>
          <AccentButton onClick={() => addSet(sel, { reps, weight: c.toLb(weight), done: true })} icon={<Icon name="plus" size={18} />}>Add Set</AccentButton>
        </Card>
      )}

      {cur && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <Eyebrow>Logged sets · {cur.sets.filter(s => s.done).length}/{cur.sets.length}</Eyebrow>
          {cur.sets.map((s, si) => (
            <div key={si} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
              background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)' }}>
              <span style={{ width: 26, height: 26, borderRadius: 7, background: s.done ? c.accent : 'var(--surface-2)', color: s.done ? c.accentInk : 'var(--muted)',
                fontFamily: 'var(--font-display)', fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{si + 1}</span>
              <span style={{ flex: 1, fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15, color: 'var(--text)' }}>{s.reps} <span style={{ color: 'var(--muted)', fontWeight: 600, fontSize: 12 }}>reps</span> &nbsp;×&nbsp; {c.toDisp(s.weight)} <span style={{ color: 'var(--muted)', fontWeight: 600, fontSize: 12 }}>{c.wtLabel}</span></span>
              <button onClick={() => toggleSet(sel, si)} style={{ width: 28, height: 28, borderRadius: 8, cursor: 'pointer', border: '1px solid ' + (s.done ? 'transparent' : 'var(--border)'),
                background: s.done ? c.accent : 'transparent', color: c.accentInk, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{s.done && <Icon name="check" size={15} />}</button>
              <button onClick={() => removeSet(sel, si)} style={{ background: 'none', border: 'none', color: 'var(--dim)', cursor: 'pointer', display: 'flex', padding: 2 }}><Icon name="trash" size={17} /></button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── LIBRARY ──────────────────────────────────────────────────
function LibraryScreen({ library, openSheet, addToPlan }) {
  const c = useTheme();
  const [q, setQ] = React.useState('');
  const [muscle, setMuscle] = React.useState('All');
  const filtered = library.filter(e =>
    (muscle === 'All' || e.muscle === muscle) &&
    e.name.toLowerCase().includes(q.toLowerCase()));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <ScreenHeader eyebrow={library.length + ' exercises'} title="Library"
        right={<IconBtn name="plus" active onClick={() => openSheet('add-exercise')} />} />

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 14px', height: 46,
        background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 999 }}>
        <span style={{ color: 'var(--muted)' }}><Icon name="search" size={18} /></span>
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search exercises"
          style={{ flex: 1, background: 'none', border: 'none', outline: 'none', color: 'var(--text)',
            fontFamily: 'var(--font-body)', fontSize: 15 }} />
        {q && <span onClick={() => setQ('')} style={{ color: 'var(--dim)', cursor: 'pointer', display: 'flex' }}><Icon name="close" size={16} /></span>}
      </div>

      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', margin: '0 -20px', padding: '0 20px 2px' }}>
        {['All', ...MUSCLES].map(m => <Chip key={m} active={muscle === m} onClick={() => setMuscle(m)}>{m}</Chip>)}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
        {filtered.map(e => (
          <div key={e.id} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: 13,
            background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)' }}>
            <div style={{ width: 40, height: 40, borderRadius: 'var(--radius-sm)', background: 'var(--surface-2)', color: 'var(--muted)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="dumbbell" size={19} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15, color: 'var(--text)', display: 'flex', alignItems: 'center', gap: 7 }}>
                {e.name}
                {e.custom && <span style={{ fontFamily: 'var(--font-body)', fontSize: 9, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase', color: c.accentInk, background: c.accent, padding: '2px 6px', borderRadius: 5 }}>Custom</span>}
              </div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--muted)' }}>{e.muscle} · {e.gear}</div>
            </div>
            <button onClick={() => addToPlan(e.id)} style={{ width: 34, height: 34, borderRadius: 999, border: '1px solid var(--border)',
              background: 'var(--surface-2)', color: c.accent, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name="plus" size={18} />
            </button>
          </div>
        ))}
        {filtered.length === 0 && <div style={{ textAlign: 'center', color: 'var(--dim)', fontFamily: 'var(--font-body)', padding: 30 }}>No matches.</div>}
      </div>
    </div>
  );
}

Object.assign(window, { LogScreen, LibraryScreen, Stepper, RestTimer });
