// Workout flow: Program Details → Session Details → Exercise Detail
// Plus the in-session states: Countdown → Active Workout → Finish dialog → Complete form

// --- shared badge/tag styles ---
function StrengthTag({ t, dark }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      background: t.fat + (dark ? '26' : '22'), color: t.fat,
      padding: '3px 9px', borderRadius: 999,
      fontSize: 11, fontWeight: 600,
    }}>
      <Icon.Dumbbell size={11} color={t.fat}/> Strength
    </div>
  );
}
function AmrapTag({ t, dark }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      background: t.primarySoft, color: t.primary,
      padding: '3px 9px', borderRadius: 999,
      fontSize: 11, fontWeight: 600,
    }}>
      <Icon.Flame size={11} color={t.primary}/> AMRAP
    </div>
  );
}

// ────────────────────────────── Program Details ──────────────────────────────
function ProgramDetailsScreen({ t, coach, dark, nav }) {
  const [phase, setPhase] = React.useState('Phase 1');

  const sessions = [
    { num: 1, title: 'Push Day — Strength', kind: 'strength', dur: '45 min', img: 'barbell press', status: null },
    { num: 2, title: 'Full Body Basics',     kind: 'strength', dur: '40 min', img: 'squat rack',    status: '1× done' },
    { num: 3, title: 'AMRAP Blast',          kind: 'amrap',    dur: '20 min', img: 'rowing',        status: '3× done' },
  ];

  return (
    <>
      <NavHeader title="Program Details" t={t}/>
      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 16 }}>

        {/* Hero */}
        <div style={{ position: 'relative', borderRadius: 18, overflow: 'hidden' }}>
          <ImgPlaceholder label="gym hero" height={200} t={t} dark={true}/>
          <div style={{
            position: 'absolute', top: 12, left: 12,
            background: 'rgba(0,0,0,0.55)', color: '#fff',
            padding: '4px 10px', borderRadius: 6, fontSize: 11, fontWeight: 600,
            backdropFilter: 'blur(8px)',
          }}>Intermediate</div>
          <div style={{
            position: 'absolute', bottom: 14, left: 16, right: 16,
            display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 10,
          }}>
            <div style={{ color: '#fff', fontSize: 22, fontWeight: 700, lineHeight: 1.15 }}>
              Upper Body Strength
            </div>
            <BrandPill t={t} icon={<Icon.Speaker size={12} color={t.onPrimary}/>}>Coach Note</BrandPill>
          </div>
        </div>

        {/* Description */}
        <Card t={t} style={{ padding: 14 }}>
          <div style={{ fontSize: 13, color: t.textMuted, lineHeight: 1.5 }}>
            A progressive upper body program designed to build strength and muscle. Focus on compound movements with accessory work to target weak points.
          </div>
        </Card>

        {/* Sessions */}
        <div style={{ fontSize: 17, fontWeight: 700, color: t.text }}>Sessions</div>
        <div style={{ display: 'flex', gap: 8 }}>
          {['Phase 1', 'Phase 2', 'Phase 3'].map(p => (
            <button key={p} onClick={() => setPhase(p)} style={{
              padding: '8px 16px', borderRadius: 999, border: 'none',
              background: phase === p ? t.primary : t.surface3,
              color: phase === p ? t.onPrimary : t.text,
              fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            }}>{p}</button>
          ))}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {sessions.map(s => (
            <button key={s.num} onClick={() => nav.push(p => <SessionDetailsScreen {...p} session={s}/>)} style={{
              background: t.surface, border: 'none', cursor: 'pointer', textAlign: 'left',
              borderRadius: 16, padding: 12, display: 'flex', alignItems: 'center', gap: 12,
              fontFamily: 'inherit', boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
            }}>
              <div style={{ position: 'relative' }}>
                <ImgPlaceholder label={s.img} height={60} t={t} dark={true}/>
                <div style={{
                  position: 'relative', width: 60, height: 60, borderRadius: 12, overflow: 'hidden',
                  marginTop: -60,
                  background: `repeating-linear-gradient(135deg, #333 0 6px, #222 6px 12px)`,
                }}>
                  {s.status && (
                    <div style={{
                      position: 'absolute', top: 4, left: 4, width: 18, height: 18, borderRadius: 999,
                      background: 'rgba(0,0,0,0.6)', color: '#fff',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}><Icon.Check size={10} color="#fff"/></div>
                  )}
                </div>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 11, color: t.textMuted, fontWeight: 600, marginBottom: 3, display:'flex', gap:6, alignItems:'center' }}>
                  Session {s.num}
                  {s.status && (
                    <span style={{
                      background: t.primarySoft, color: t.primary,
                      padding: '2px 7px', borderRadius: 999, fontSize: 10, fontWeight: 700,
                    }}>{s.status}</span>
                  )}
                </div>
                <div style={{ fontSize: 15, fontWeight: 700, color: t.text, marginBottom: 4 }}>{s.title}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  {s.kind === 'strength' ? <StrengthTag t={t} dark={dark}/> : <AmrapTag t={t} dark={dark}/>}
                  <div style={{ fontSize: 12, color: t.primary, fontWeight: 600 }}>{s.dur}</div>
                </div>
              </div>
              <Icon.ChevronRight color={t.textDim}/>
            </button>
          ))}
        </div>
      </div>
    </>
  );
}

