// screens-2.jsx — Exercise detail (with set logging + feedback flow), History, Health, Goals, Assessments, Side menu

// ─── Exercise Detail (the meatiest screen) ───────────────────────────────
function ExerciseDetailScreen({ theme, cardStyle, exercise, onBack, onUpdateSet, onOpenFeedback, onMarkDone, weightUnit }) {
  const [expanded, setExpanded] = React.useState(true);
  const ex = exercise;
  if (!ex) return null;
  const wtLabel = `Weight (${weightUnit || 'lb'})`;

  return (
    <>
      <TopBar theme={theme} title={ex.name} onBack={onBack}
        right={<div style={{
          padding: '6px 10px', borderRadius: 9999, fontSize: 11, fontWeight: 600,
          background: theme.isDark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)',
          color: theme.muted, fontFamily: theme.uiFamily,
        }}>Main · {(EXERCISES.findIndex(e => e.id === ex.id) + 1)}/{EXERCISES.length}</div>}
      />

      <div style={{ padding: '0 18px 110px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {/* Video placeholder */}
        <div style={{
          aspectRatio: '16/9', borderRadius: theme.radius, overflow: 'hidden',
          background: theme.isDark ? '#0a0a0a' : '#1a1a1d',
          position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center',
          backgroundImage: 'repeating-linear-gradient(45deg, rgba(255,255,255,0.02) 0 10px, transparent 10px 20px)',
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: 9999, background: theme.primary,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 8px 24px rgba(0,0,0,0.3)',
          }}>
            <Icon name="play" size={22} color={theme.primaryInk}/>
          </div>
          <div style={{
            position: 'absolute', bottom: 10, left: 12, right: 12,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <span style={{
              padding: '4px 8px', borderRadius: 6,
              background: 'rgba(0,0,0,0.6)', color: '#fff',
              fontFamily: theme.monoFamily, fontSize: 10, fontWeight: 500,
            }}>DEMO · 0:42</span>
            <span style={{
              padding: '4px 8px', borderRadius: 6,
              background: 'rgba(0,0,0,0.6)', color: '#fff',
              fontFamily: theme.uiFamily, fontSize: 10, fontWeight: 500,
            }}>video placeholder</span>
          </div>
        </div>

        {/* Exercise meta */}
        <div>
          <div style={{ fontFamily: theme.uiFamily, fontSize: 13, color: theme.muted, lineHeight: 1.45 }}>
            {ex.detail}
          </div>
          {/* MGJA tags */}
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 10 }}>
            {ex.mg && ex.mg.map(m => (
              <Tag key={`mg-${m}`} theme={theme} kind="mg" label={m}/>
            ))}
            {ex.j && ex.j.map(j => (
              <Tag key={`j-${j}`} theme={theme} kind="j" label={j}/>
            ))}
            {ex.a && ex.a.map(a => (
              <Tag key={`a-${a}`} theme={theme} kind="a" label={a}/>
            ))}
          </div>
        </div>

        {/* Trainer flag note */}
        {ex.flagged && ex.flagNote && (
          <Card theme={theme} cardStyle={cardStyle} padding={12} style={{
            background: theme.isDark ? 'rgba(255,77,77,0.08)' : 'rgba(199,39,39,0.06)',
            borderColor: theme.danger,
          }}>
            <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
              <div style={{ width: 8, height: 8, borderRadius: 9999, background: theme.danger, marginTop: 6, flexShrink: 0 }}/>
              <div>
                <div style={{ fontFamily: theme.uiFamily, fontSize: 11, fontWeight: 600, color: theme.danger, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                  Trainer flag
                </div>
                <div style={{ fontFamily: theme.uiFamily, fontSize: 13, color: theme.text, marginTop: 3, lineHeight: 1.4 }}>
                  {ex.flagNote}
                </div>
              </div>
            </div>
          </Card>
        )}

        {/* Set log table */}
        <Card theme={theme} cardStyle={cardStyle} padding={0}>
          <div style={{
            display: 'flex', alignItems: 'center', padding: '12px 14px',
            borderBottom: `1px solid ${theme.border}`,
          }}>
            <div style={{ fontFamily: theme.uiFamily, fontSize: 14, fontWeight: 600, color: theme.text, flex: 1 }}>
              Set log
            </div>
            <button onClick={() => setExpanded(!expanded)} style={{
              background: 'transparent', border: 'none', cursor: 'pointer',
              display: 'flex', alignItems: 'center', gap: 4,
              fontFamily: theme.uiFamily, fontSize: 11, fontWeight: 600, color: theme.primary,
            }}>
              {expanded ? 'Collapse' : 'Expand'}
              <Icon name="chevronDown" size={12} color={theme.primary}/>
            </button>
          </div>

          {/* Header row */}
          <div style={{
            display: 'grid', gridTemplateColumns: '32px 1fr 1fr 50px 32px',
            gap: 8, padding: '10px 14px',
            fontFamily: theme.uiFamily, fontSize: 10, fontWeight: 600,
            color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.5,
            background: theme.isDark ? 'rgba(255,255,255,0.02)' : 'rgba(0,0,0,0.02)',
          }}>
            <div>Set</div><div>Reps</div><div>{wtLabel}</div><div>RPE</div><div></div>
          </div>

          {ex.sets.map((set, i) => (
            <SetRow key={i} theme={theme} index={i} set={set}
              onUpdate={(patch) => onUpdateSet(ex.id, i, patch)}
              onFeedback={() => onOpenFeedback({ exerciseId: ex.id, setIndex: i, exerciseName: ex.name })}
            />
          ))}

          {/* Add set */}
          <div style={{
            padding: '10px 14px', borderTop: `1px solid ${theme.border}`,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <button style={{
              flex: 1, padding: '8px 10px', borderRadius: 8,
              background: 'transparent', border: `1px dashed ${theme.border}`,
              fontFamily: theme.uiFamily, fontSize: 12, fontWeight: 500, color: theme.muted,
              cursor: 'pointer',
            }}>+ Add set</button>
            <button style={{
              flex: 1, padding: '8px 10px', borderRadius: 8,
              background: 'transparent', border: `1px dashed ${theme.border}`,
              fontFamily: theme.uiFamily, fontSize: 12, fontWeight: 500, color: theme.muted,
              cursor: 'pointer',
            }}>Swap exercise</button>
          </div>
        </Card>

        {/* Last session comparison */}
        <Card theme={theme} cardStyle={cardStyle} padding={12}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <Icon name="history" size={14} color={theme.muted}/>
            <div style={{ fontFamily: theme.uiFamily, fontSize: 11, fontWeight: 600, color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              Apr 24 · last session
            </div>
          </div>
          <div style={{ display: 'flex', gap: 16 }}>
            <Stat theme={theme} label="Top set" value="30 lb × 12"/>
            <Stat theme={theme} label="Volume" value="900 lb"/>
            <Stat theme={theme} label="Avg RPE" value="6.5"/>
          </div>
        </Card>

        {/* Bottom action row */}
        <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
          <button onClick={() => onOpenFeedback({ exerciseId: ex.id, exerciseName: ex.name })}
            style={{
              flex: 1, padding: '12px',
              borderRadius: theme.radius, background: 'transparent', color: theme.text,
              border: `1px solid ${theme.border}`,
              fontFamily: theme.uiFamily, fontSize: 13, fontWeight: 600,
              cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}>
            <Icon name="message" size={14} color={theme.text}/> Feedback
          </button>
          <button onClick={() => onMarkDone(ex.id)} style={{
            flex: 2, padding: '12px',
            borderRadius: theme.radius, background: theme.primary, color: theme.primaryInk,
            border: 'none', fontFamily: theme.uiFamily, fontSize: 13, fontWeight: 600,
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
          }}>
            <Icon name="check" size={16} color={theme.primaryInk} strokeWidth={2.6}/> Mark exercise done
          </button>
        </div>
      </div>
    </>
  );
}

function Tag({ theme, kind, label }) {
  const styles = {
    mg: { color: theme.primary, bg: theme.isDark ? 'rgba(232,131,11,0.12)' : 'rgba(232,131,11,0.08)' },
    j:  { color: theme.accent,  bg: theme.isDark ? 'rgba(255,77,77,0.12)' : 'rgba(122,16,16,0.06)' },
    a:  { color: theme.muted,   bg: theme.isDark ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.04)' },
  };
  const s = styles[kind];
  return (
    <span style={{
      fontFamily: theme.uiFamily, fontSize: 10, fontWeight: 500,
      padding: '3px 7px', borderRadius: 9999,
      background: s.bg, color: s.color,
      letterSpacing: 0.2,
    }}>
      <span style={{ opacity: 0.6, marginRight: 3, fontSize: 9 }}>{kind.toUpperCase()}</span>{label}
    </span>
  );
}

function Stat({ theme, label, value }) {
  return (
    <div style={{ flex: 1 }}>
      <div style={{ fontFamily: theme.uiFamily, fontSize: 10, color: theme.muted, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.5 }}>{label}</div>
      <div style={{ fontFamily: theme.monoFamily, fontSize: 14, fontWeight: 600, color: theme.text, marginTop: 2 }}>{value}</div>
    </div>
  );
}

function SetRow({ theme, index, set, onUpdate, onFeedback }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '32px 1fr 1fr 50px 32px',
      gap: 8, padding: '8px 14px', alignItems: 'center',
      borderTop: `0.5px solid ${theme.border}`,
      background: set.done ? (theme.isDark ? 'rgba(52,211,153,0.06)' : 'rgba(46,125,50,0.04)') : 'transparent',
    }}>
      <div style={{ fontFamily: theme.monoFamily, fontSize: 12, color: theme.muted, fontWeight: 600 }}>
        {index + 1}
      </div>
      <NumInput theme={theme} value={set.reps} suffix="" onChange={v => onUpdate({ reps: v })}/>
      <NumInput theme={theme} value={set.weight} suffix="" onChange={v => onUpdate({ weight: v })}/>
      <div style={{
        fontFamily: theme.monoFamily, fontSize: 12, fontWeight: 600,
        textAlign: 'left', color: set.rpe ? theme.text : theme.muted,
      }}>{set.rpe ?? '—'}</div>
      <div onClick={() => onUpdate({ done: !set.done })} style={{
        width: 24, height: 24, borderRadius: 6,
        background: set.done ? theme.success : 'transparent',
        border: set.done ? 'none' : `1.5px solid ${theme.border}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', justifySelf: 'end',
      }}>
        {set.done && <Icon name="check" size={14} color="#fff" strokeWidth={3}/>}
      </div>
    </div>
  );
}

function NumInput({ theme, value, suffix, onChange }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
      <div style={{
        display: 'inline-flex', alignItems: 'baseline', gap: 3,
        padding: '4px 6px', borderRadius: 6,
        background: theme.isDark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.03)',
      }}>
        <input
          type="text" value={value}
          onChange={e => onChange(Number(e.target.value) || 0)}
          style={{
            width: '3.2ch', minWidth: 0, background: 'transparent', border: 'none',
            fontFamily: theme.monoFamily, fontSize: 13, fontWeight: 600,
            color: theme.text, outline: 'none', textAlign: 'left',
          }}
        />
        {suffix && <span style={{ fontFamily: theme.uiFamily, fontSize: 10, color: theme.muted }}>{suffix}</span>}
      </div>
    </div>
  );
}

// ─── Feedback Modal — structured pain/RPE flow ─────────────────────────
function FeedbackModal({ theme, cardStyle, context, onClose, onSave }) {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    type: null,        // pain | rpe | failed | restriction | note
    location: '',
    severity: 5,
    painType: null,    // sharp | dull | burning | tightness
    relatedToCondition: null, // 'L4-L5 disc bulge' | 'Knee meniscus' | null
    rpe: 7,
    failedReason: null,
    note: '',
  });

  if (!context) return null;
  const setF = (patch) => setData({ ...data, ...patch });

  const types = [
    { id: 'pain',         label: 'Pain',              icon: 'flag',    danger: true },
    { id: 'rpe',          label: 'RPE / Effort',      icon: 'energy' },
    { id: 'failed',       label: 'Failed exercise',   icon: 'close' },
    { id: 'restriction',  label: 'Temp restriction',  icon: 'bell' },
    { id: 'note',         label: 'General note',      icon: 'notes' },
  ];

  const painTypes = ['Sharp', 'Dull', 'Burning', 'Tightness', 'Throbbing'];
  const failedReasons = ['Compensation', 'Out of time', 'Fatigue', 'Form breakdown', 'Equipment', 'Preference'];

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'flex-end',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', background: theme.bg,
        borderRadius: '24px 24px 0 0',
        padding: '12px 18px 28px', maxHeight: '85%', overflow: 'auto',
        boxShadow: '0 -10px 40px rgba(0,0,0,0.3)',
      }}>
        {/* drag handle */}
        <div style={{
          width: 40, height: 4, borderRadius: 4,
          background: theme.isDark ? 'rgba(255,255,255,0.2)' : 'rgba(0,0,0,0.18)',
          margin: '4px auto 14px',
        }}/>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 4 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: theme.uiFamily, fontSize: 11, fontWeight: 600, color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              Feedback
            </div>
            <div style={{ fontFamily: theme.displayFamily, fontSize: 22, fontWeight: 600, color: theme.text, marginTop: 2 }}>
              {context.exerciseName}{context.setIndex !== undefined ? ` · Set ${context.setIndex + 1}` : ''}
            </div>
          </div>
          <button onClick={onClose} style={{
            width: 32, height: 32, borderRadius: 9999, background: 'transparent',
            border: `1px solid ${theme.border}`, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="close" size={14} color={theme.text}/>
          </button>
        </div>

        {step === 0 && (
          <>
            <div style={{ fontFamily: theme.uiFamily, fontSize: 13, color: theme.muted, margin: '14px 0 10px' }}>
              What kind of feedback?
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {types.map(t => (
                <Card key={t.id} theme={theme} cardStyle={cardStyle} padding={14}
                  onClick={() => { setF({ type: t.id }); setStep(1); }}
                  style={{ display: 'flex', alignItems: 'center', gap: 12 }}
                >
                  <div style={{
                    width: 32, height: 32, borderRadius: 9999,
                    background: t.danger ? (theme.isDark ? 'rgba(255,77,77,0.12)' : 'rgba(199,39,39,0.08)') : (theme.isDark ? 'rgba(232,131,11,0.12)' : 'rgba(232,131,11,0.08)'),
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <Icon name={t.icon} size={16} color={t.danger ? theme.danger : theme.primary}/>
                  </div>
                  <div style={{ flex: 1, fontFamily: theme.uiFamily, fontSize: 14, fontWeight: 500, color: theme.text }}>
                    {t.label}
                  </div>
                  <Icon name="chevron" size={16} color={theme.muted}/>
                </Card>
              ))}
            </div>
          </>
        )}

        {step === 1 && data.type === 'pain' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 14 }}>
            <Field theme={theme} label="Where?">
              <input value={data.location} onChange={e => setF({ location: e.target.value })}
                placeholder="e.g. outer right knee" style={inputStyle(theme)}
              />
            </Field>
            <Field theme={theme} label={`How bad? (${data.severity}/10)`}>
              <input type="range" min="1" max="10" value={data.severity}
                onChange={e => setF({ severity: Number(e.target.value) })}
                style={{ width: '100%', accentColor: theme.danger }}
              />
            </Field>
            <Field theme={theme} label="Type">
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {painTypes.map(p => (
                  <Chip key={p} theme={theme} active={data.painType === p}
                    onClick={() => setF({ painType: p })}>{p}</Chip>
                ))}
              </div>
            </Field>
            <Field theme={theme} label="Related to existing condition?">
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {[...HEALTH_HISTORY.conditions.map(c => c.label), 'Not related'].map(c => (
                  <Chip key={c} theme={theme} active={data.relatedToCondition === c}
                    onClick={() => setF({ relatedToCondition: c })} block>{c}</Chip>
                ))}
              </div>
            </Field>
            <Field theme={theme} label="Notes (optional)">
              <textarea value={data.note} onChange={e => setF({ note: e.target.value })}
                placeholder="Felt it on rep 8, sharp pinch when descending…"
                style={{ ...inputStyle(theme), minHeight: 60, resize: 'vertical' }}
              />
            </Field>
            <FeedbackFooter theme={theme} onBack={() => setStep(0)} onSave={() => onSave(data)}/>
          </div>
        )}

        {step === 1 && data.type === 'rpe' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 14 }}>
            <Field theme={theme} label={`Rate of perceived exertion (${data.rpe}/10)`}>
              <input type="range" min="1" max="10" value={data.rpe}
                onChange={e => setF({ rpe: Number(e.target.value) })}
                style={{ width: '100%', accentColor: theme.primary }}
              />
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4, fontFamily: theme.uiFamily, fontSize: 10, color: theme.muted }}>
                <span>Easy</span><span>Hard</span><span>Max</span>
              </div>
            </Field>
            <Field theme={theme} label="Notes">
              <textarea value={data.note} onChange={e => setF({ note: e.target.value })}
                placeholder="Form felt clean, could go heavier next session"
                style={{ ...inputStyle(theme), minHeight: 60, resize: 'vertical' }}
              />
            </Field>
            <FeedbackFooter theme={theme} onBack={() => setStep(0)} onSave={() => onSave(data)}/>
          </div>
        )}

        {step === 1 && data.type === 'failed' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 14 }}>
            <Field theme={theme} label="Reason">
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {failedReasons.map(r => (
                  <Chip key={r} theme={theme} active={data.failedReason === r}
                    onClick={() => setF({ failedReason: r })}>{r}</Chip>
                ))}
              </div>
            </Field>
            <Field theme={theme} label="Notes">
              <textarea value={data.note} onChange={e => setF({ note: e.target.value })}
                style={{ ...inputStyle(theme), minHeight: 60, resize: 'vertical' }}
              />
            </Field>
            <FeedbackFooter theme={theme} onBack={() => setStep(0)} onSave={() => onSave(data)}/>
          </div>
        )}

        {step === 1 && (data.type === 'restriction' || data.type === 'note') && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 14 }}>
            <Field theme={theme} label={data.type === 'restriction' ? 'Restriction details' : 'Note'}>
              <textarea value={data.note} onChange={e => setF({ note: e.target.value })}
                placeholder={data.type === 'restriction' ? 'Avoid loaded spinal flexion this week (back tightness)' : 'Anything worth remembering…'}
                style={{ ...inputStyle(theme), minHeight: 80, resize: 'vertical' }}
              />
            </Field>
            <FeedbackFooter theme={theme} onBack={() => setStep(0)} onSave={() => onSave(data)}/>
          </div>
        )}
      </div>
    </div>
  );
}

function Field({ theme, label, children }) {
  return (
    <div>
      <div style={{ fontFamily: theme.uiFamily, fontSize: 11, fontWeight: 600, color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>
        {label}
      </div>
      {children}
    </div>
  );
}

function inputStyle(theme) {
  return {
    width: '100%', padding: '10px 12px', boxSizing: 'border-box',
    background: theme.isDark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.03)',
    border: `1px solid ${theme.border}`, borderRadius: 10,
    fontFamily: theme.uiFamily, fontSize: 13, color: theme.text, outline: 'none',
  };
}

function Chip({ theme, active, onClick, block, children }) {
  return (
    <div onClick={onClick} style={{
      padding: '6px 12px', borderRadius: 9999, cursor: 'pointer',
      background: active ? theme.primary : (theme.isDark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.03)'),
      color: active ? theme.primaryInk : theme.text,
      border: `1px solid ${active ? theme.primary : theme.border}`,
      fontFamily: theme.uiFamily, fontSize: 12, fontWeight: 500,
      width: block ? '100%' : 'auto',
      textAlign: block ? 'left' : 'center',
      transition: 'all 0.15s',
    }}>{children}</div>
  );
}

function FeedbackFooter({ theme, onBack, onSave }) {
  return (
    <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
      <button onClick={onBack} style={{
        flex: 1, padding: '12px', borderRadius: 12,
        background: 'transparent', border: `1px solid ${theme.border}`,
        fontFamily: theme.uiFamily, fontSize: 13, fontWeight: 600, color: theme.text,
        cursor: 'pointer',
      }}>Back</button>
      <button onClick={onSave} style={{
        flex: 2, padding: '12px', borderRadius: 12,
        background: theme.primary, color: theme.primaryInk, border: 'none',
        fontFamily: theme.uiFamily, fontSize: 13, fontWeight: 600,
        cursor: 'pointer',
      }}>Save feedback</button>
    </div>
  );
}

// ─── Workout History ─────────────────────────────────────────────────────
function WorkoutHistoryScreen({ theme, cardStyle, onBack, accent }) {
  return (
    <>
      <TopBar theme={theme} title="Workout History" onBack={onBack} accent={accent} sectionIcon="history"/>
      <div style={{ padding: '0 18px 100px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {/* summary strip */}
        <Card theme={theme} cardStyle={cardStyle} padding={14}>
          <div style={{ display: 'flex', gap: 12 }}>
            <Stat theme={theme} label="6-week" value="24 sessions"/>
            <Stat theme={theme} label="Avg duration" value="49 min"/>
            <Stat theme={theme} label="Completion" value="95%"/>
          </div>
        </Card>

        {WORKOUT_HISTORY.map((w, i) => (
          <Card key={i} theme={theme} cardStyle={cardStyle} padding={14}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: theme.monoFamily, fontSize: 10, color: theme.muted, fontWeight: 600 }}>
                  {w.date}
                </div>
                <div style={{ fontFamily: theme.uiFamily, fontSize: 14, fontWeight: 600, color: theme.text, marginTop: 2 }}>
                  {w.name}
                </div>
                <div style={{ fontFamily: theme.uiFamily, fontSize: 11, color: theme.muted, marginTop: 3 }}>
                  {w.duration} · {w.completion}% complete
                </div>
                <div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
                  <MiniMetric theme={theme} label="Mood" value={w.mood} max={5}/>
                  <MiniMetric theme={theme} label="Energy" value={w.energy} max={5}/>
                </div>
              </div>
              <div style={{
                width: 44, height: 44, borderRadius: 9999, position: 'relative',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: `conic-gradient(${accent || theme.primary} ${w.completion * 3.6}deg, ${theme.isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)'} 0)`,
              }}>
                <div style={{
                  position: 'absolute', inset: 4, borderRadius: 9999, background: theme.surface,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: theme.monoFamily, fontSize: 11, fontWeight: 700, color: theme.text,
                }}>{w.completion}</div>
              </div>
            </div>
          </Card>
        ))}
      </div>
    </>
  );
}

function MiniMetric({ theme, label, value, max }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
      <span style={{ fontFamily: theme.uiFamily, fontSize: 10, color: theme.muted, fontWeight: 500 }}>{label}</span>
      <div style={{ display: 'flex', gap: 2 }}>
        {Array.from({ length: max }).map((_, i) => (
          <div key={i} style={{
            width: 6, height: 6, borderRadius: 9999,
            background: i < value ? theme.primary : (theme.isDark ? 'rgba(255,255,255,0.12)' : 'rgba(0,0,0,0.1)'),
          }}/>
        ))}
      </div>
    </div>
  );
}

// ─── Health History ──────────────────────────────────────────────────────
function HealthHistoryScreen({ theme, cardStyle, onBack, accent }) {
  return (
    <>
      <TopBar theme={theme} title="Health History" onBack={onBack} accent={accent} sectionIcon="heart"/>
      <div style={{ padding: '0 18px 100px', display: 'flex', flexDirection: 'column', gap: 14 }}>

        <SectionLabel theme={theme} label="Conditions"/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {HEALTH_HISTORY.conditions.map((c, i) => (
            <Card key={i} theme={theme} cardStyle={cardStyle} padding={14}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                <div style={{
                  width: 8, height: 8, borderRadius: 9999, marginTop: 6, flexShrink: 0,
                  background: c.severity === 'monitor' ? theme.danger : theme.success,
                }}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: theme.uiFamily, fontSize: 14, fontWeight: 600, color: theme.text }}>
                    {c.label}
                  </div>
                  <div style={{
                    fontFamily: theme.uiFamily, fontSize: 11, fontWeight: 500,
                    color: c.severity === 'monitor' ? theme.danger : theme.success,
                    textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 2,
                  }}>{c.severity}</div>
                  <div style={{ fontFamily: theme.uiFamily, fontSize: 12, color: theme.muted, marginTop: 4, lineHeight: 1.4 }}>
                    {c.note}
                  </div>
                </div>
              </div>
            </Card>
          ))}
        </div>

        <SectionLabel theme={theme} label="Metrics"/>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {HEALTH_HISTORY.metrics.map((m, i) => (
            <Card key={i} theme={theme} cardStyle={cardStyle} padding={12}>
              <div style={{ fontFamily: theme.uiFamily, fontSize: 10, color: theme.muted, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                {m.label}
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 4 }}>
                <div style={{ fontFamily: theme.monoFamily, fontSize: 18, fontWeight: 700, color: theme.text }}>{m.value}</div>
                <Icon name={m.trend === 'up' ? 'arrowUp' : 'arrowDown'} size={12}
                  color={m.trend === 'up' ? theme.success : theme.success}/>
              </div>
            </Card>
          ))}
        </div>

        <SectionLabel theme={theme} label="Medications"/>
        <Card theme={theme} cardStyle={cardStyle} padding={14}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {HEALTH_HISTORY.meds.map(m => (
              <span key={m} style={{
                fontFamily: theme.uiFamily, fontSize: 12, fontWeight: 500,
                padding: '5px 10px', borderRadius: 9999,
                background: theme.isDark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)',
                color: theme.text,
              }}>{m}</span>
            ))}
          </div>
        </Card>
      </div>
    </>
  );
}

