// screens3.jsx — Progress + Calendar + Profile

function ProgressScreen() {
  const c = useTheme();
  const [tab, setTab] = React.useState('Weight');
  const [exId, setExId] = React.useState('bench');
  const series = WEIGHT_SERIES[exId];
  const dispSeries = series.map(c.toDisp);
  const delta = dispSeries[dispSeries.length - 1] - dispSeries[0];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <ScreenHeader eyebrow="Last 10 weeks" title="Progress" />
      {c.cleared ? (
        <Card pad={28} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, textAlign: 'center' }}>
          <span style={{ color: 'var(--dim)' }}><Icon name="progress" size={40} /></span>
          <Display size={22}>No history yet</Display>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--muted)', maxWidth: 240, lineHeight: 1.4 }}>
            Log a workout and your weight, volume and streak charts will start building here.
          </div>
        </Card>
      ) : (
      <>
      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', margin: '0 -20px', padding: '0 20px 2px' }}>
        {['Weight', 'Volume', 'Reps', 'Streak'].map(t => <Chip key={t} active={tab === t} onClick={() => setTab(t)}>{t}</Chip>)}
      </div>

      {tab === 'Weight' && (
        <>
          <div style={{ display: 'flex', gap: 8, overflowX: 'auto', margin: '0 -20px', padding: '0 20px 2px' }}>
            {[['bench', 'Bench'], ['squat', 'Squat'], ['deadlift', 'Deadlift'], ['ohp', 'OHP']].map(([id, l]) =>
              <Chip key={id} active={exId === id} onClick={() => setExId(id)} style={{ borderStyle: 'dashed' }}>{l}</Chip>)}
          </div>
          <Card pad={16}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 10 }}>
              <div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 40, color: 'var(--text)', lineHeight: 0.9 }}>{dispSeries[dispSeries.length - 1]}</span>
                  <span style={{ fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 700, color: 'var(--muted)' }}>{c.wtLabel} working set</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 5, color: c.accent, fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 700 }}>
                  <Icon name="progress" size={15} />+{delta} {c.wtLabel} since week 1
                </div>
              </div>
            </div>
            <LineChart data={dispSeries} labels={SERIES_LABELS} accent={c.accent} muted={c.dim} text={c.muted} height={170} />
          </Card>
        </>
      )}

      {tab === 'Volume' && (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <StatTile icon="bolt" label="Last session" value={c.abbrWt(18600)} unit={c.wtLabel} />
            <StatTile icon="progress" label="Avg / session" value={c.abbrWt(16000)} unit={c.wtLabel} />
          </div>
          <Card pad={16}>
            <Eyebrow style={{ marginBottom: 12 }}>Total volume per session (lb)</Eyebrow>
            <BarChart data={VOLUME_SERIES} accent={c.accent} text={c.muted} surface={c.surface3} height={180} />
          </Card>
        </>
      )}

      {tab === 'Reps' && (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <StatTile icon="check" label="Last session" value="174" unit="reps" />
            <StatTile icon="progress" label="Avg / session" value="146" unit="reps" />
          </div>
          <Card pad={16}>
            <Eyebrow style={{ marginBottom: 12 }}>Reps completed per session</Eyebrow>
            <BarChart data={REPS_SERIES.map(r => ({ label: r.label, value: r.reps }))} accent={c.accent} text={c.muted} surface={c.surface3} height={180} />
          </Card>
        </>
      )}

      {tab === 'Streak' && (
        <>
          <Card pad={20} style={{ display: 'flex', alignItems: 'center', gap: 18,
            background: `radial-gradient(120% 90% at 90% 0%, ${c.accent}1f, transparent 55%), var(--surface)` }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 64, color: c.accent, lineHeight: 0.8 }}>{PROFILE.stats.streak}</div>
              <Eyebrow style={{ marginTop: 6 }}>Day streak</Eyebrow>
            </div>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div><div style={{ fontFamily: 'var(--font-display)', fontSize: 24, color: 'var(--text)' }}>{PROFILE.stats.bestStreak}</div><Eyebrow>Best ever</Eyebrow></div>
              <div><div style={{ fontFamily: 'var(--font-display)', fontSize: 24, color: 'var(--text)' }}>{PROFILE.stats.workouts}</div><Eyebrow>Total workouts</Eyebrow></div>
            </div>
          </Card>
          <Card pad={16}>
            <Eyebrow style={{ marginBottom: 12 }}>Consistency · last 12 weeks</Eyebrow>
            <Heatmap values={HEATMAP} accent={c.accent} empty={c.surface3} />
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 6, marginTop: 12 }}>
              <span style={{ fontFamily: 'var(--font-body)', fontSize: 10.5, color: 'var(--dim)' }}>Less</span>
              {[0, 1, 2, 3].map(v => <div key={v} style={{ width: 12, height: 12, borderRadius: 3.5,
                background: v === 0 ? c.surface3 : c.accent + Math.round((v === 1 ? 0.35 : v === 2 ? 0.62 : 1) * 255).toString(16).padStart(2, '0') }} />)}
              <span style={{ fontFamily: 'var(--font-body)', fontSize: 10.5, color: 'var(--dim)' }}>More</span>
            </div>
          </Card>
        </>
      )}
      </>
      )}
    </div>
  );
}