// ────────────────────────────── Session Details ──────────────────────────────
function SessionDetailsScreen({ t, coach, dark, nav, session }) {
  const [openSection, setOpenSection] = React.useState('main');

  const mainLifts = [
    { name: 'Barbell Bench Press', sets: 4, reps: '6-8', weight: 185, img: 'bench press' },
  ];
  const superset1 = [
    { name: 'Overhead Press',         reps: '8-10', weight: 115, img: 'overhead press' },
    { name: 'Incline Dumbbell Press', reps: '10-12', weight: 60,  img: 'incline press' },
  ];
  const superset2 = [
    { name: 'Lateral Raises',  reps: '15', weight: 20, img: 'lateral raises' },
    { name: 'Face Pulls',      reps: '15', weight: 30, img: 'face pulls' },
  ];

  const openExercise = (ex) => nav.push(p => <ExerciseDetailScreen {...p} exercise={ex}/>);

  return (
    <>
      <NavHeader title="Session Details" t={t}/>
      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>

        {/* Hero */}
        <div style={{ position: 'relative', borderRadius: 18, overflow: 'hidden' }}>
          <ImgPlaceholder label="session hero" height={190} t={t} dark={true}/>
          <div style={{
            position: 'absolute', bottom: 14, left: 16, right: 16,
            display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 10,
          }}>
            <div>
              <div style={{ color: '#fff', fontSize: 20, fontWeight: 700, lineHeight: 1.15 }}>
                {session?.title || 'Push Day — Strength'}
              </div>
              <div style={{ color: 'rgba(255,255,255,0.9)', fontSize: 12, fontWeight: 500, marginTop: 4, display: 'flex', alignItems: 'center', gap: 4 }}>
                <Icon.Clock size={12} color="#fff"/> {session?.dur || '45 min'}
              </div>
            </div>
            <BrandPill t={t} icon={<Icon.Speaker size={12} color={t.onPrimary}/>}>Coach Note</BrandPill>
          </div>
        </div>

        <Card t={t} style={{ padding: 14 }}>
          <div style={{ fontSize: 13, color: t.textMuted, lineHeight: 1.5 }}>
            Heavy compound pushing movements followed by isolation work. Focus on controlled tempo and full range of motion.
          </div>
        </Card>

        {/* Main lifts expandable */}
        <ExpandableSection t={t}
          open={openSection === 'main'}
          onToggle={() => setOpenSection(openSection === 'main' ? null : 'main')}
          icon={<Icon.Dumbbell size={16} color={t.fat}/>}
          iconBg={t.fat + (dark ? '26' : '22')}
          title="Main Lifts"
          tag={<StrengthTag t={t} dark={dark}/>}
          subtitle={`${mainLifts.length + superset1.length + superset2.length} exercises`}
        >
          {mainLifts.map((ex, i) => (
            <ExerciseRow key={i} t={t} dark={dark} ex={ex} onClick={() => openExercise(ex)} sets={ex.sets}/>
          ))}

          <SupersetBlock t={t} dark={dark} exercises={superset1} sets="3 sets each" onExercise={openExercise}/>
          <SupersetBlock t={t} dark={dark} exercises={superset2} sets="3 sets each" onExercise={openExercise}/>
        </ExpandableSection>

        {/* Start button */}
        <button onClick={() => nav.push(p => <CountdownScreen {...p} session={session}/>)} style={{
          background: t.primary, color: t.onPrimary, border: 'none',
          padding: '16px', borderRadius: 999, cursor: 'pointer',
          fontSize: 15, fontWeight: 700, fontFamily: 'inherit',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          marginTop: 4,
        }}>
          <Icon.Play size={14} color={t.onPrimary}/> Start Workout
        </button>
      </div>
    </>
  );
}