function SectionLabel({ theme, label }) {
  return (
    <div style={{ fontFamily: theme.uiFamily, fontSize: 11, fontWeight: 600, color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 4 }}>
      {label}
    </div>
  );
}

// ─── Goals & Programs ────────────────────────────────────────────────────
function GoalsScreen({ theme, cardStyle, onBack, accent }) {
  return (
    <>
      <TopBar theme={theme} title="Goals & Programs" onBack={onBack} accent={accent} sectionIcon="target"/>
      <div style={{ padding: '0 18px 100px', display: 'flex', flexDirection: 'column', gap: 14 }}>

        <SectionLabel theme={theme} label="Active goals"/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {GOALS.map(g => (
            <Card key={g.id} theme={theme} cardStyle={cardStyle} padding={14}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                <Icon name="target" size={16} color={theme.primary}/>
                <div style={{ flex: 1, fontFamily: theme.uiFamily, fontSize: 14, fontWeight: 600, color: theme.text }}>
                  {g.name}
                </div>
                <div style={{ fontFamily: theme.monoFamily, fontSize: 11, color: theme.muted }}>{g.target}</div>
              </div>
              <div style={{
                height: 6, borderRadius: 4,
                background: theme.isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)',
                overflow: 'hidden',
              }}>
                <div style={{ width: `${g.progress * 100}%`, height: '100%', background: accent || theme.primary }}/>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6 }}>
                <span style={{ fontFamily: theme.monoFamily, fontSize: 11, color: theme.muted }}>{g.unit}</span>
                <span style={{ fontFamily: theme.monoFamily, fontSize: 11, fontWeight: 600, color: accent || theme.primary }}>{Math.round(g.progress * 100)}%</span>
              </div>
            </Card>
          ))}
        </div>

        <SectionLabel theme={theme} label="Programs"/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {PROGRAMS.map(p => (
            <Card key={p.id} theme={theme} cardStyle={cardStyle} padding={14}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{
                  width: 6, height: 36, borderRadius: 4,
                  background: p.active ? (accent || theme.primary) : theme.muted,
                }}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: theme.uiFamily, fontSize: 14, fontWeight: 600, color: theme.text }}>{p.name}</div>
                  <div style={{ fontFamily: theme.uiFamily, fontSize: 11, color: theme.muted, marginTop: 2 }}>
                    {p.weeks} · {p.sessions}
                  </div>
                </div>
                {p.active && (
                  <span style={{
                    fontFamily: theme.uiFamily, fontSize: 10, fontWeight: 600,
                    padding: '3px 8px', borderRadius: 9999,
                    background: theme.isDark ? 'rgba(52,211,153,0.12)' : 'rgba(46,125,50,0.08)',
                    color: theme.success, textTransform: 'uppercase', letterSpacing: 0.5,
                  }}>Active</span>
                )}
              </div>
            </Card>
          ))}
        </div>
      </div>
    </>
  );
}