// ── CALENDAR ─────────────────────────────────────────────────
function CalendarScreen() {
  const c = useTheme();
  const today = new Date();
  const [view, setView] = React.useState({ y: today.getFullYear(), m: today.getMonth() });
  const [sel, setSel] = React.useState(today.getDate());

  const first = new Date(view.y, view.m, 1);
  const startDow = (first.getDay() + 6) % 7; // Mon=0
  const daysInMonth = new Date(view.y, view.m + 1, 0).getDate();
  const isCurMonth = view.y === today.getFullYear() && view.m === today.getMonth();

  function statusOf(day) {
    const d = new Date(view.y, view.m, day);
    const idx = (d.getDay() + 6) % 7;
    if (WEEK_SPLIT[idx].rest) return 'rest';
    const t0 = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    if (d.getTime() === t0.getTime()) return 'today';
    if (d > t0) return 'planned';
    if (c.cleared) return 'planned';
    return (day % 11 === 4) ? 'missed' : 'done';
  }

  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);

  const monthName = first.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
  const shift = (dir) => setView(v => {
    let m = v.m + dir, y = v.y;
    if (m < 0) { m = 11; y--; } if (m > 11) { m = 0; y++; }
    return { y, m };
  });

  const selStatus = statusOf(sel);
  const selDow = (new Date(view.y, view.m, sel).getDay() + 6) % 7;
  const selDay = WEEK_SPLIT[selDow];

  const dotStyle = (st) => {
    if (st === 'done') return { background: c.accent, color: c.accentInk, border: 'none' };
    if (st === 'missed') return { background: 'transparent', color: c.danger, border: `1.5px solid ${c.danger}` };
    if (st === 'today') return { background: 'transparent', color: c.accent, border: `2px solid ${c.accent}` };
    if (st === 'rest') return { background: 'var(--surface-2)', color: 'var(--dim)', border: '1px solid var(--border)' };
    return { background: 'transparent', color: 'var(--muted)', border: '1px solid var(--border)' }; // planned
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <ScreenHeader eyebrow="Your history" title="Calendar" />
      <Card pad={16}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <button onClick={() => shift(-1)} style={{ background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 999, width: 34, height: 34, color: 'var(--text)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="chevL" size={16} /></button>
          <Display size={22}>{monthName}</Display>
          <button onClick={() => shift(1)} style={{ background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 999, width: 34, height: 34, color: 'var(--text)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="chevR" size={16} /></button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 4, marginBottom: 8 }}>
          {['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((d, i) => <div key={i} style={{ textAlign: 'center', fontFamily: 'var(--font-body)', fontSize: 10.5, fontWeight: 700, color: 'var(--dim)' }}>{d}</div>)}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 4 }}>
          {cells.map((d, i) => {
            if (!d) return <div key={i} />;
            const st = statusOf(d);
            const isSel = d === sel;
            return (
              <button key={i} onClick={() => setSel(d)} style={{ aspectRatio: '1', borderRadius: 11, cursor: 'pointer',
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 3,
                background: isSel ? 'var(--surface-3)' : 'transparent', border: 'none', position: 'relative' }}>
                <span style={{ fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: st === 'today' ? 800 : 600,
                  color: st === 'planned' || st === 'rest' ? 'var(--muted)' : 'var(--text)' }}>{d}</span>
                <span style={{ width: st === 'done' || st === 'missed' || st === 'today' ? 7 : 5, height: st === 'done' || st === 'missed' || st === 'today' ? 7 : 5,
                  borderRadius: 999, ...dotStyle(st), display: 'inline-block' }} />
              </button>
            );
          })}
        </div>
      </Card>

      {/* legend */}
      <div style={{ display: 'flex', gap: 16, justifyContent: 'center', flexWrap: 'wrap' }}>
        {[['done', 'Completed'], ['missed', 'Missed'], ['rest', 'Rest'], ['planned', 'Planned']].map(([k, l]) => (
          <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 9, height: 9, borderRadius: 999, ...dotStyle(k) }} />
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, fontWeight: 600, color: 'var(--muted)' }}>{l}</span>
          </div>
        ))}
      </div>

      {/* selected detail */}
      <Card pad={16} style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ width: 54, height: 54, borderRadius: 'var(--radius-sm)', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center', ...dotStyle(selStatus === 'planned' ? 'planned' : selStatus) }}>
          <Icon name={selStatus === 'done' ? 'check' : selStatus === 'missed' ? 'close' : selStatus === 'rest' ? 'heart' : 'dumbbell'} size={24} />
        </div>
        <div style={{ flex: 1 }}>
          <Eyebrow>{new Date(view.y, view.m, sel).toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}</Eyebrow>
          <Display size={22} style={{ margin: '3px 0 4px' }}>
            {selStatus === 'done' ? 'Crushed it' : selStatus === 'missed' ? 'Missed day' : selStatus === 'rest' ? 'Rest day' : selStatus === 'today' ? 'On deck' : 'Upcoming'}
          </Display>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600, color: 'var(--muted)' }}>
            {selDay.rest ? selDay.muscles : `${selDay.focus} · ${selDay.muscles}`}
          </div>
        </div>
      </Card>
    </div>
  );
}