function ExpandableSection({ t, open, onToggle, icon, iconBg, title, subtitle, tag, children }) {
  return (
    <div style={{
      background: t.surface, borderRadius: 16,
      boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
      overflow: 'hidden',
    }}>
      <button onClick={onToggle} style={{
        width: '100%', background: 'none', border: 'none', cursor: 'pointer',
        padding: 14, display: 'flex', alignItems: 'center', gap: 12,
        fontFamily: 'inherit', textAlign: 'left',
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: 10, background: iconBg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{icon}</div>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{title}</div>
            {tag}
          </div>
          <div style={{ fontSize: 12, color: t.textMuted }}>{subtitle}</div>
        </div>
        {open ? <Icon.ChevronUp color={t.textMuted}/> : <Icon.ChevronDown color={t.textMuted}/>}
      </button>
      {open && (
        <div style={{ padding: '0 12px 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {children}
        </div>
      )}
    </div>
  );
}

function ExerciseRow({ t, dark, ex, onClick, sets, compact = false }) {
  return (
    <button onClick={onClick} style={{
      background: 'none', border: 'none', cursor: 'pointer',
      padding: '8px 8px', display: 'flex', alignItems: 'center', gap: 10,
      fontFamily: 'inherit', textAlign: 'left', width: '100%',
    }}>
      <div style={{ width: 46, height: 46, borderRadius: 8, overflow: 'hidden', flexShrink: 0 }}>
        <ImgPlaceholder label={ex.img} height={46} t={t} dark={true}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: t.text, marginBottom: 2 }}>{ex.name}</div>
        <div style={{ fontSize: 11, color: t.textMuted, display: 'flex', gap: 6 }}>
          <span>{sets ? `${sets} sets × ${ex.reps}` : `${ex.reps}`}</span>
          <span style={{ color: t.primary, fontWeight: 700 }}>{ex.weight} lbs</span>
        </div>
      </div>
      <Icon.ChevronRight color={t.textDim} size={14}/>
    </button>
  );
}

function SupersetBlock({ t, dark, exercises, sets, onExercise }) {
  return (
    <div style={{
      background: t.primarySoft, borderRadius: 12, padding: 8,
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '0 6px 6px', fontSize: 10, fontWeight: 700, color: t.primary,
        textTransform: 'uppercase', letterSpacing: 0.5,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          <Icon.Repeat size={11} color={t.primary}/> SUPERSET
        </div>
        <div>{sets}</div>
      </div>
      {exercises.map((ex, i) => (
        <ExerciseRow key={i} t={t} dark={dark} ex={ex} onClick={() => onExercise(ex)}/>
      ))}
    </div>
  );
}

// ────────────────────────────── Exercise Detail ──────────────────────────────
function ExerciseDetailScreen({ t, coach, dark, nav, exercise }) {
  const ex = exercise || { name: 'Barbell Bench Press' };
  return (
    <>
      <NavHeader title="Exercise Detail" t={t}/>
      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>

        <ImgPlaceholder label="exercise video / image" height={200} t={t} dark={true}/>

        <div style={{ fontSize: 20, fontWeight: 700, color: t.text }}>{ex.name}</div>

        {/* Attribute chips — 3 column */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
          {[
            { k: 'Equipment', v: 'Barbell' },
            { k: 'Category',  v: 'Strength' },
            { k: 'Muscle',    v: 'Chest' },
          ].map(chip => (
            <div key={chip.k} style={{
              background: t.surface, borderRadius: 12, padding: '10px 12px',
              boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
            }}>
              <div style={{ fontSize: 11, color: t.textMuted, marginBottom: 2 }}>{chip.k}</div>
              <div style={{ fontSize: 13, fontWeight: 700, color: t.text }}>{chip.v}</div>
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon.Location size={14} color={t.textMuted}/>
          <div style={{
            background: t.surface3, padding: '3px 10px', borderRadius: 999,
            fontSize: 12, fontWeight: 600, color: t.text,
          }}>Gym</div>
        </div>

        {/* Prescribed */}
        <Card t={t} style={{ padding: 14 }}>
          <div style={{ fontSize: 11, color: t.textMuted, fontWeight: 700, marginBottom: 10, letterSpacing: 0.5 }}>PRESCRIBED</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
            {[
              { k: 'Sets', v: '4' }, { k: 'Reps', v: '6-8' },
              { k: 'Weight', v: '185 lbs' }, { k: 'Rest', v: '2:00' },
            ].map(c => (
              <div key={c.k}>
                <div style={{ fontSize: 11, color: t.textMuted, marginBottom: 2 }}>{c.k}</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{c.v}</div>
              </div>
            ))}
          </div>
        </Card>

        {/* Instructions */}
        <Card t={t} style={{ padding: 14 }}>
          <div style={{ fontSize: 11, color: t.textMuted, fontWeight: 700, marginBottom: 12, letterSpacing: 0.5 }}>INSTRUCTIONS</div>
          <ol style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              'Lie flat on a bench with feet planted firmly on the floor.',
              'Grip the bar slightly wider than shoulder-width apart.',
              'Unrack the bar and hold it directly above your chest with arms extended.',
              'Lower the bar with control to your mid-chest, keeping elbows at ~45°.',
              'Press the bar back up explosively, locking out at the top.',
              'Breathe in on the way down, exhale as you push through the sticking point.',
            ].map((txt, i) => (
              <li key={i} style={{ display: 'flex', gap: 10, fontSize: 13, color: t.text, lineHeight: 1.5 }}>
                <span style={{ color: t.primary, fontWeight: 700, flexShrink: 0 }}>{i + 1}.</span>
                <span>{txt}</span>
              </li>
            ))}
          </ol>
        </Card>
      </div>
    </>
  );
}

// ────────────────────────────── Countdown ──────────────────────────────
function CountdownScreen({ t, coach, dark, nav, session }) {
  const [count, setCount] = React.useState(3);

  React.useEffect(() => {
    if (count <= 0) {
      nav.pop();
      nav.push(p => <ActiveWorkoutScreen {...p} session={session}/>);
      return;
    }
    const id = setTimeout(() => setCount(c => c - 1), 1000);
    return () => clearTimeout(id);
  }, [count]);

  const c = 2 * Math.PI * 62;
  const [mounted, setMounted] = React.useState(false);
  React.useEffect(() => { setMounted(true); }, []);

  return (
    <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column', padding: '60px 0 0' }}>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ position: 'relative', width: 150, height: 150 }}>
          <svg width={150} height={150} style={{ transform: 'rotate(-90deg)' }}>
            <circle cx={75} cy={75} r={62} stroke={t.surface3} strokeWidth={8} fill="none"/>
            <circle cx={75} cy={75} r={62}
              stroke={t.primary} strokeWidth={8} fill="none"
              strokeDasharray={c} strokeLinecap="round"
              style={{
                strokeDashoffset: mounted ? c * (1 - count / 3) : c,
                transition: 'stroke-dashoffset 1s linear',
              }}/>
          </svg>
          <div style={{
            position: 'absolute', inset: 0, display: 'flex',
            alignItems: 'center', justifyContent: 'center',
            fontSize: 72, fontWeight: 700, color: t.primary,
            lineHeight: 1,
          }}>{count > 0 ? count : 'GO'}</div>
        </div>
      </div>
      <div style={{ padding: '0 18px 24px' }}>
        <Card t={t} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: 12 }}>
          <div style={{ width: 48, height: 48, borderRadius: 10, overflow: 'hidden' }}>
            <ImgPlaceholder label="bench" height={48} t={t} dark={true}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 10, color: t.textMuted, fontWeight: 700, letterSpacing: 0.5 }}>WHAT'S NEXT</div>
            <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>Barbell Bench Press</div>
            <div style={{ fontSize: 11, color: t.textMuted, marginTop: 2 }}>
              4 sets × 6-8 · <span style={{ color: t.primary, fontWeight: 700 }}>185 lbs</span>
            </div>
          </div>
          <div style={{
            background: t.surface3, padding: '3px 10px', borderRadius: 999,
            fontSize: 11, fontWeight: 600, color: t.text,
          }}>Barbell</div>
        </Card>
      </div>
    </div>
  );
}

// ────────────────────────────── Active Workout ──────────────────────────────
function ActiveWorkoutScreen({ t, coach, dark, nav, session }) {
  const [elapsed, setElapsed] = React.useState(16);
  const [sets, setSets] = React.useState([
    { reps: 6, weight: 185, done: false },
    { reps: 6, weight: '',  done: false },
    { reps: 6, weight: '',  done: false },
    { reps: 6, weight: '',  done: false },
  ]);
  const [showFinish, setShowFinish] = React.useState(false);

  React.useEffect(() => {
    const id = setInterval(() => setElapsed(e => e + 1), 1000);
    return () => clearInterval(id);
  }, []);

  const mm = String(Math.floor(elapsed / 60)).padStart(2, '0');
  const ss = String(elapsed % 60).padStart(2, '0');

  const updateSet = (i, k, v) => setSets(s => s.map((x, idx) => idx === i ? { ...x, [k]: v } : x));

  const finishWorkout = () => {
    setShowFinish(false);
    nav.reset();
    nav.push(p => <WorkoutCompleteScreen {...p} duration={`${mm}:${ss}`}/>);
  };

  return (
    <>
      {/* top bar: timer + close */}
      <div style={{
        position: 'relative', padding: '58px 18px 12px',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <button onClick={() => setShowFinish(true)} style={{
          background: 'none', border: 'none', width: 36, height: 36,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
        }}><Icon.Close size={18} color={t.text}/></button>
        <div style={{
          flex: 1, textAlign: 'center',
          fontFamily: 'ui-monospace, SFMono-Regular, monospace',
          fontSize: 16, fontWeight: 700, color: t.text,
        }}>{mm}:{ss}</div>
        <div style={{ width: 36 }}/>
      </div>
      <div style={{ height: 1, background: t.border, margin: '0 18px' }}/>

      <div style={{ padding: '12px 18px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div><StrengthTag t={t} dark={dark}/></div>

        {/* Exercise hero */}
        <div style={{ position: 'relative', borderRadius: 14, overflow: 'hidden' }}>
          <ImgPlaceholder label="bench press" height={130} t={t} dark={true}/>
          <div style={{
            position: 'absolute', top: 10, right: 10,
            width: 28, height: 28, borderRadius: 999,
            background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(8px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer',
          }}>
            <Icon.Info size={14} color="#fff"/>
          </div>
          <div style={{
            position: 'absolute', bottom: 10, left: 14, color: '#fff',
          }}>
            <div style={{ fontSize: 18, fontWeight: 700 }}>Barbell Bench Press</div>
            <div style={{ fontSize: 11, opacity: 0.85 }}>4 sets × 6-8 · 185 lbs</div>
          </div>
        </div>

        {/* Equipment tags */}
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {['Barbell', 'Dumbbell', 'Cable'].map(eq => (
            <div key={eq} style={{
              padding: '4px 10px', borderRadius: 999,
              background: t.surface3, color: t.text,
              fontSize: 11, fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', gap: 4,
            }}><Icon.Workouts size={10} color={t.textMuted}/> {eq}</div>
          ))}
        </div>

        {/* PR */}
        <div style={{
          background: t.primarySoft, color: t.primary,
          padding: '7px 12px', borderRadius: 999,
          fontSize: 12, fontWeight: 700, alignSelf: 'flex-start',
          display: 'inline-flex', alignItems: 'center', gap: 6,
        }}>
          <Icon.Trophy size={14} color={t.primary}/> PR: 225 lbs × 3
        </div>

        {/* Sets table */}
        <Card t={t} style={{ padding: '14px 14px' }}>
          <div style={{
            display: 'grid', gridTemplateColumns: '30px 40px 1fr 1fr 60px',
            gap: 8, fontSize: 10, fontWeight: 700, color: t.textMuted,
            letterSpacing: 0.5, paddingBottom: 8,
            textAlign: 'center',
          }}>
            <div/><div>SET</div><div>REPS</div><div>WEIGHT</div><div>REST</div>
          </div>
          {sets.map((s, i) => (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '30px 40px 1fr 1fr 60px',
              gap: 8, padding: '8px 0', alignItems: 'center',
            }}>
              <button onClick={() => updateSet(i, 'done', !s.done)} style={{
                width: 22, height: 22, borderRadius: 6,
                border: `2px solid ${s.done ? t.primary : t.textDim}`,
                background: s.done ? t.primary : 'transparent',
                cursor: 'pointer', padding: 0,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{s.done && <Icon.Check size={12} color={t.onPrimary}/>}</button>
              <div style={{ textAlign: 'center', fontSize: 14, color: t.text }}>{i + 1}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 4, justifyContent: 'center' }}>
                <button onClick={() => updateSet(i, 'reps', Math.max(0, s.reps - 1))} style={stepBtn(t)}>
                  <Icon.Minus size={10} color={t.text}/>
                </button>
                <div style={{ fontSize: 14, color: t.text, width: 18, textAlign: 'center' }}>{s.reps}</div>
                <button onClick={() => updateSet(i, 'reps', s.reps + 1)} style={stepBtn(t)}>
                  <Icon.Plus size={10} color={t.text}/>
                </button>
              </div>
              <input value={s.weight} onChange={e => updateSet(i, 'weight', e.target.value)}
                placeholder="—" style={{
                  background: t.surface3, border: 'none', borderRadius: 8,
                  padding: '6px 8px', fontSize: 13, color: t.text,
                  fontFamily: 'inherit', textAlign: 'center', width: '100%',
                }}/>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 4, justifyContent: 'center',
                fontSize: 12, color: t.text,
              }}>
                <span>2:00</span>
                <Icon.Close size={10} color={t.textMuted}/>
              </div>
            </div>
          ))}
          <div style={{ display: 'flex', gap: 14, marginTop: 8 }}>
            <button style={{
              background: 'none', border: 'none', color: t.primary,
              fontSize: 13, fontWeight: 700, cursor: 'pointer', padding: 0,
              fontFamily: 'inherit',
            }}>+ Add Set</button>
            <button style={{
              background: 'none', border: 'none', color: t.primary,
              fontSize: 13, fontWeight: 700, cursor: 'pointer', padding: 0,
              fontFamily: 'inherit',
            }}>+ Drop Set</button>
          </div>
        </Card>

        {/* What's next */}
        <Card t={t} style={{ padding: 10, display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 42, height: 42, borderRadius: 8, overflow: 'hidden' }}>
            <ImgPlaceholder label="ohp" height={42} t={t} dark={true}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 10, color: t.textMuted, fontWeight: 700, letterSpacing: 0.5 }}>WHAT'S NEXT</div>
            <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>Overhead Press</div>
            <div style={{ fontSize: 11, color: t.textMuted }}>3×8-10</div>
          </div>
        </Card>

        {/* Actions */}
        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          <button onClick={() => setShowFinish(true)} style={{
            flex: '0 0 auto', padding: '14px 20px', borderRadius: 999,
            background: 'transparent', border: `1.5px solid ${t.primary}`,
            color: t.primary, fontSize: 14, fontWeight: 700, cursor: 'pointer',
            fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <Icon.Flag size={12} color={t.primary}/> FINISH
          </button>
          <button style={{
            flex: 1, padding: '14px', borderRadius: 999,
            background: t.primary, border: 'none',
            color: t.onPrimary, fontSize: 14, fontWeight: 700, cursor: 'pointer',
            fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
          }}>
            <Icon.SkipForward size={14} color={t.onPrimary}/> NEXT EXERCISE
          </button>
        </div>
      </div>

      {/* Finish dialog */}
      {showFinish && (
        <FinishDialog t={t}
          onContinue={() => setShowFinish(false)}
          onEnd={finishWorkout}
          onPause={() => setShowFinish(false)}
        />
      )}
    </>
  );
}

function stepBtn(t) {
  return {
    width: 22, height: 22, borderRadius: 999,
    background: t.surface3, border: 'none', cursor: 'pointer',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    flexShrink: 0,
  };
}

function FinishDialog({ t, onContinue, onEnd, onPause }) {
  return (
    <div onClick={onContinue} style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '0 24px',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: t.surface, borderRadius: 22, padding: 24,
        width: '100%', maxWidth: 340,
        animation: 'fadeIn .2s ease',
      }}>
        <div style={{
          width: 44, height: 44, borderRadius: 999, background: t.primarySoft,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          margin: '0 auto 12px',
        }}>
          <Icon.Pause size={18} color={t.primary}/>
        </div>
        <div style={{ fontSize: 18, fontWeight: 700, color: t.text, textAlign: 'center', marginBottom: 8 }}>
          Workout In Progress
        </div>
        <div style={{ fontSize: 13, color: t.textMuted, textAlign: 'center', lineHeight: 1.45, marginBottom: 18 }}>
          You've completed 0 of 4 sets. Would you like to pause and come back later, or end this workout?
        </div>
        <button onClick={onPause} style={{
          width: '100%', background: t.primarySoft, color: t.primary, border: 'none',
          padding: 14, borderRadius: 12, fontSize: 14, fontWeight: 700, cursor: 'pointer',
          fontFamily: 'inherit', marginBottom: 8,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>
          <Icon.Pause size={13} color={t.primary}/> Pause Workout
        </button>
        <button onClick={onEnd} style={{
          width: '100%', background: t.primary, color: t.onPrimary, border: 'none',
          padding: 14, borderRadius: 12, fontSize: 14, fontWeight: 700, cursor: 'pointer',
          fontFamily: 'inherit', marginBottom: 6,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>
          <Icon.Flag size={13} color={t.onPrimary}/> End Workout
        </button>
        <button onClick={onContinue} style={{
          width: '100%', background: 'transparent', color: t.text, border: 'none',
          padding: 10, fontSize: 13, fontWeight: 600, cursor: 'pointer',
          fontFamily: 'inherit',
        }}>Continue Workout</button>
      </div>
    </div>
  );
}

// ────────────────────────────── Workout Complete ──────────────────────────────
function WorkoutCompleteScreen({ t, coach, dark, nav, duration = '39:00' }) {
  const [rpe, setRpe] = React.useState(null);
  const [feel, setFeel] = React.useState(null);
  const [notes, setNotes] = React.useState('');

  const feelings = [
    { k: 'exhausted', emoji: '😣', label: 'Exhausted' },
    { k: 'tired',     emoji: '😪', label: 'Tired' },
    { k: 'good',      emoji: '😊', label: 'Good' },
    { k: 'strong',    emoji: '💪', label: 'Strong' },
    { k: 'amazing',   emoji: '🔥', label: 'Amazing' },
  ];

  const canSubmit = rpe != null && feel != null;

  return (
    <div style={{ padding: '58px 18px 24px', display: 'flex', flexDirection: 'column', gap: 12 }}>
      {/* Coach callout */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, padding: '6px 0 4px' }}>
        <div style={{
          width: 66, height: 66, borderRadius: 999,
          background: `linear-gradient(135deg, ${t.primarySoft}, ${t.primary})`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: t.onPrimary, fontWeight: 700, fontSize: 22,
        }}>{coach.coach.split(' ').map(n => n[0]).join('').slice(0, 2)}</div>
        <div style={{ fontSize: 16, fontWeight: 700, color: t.text, marginTop: 4 }}>
          Coach {coach.coach.split(' ')[0]}
        </div>
        <div style={{ fontSize: 12, color: t.textMuted }}>wants to know how it went</div>
      </div>

      {/* Duration */}
      <Card t={t} style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
        <Icon.Clock size={16} color={t.text}/>
        <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>Duration</div>
        <div style={{ flex: 1, textAlign: 'right' }}>
          <span style={{ fontSize: 15, fontWeight: 700, color: t.primary }}>{duration}</span>
          <span style={{ fontSize: 11, color: t.textMuted, marginLeft: 6, textDecoration: 'underline' }}>edit</span>
        </div>
      </Card>

      {/* RPE */}
      <Card t={t} style={{ padding: 14 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: t.text, marginBottom: 4 }}>Rate your effort (RPE)</div>
        <div style={{ fontSize: 11, color: t.textMuted, marginBottom: 12 }}>1 = Very easy · 5 = Maximum effort</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8 }}>
          {[1,2,3,4,5].map(n => (
            <button key={n} onClick={() => setRpe(n)} style={{
              aspectRatio: '1', borderRadius: 10,
              background: rpe === n ? t.primary : t.surface3,
              color: rpe === n ? t.onPrimary : t.text,
              border: 'none', cursor: 'pointer',
              fontSize: 18, fontWeight: 700, fontFamily: 'inherit',
            }}>{n}</button>
          ))}
        </div>
      </Card>

      {/* Feeling */}
      <Card t={t} style={{ padding: 14 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: t.text, marginBottom: 12 }}>How are you feeling?</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 6 }}>
          {feelings.map(f => (
            <button key={f.k} onClick={() => setFeel(f.k)} style={{
              background: feel === f.k ? t.primarySoft : 'transparent',
              border: `1.5px solid ${feel === f.k ? t.primary : 'transparent'}`,
              borderRadius: 10, padding: '8px 4px', cursor: 'pointer',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              fontFamily: 'inherit',
            }}>
              <div style={{ fontSize: 22, lineHeight: 1 }}>{f.emoji}</div>
              <div style={{ fontSize: 10, color: t.textMuted, fontWeight: 600 }}>{f.label}</div>
            </button>
          ))}
        </div>
      </Card>

      {/* Notes */}
      <Card t={t} style={{ padding: 14 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: t.text, marginBottom: 10 }}>Anything else for your coach?</div>
        <textarea value={notes} onChange={e => setNotes(e.target.value)}
          placeholder="Optional notes about the session..."
          rows={3}
          style={{
            width: '100%', background: t.surface3, border: 'none', borderRadius: 10,
            padding: 10, fontSize: 13, color: t.text, resize: 'none',
            fontFamily: 'inherit', outline: 'none',
          }}/>
      </Card>

      {/* Submit */}
      <button disabled={!canSubmit} onClick={() => nav.reset()} style={{
        width: '100%', background: canSubmit ? t.primary : t.primarySoft,
        color: canSubmit ? t.onPrimary : t.primary, border: 'none',
        padding: 16, borderRadius: 14, fontSize: 14, fontWeight: 700,
        cursor: canSubmit ? 'pointer' : 'default',
        fontFamily: 'inherit', letterSpacing: 0.5, textTransform: 'uppercase',
        opacity: canSubmit ? 1 : 0.7,
        marginTop: 6,
      }}>Submit & Log Workout</button>
    </div>
  );
}

Object.assign(window, {
  ProgramDetailsScreen, SessionDetailsScreen, ExerciseDetailScreen,
  CountdownScreen, ActiveWorkoutScreen, WorkoutCompleteScreen,
  StrengthTag, AmrapTag, ExpandableSection, ExerciseRow, SupersetBlock,
});