// ─── Assessments ─────────────────────────────────────────────────────────
function AssessmentsScreen({ theme, cardStyle, onBack, accent }) {
  return (
    <>
      <TopBar theme={theme} title="Assessments" onBack={onBack} accent={accent} sectionIcon="chart"
        right={<button style={{
          padding: '7px 14px', borderRadius: 9999, whiteSpace: 'nowrap',
          background: accent || theme.primary, color: '#fff',
          fontFamily: theme.uiFamily, fontSize: 11, fontWeight: 600,
          border: 'none', cursor: 'pointer',
        }}>+ New</button>}
      />
      <div style={{ padding: '0 18px 100px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {ASSESSMENTS.map((a, i) => (
          <Card key={i} theme={theme} cardStyle={cardStyle} padding={14}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: theme.monoFamily, fontSize: 10, color: theme.muted }}>{a.date}</div>
                <div style={{ fontFamily: theme.uiFamily, fontSize: 14, fontWeight: 600, color: theme.text, marginTop: 2 }}>{a.name}</div>
              </div>
              <div style={{ textAlign: 'left', minWidth: 92, flexShrink: 0 }}>
                <div style={{ fontFamily: theme.monoFamily, fontSize: 13, fontWeight: 600, color: a.flag ? theme.danger : theme.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {a.score}
                </div>
                {a.flag && (
                  <div style={{ fontFamily: theme.uiFamily, fontSize: 9, fontWeight: 600, color: theme.danger, textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 2 }}>
                    Flagged
                  </div>
                )}
              </div>
              <Icon name="chevron" size={14} color={theme.muted}/>
            </div>
          </Card>
        ))}
      </div>
    </>
  );
}