// ── PROFILE ──────────────────────────────────────────────────
function fmtTime12(hhmm) {
  const [h, m] = String(hhmm || '18:00').split(':').map(Number);
  const ap = h >= 12 ? 'PM' : 'AM';
  const h12 = h % 12 === 0 ? 12 : h % 12;
  return `${h12}:${String(m).padStart(2, '0')} ${ap}`;
}

function ProfileScreen({ openSheet, profile, settings }) {
  const c = useTheme();
  const p = profile || PROFILE;
  const st = settings || { unit: 'lb', reminderOn: true, reminderTime: '18:00', weeklyGoal: 5 };
  const weekDone = c.cleared ? 0 : HEATMAP.slice(-7).filter(v => v > 0).length;
  const goalPct = Math.min(100, Math.round((weekDone / Math.max(1, st.weeklyGoal)) * 100));

  const rows = [
    { kind: 'units', icon: 'ruler', label: 'Units', detail: st.unit === 'kg' ? 'Metric (kg)' : 'Imperial (lb)' },
    { kind: 'reminders', icon: 'bell', label: 'Reminders', detail: st.reminderOn ? 'Daily ' + fmtTime12(st.reminderTime) : 'Off' },
    { kind: 'goal', icon: 'target', label: 'Weekly goal', detail: st.weeklyGoal + ' / week' },
    { kind: 'preferences', icon: 'settings', label: 'Preferences', detail: '' },
    { kind: 'data', icon: 'share', label: 'Backup & export', detail: '' },
  ];

  const camBadge = (
    <div style={{ position: 'absolute', right: -2, bottom: -2, width: 26, height: 26, borderRadius: 999,
      background: c.accent, color: c.accentInk, display: 'flex', alignItems: 'center', justifyContent: 'center',
      border: '2px solid var(--surface)' }}>
      <Icon name="edit" size={13} />
    </div>
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <ScreenHeader eyebrow={'Member since ' + p.memberSince} title="Profile" right={<IconBtn name="share" onClick={() => openSheet('data')} />} />

      <Card pad={18} style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <div style={{ width: 74, height: 74, borderRadius: 999, overflow: 'hidden', border: `2px solid ${c.accent}` }}>
            <AppPhoto id="avatar" shape="circle" placeholderIcon="profile" placeholder="" maxDim={420}
              style={{ width: '100%', height: '100%' }} overlay={camBadge} />
          </div>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <Display size={26}>{p.name}</Display>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600, color: 'var(--muted)', marginTop: 3 }}>{p.handle}</div>
          <div style={{ display: 'inline-flex', marginTop: 8, padding: '4px 10px', borderRadius: 999, background: c.accent, color: c.accentInk,
            fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>{p.level}</div>
        </div>
        <button onClick={() => openSheet('edit-profile')} style={{ background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 999, width: 38, height: 38, color: 'var(--text)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="edit" size={18} /></button>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
        <StatTile icon="dumbbell" label="Workouts" value={c.cleared ? 0 : p.stats.workouts} />
        <StatTile icon="flame" label="Streak" value={c.cleared ? 0 : p.stats.streak} unit="d" />
        <StatTile icon="bolt" label="Volume" value={c.abbrWt(c.cleared ? 0 : p.stats.totalVolume)} unit={c.wtLabel} />
      </div>

      {/* weekly goal */}
      <Card pad={16} style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <ProgressRing pct={goalPct} accent={c.accent} size={56} stroke={7} track={c.surface3}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 15, color: 'var(--text)' }}>{weekDone}</span>
        </ProgressRing>
        <div style={{ flex: 1 }}>
          <Eyebrow>This week</Eyebrow>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 700, color: 'var(--text)', marginTop: 3 }}>
            {weekDone} of {st.weeklyGoal} workouts
          </div>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--muted)' }}>
            {weekDone >= st.weeklyGoal ? 'Goal smashed 🔥' : `${st.weeklyGoal - weekDone} to hit your goal`}
          </div>
        </div>
        <button onClick={() => openSheet('goal')} style={{ background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 999, width: 34, height: 34, color: 'var(--text)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="edit" size={16} /></button>
      </Card>

      <div>
        <Eyebrow style={{ marginBottom: 10 }}>Recent personal records</Eyebrow>
        {c.cleared ? (
          <Card pad={18} style={{ textAlign: 'center' }}>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--muted)' }}>No personal records yet — go set some.</div>
          </Card>
        ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {p.prs.map((pr, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: 13, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)' }}>
              <span style={{ color: c.accent }}><Icon name="trophy" size={22} /></span>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15, color: 'var(--text)' }}>{pr.ex}</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--muted)' }}>{pr.when}</div>
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, color: 'var(--text)' }}>{c.toDisp(pr.value)}<span style={{ fontSize: 11, color: 'var(--muted)', marginLeft: 3 }}>{c.wtLabel}</span></div>
            </div>
          ))}
        </div>
        )}
      </div>

      <div>
        <Eyebrow style={{ marginBottom: 10 }}>Settings</Eyebrow>
        <Card pad={0}>
          {rows.map((s, i) => (
            <div key={s.kind} onClick={() => openSheet(s.kind)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '14px 16px', borderTop: i ? '1px solid var(--border)' : 'none', cursor: 'pointer' }}>
              <span style={{ color: 'var(--muted)' }}><Icon name={s.icon} size={19} /></span>
              <span style={{ flex: 1, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15, color: 'var(--text)' }}>{s.label}</span>
              {s.detail && <span style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--muted)' }}>{s.detail}</span>}
              <span style={{ color: 'var(--dim)' }}><Icon name="chevR" size={16} /></span>
            </div>
          ))}
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { ProgressScreen, CalendarScreen, ProfileScreen });