// ─── Side menu ───────────────────────────────────────────────────────────
function SideMenu({ theme, open, onClose, onNav }) {
  if (!open) return null;
  const items = [
    { id: 'home',     label: 'Clients',         icon: 'user' },
    { id: 'calendar', label: 'Schedule',        icon: 'calendar' },
    { id: 'pay',      label: 'Payments',        icon: 'receipt' },
    { id: 'add',      label: 'Generate workout',icon: 'plus' },
    { id: 'history',  label: 'Recent sessions', icon: 'history' },
    { id: 'settings', label: 'Settings',        icon: 'gear' },
  ];
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 90,
      background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        position: 'absolute', top: 0, left: 0, bottom: 0, width: '78%',
        background: theme.bg, padding: '70px 16px 24px',
        boxShadow: '4px 0 32px rgba(0,0,0,0.3)',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
          <div style={{
            width: 48, height: 48, borderRadius: 9999, background: theme.primary, color: theme.primaryInk,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: theme.uiFamily, fontWeight: 700, fontSize: 16,
          }}>MD</div>
          <div>
            <div style={{ fontFamily: theme.displayFamily, fontSize: 18, fontWeight: 600, color: theme.text }}>Mike Davies</div>
            <div style={{ fontFamily: theme.uiFamily, fontSize: 11, color: theme.muted }}>Trainer · 12 active clients</div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {items.map(it => (
            <div key={it.id} onClick={() => { onNav(it.id); onClose(); }} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '12px 10px', borderRadius: 10, cursor: 'pointer',
            }}>
              <Icon name={it.icon} size={18} color={theme.text}/>
              <div style={{ fontFamily: theme.uiFamily, fontSize: 14, color: theme.text, fontWeight: 500 }}>
                {it.label}
              </div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 'auto', fontFamily: theme.uiFamily, fontSize: 10, color: theme.muted, textAlign: 'left' }}>
          Trainer Mike · v0.1 prototype
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  ExerciseDetailScreen, FeedbackModal, WorkoutHistoryScreen,
  HealthHistoryScreen, GoalsScreen, AssessmentsScreen, SideMenu,
});
