// Additional screens: Splash, Settings, Notifications, Results, Add Goal, Add Habit,
// Quick Log (exercise sets tracker).

// ────────────────────────────── Splash ──────────────────────────────
// Full-bleed intro shown on first load. Tap anywhere to dismiss.
function SplashScreen({ coach, t, onTap }) {
  // Always darkened brand background, regardless of theme.
  return (
    <div onClick={onTap} style={{
      position: 'absolute', inset: 0, zIndex: 200,
      background: `radial-gradient(ellipse 70% 55% at 50% 50%, ${coach.primary}22 0%, #0a0806 65%)`,
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      cursor: 'pointer',
      fontFamily: 'inherit',
      animation: 'fadeIn .4s ease',
    }}>
      {/* stars */}
      {[
        { top: '18%', left: '72%', s: 6 },
        { top: '25%', right: '12%', s: 4 },
        { top: '62%', left: '28%', s: 5 },
        { top: '72%', right: '30%', s: 4 },
        { bottom: '22%', left: '40%', s: 5 },
      ].map((st, i) => (
        <div key={i} style={{
          position: 'absolute', ...st,
          width: st.s, height: st.s, background: coach.primary,
          clipPath: 'polygon(50% 0, 60% 40%, 100% 50%, 60% 60%, 50% 100%, 40% 60%, 0 50%, 40% 40%)',
          opacity: 0.8,
        }}/>
      ))}

      {/* Wordmark badge */}
      <div style={{
        width: 96, height: 96, borderRadius: 999,
        background: `radial-gradient(circle at 50% 50%, ${coach.primary}33, #1a1510)`,
        boxShadow: `0 0 60px ${coach.primary}66, inset 0 0 30px rgba(0,0,0,0.6)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        border: `1px solid ${coach.primary}55`,
        marginBottom: 20,
      }}>
        <div style={{
          fontWeight: 800, fontSize: 36, letterSpacing: -1,
          background: `linear-gradient(135deg, #fff, ${coach.primary})`,
          WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent',
          fontFamily: coach.font,
        }}>{coach.wordmark.slice(0, 2).toUpperCase()}</div>
      </div>
      <div style={{
        fontSize: 26, fontWeight: 700, color: coach.primary,
        fontFamily: coach.font, letterSpacing: -0.3,
      }}>{coach.wordmark}</div>

      <div style={{
        position: 'absolute', bottom: 48, left: 0, right: 0,
        textAlign: 'center', fontSize: 10, letterSpacing: 2,
        color: 'rgba(255,255,255,0.35)', fontWeight: 600,
      }}>TAP TO CONTINUE</div>
    </div>
  );
}

// ────────────────────────────── Notifications ──────────────────────────────
function NotificationsScreen({ t, coach, dark, nav }) {
  const [reply, setReply] = React.useState({ open: false, idx: -1 });

  const NOLAN = 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=160&q=70&auto=format&fit=crop';
  const MIKE  = 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=160&q=70&auto=format&fit=crop';

  const today = [
    { who: 'Nolan Mango', type: 'coach', text: 'Just added a new workout program', time: '10:40', avatar: NOLAN },
    { who: 'Nolan Mango', type: 'coach', text: 'Just added a new workout program', time: '10:40', avatar: NOLAN },
    { who: '@Mike Doe',   type: 'reply', text: 'Great food recipe you have log today.', time: '09:40', avatar: MIKE },
  ];
  const older = [
    { who: 'Nolan Mango', type: 'coach', text: 'Just added a new workout program', time: '10:40', avatar: NOLAN },
    { who: 'Nolan Mango', type: 'coach', text: 'Just added a new workout program', time: '10:40', avatar: NOLAN },
    { who: '@Mike Doe',   type: 'reply', text: 'Great food recipe you have log today.', time: '09:40', avatar: MIKE },
  ];

  const Row = ({ n, i, group }) => (
    <Card t={t} style={{ padding: 12, display: 'flex', gap: 10, alignItems: 'center' }}>
      <div style={{
        width: 42, height: 42, borderRadius: 999, flexShrink: 0, overflow: 'hidden',
      }}>
        <img src={n.avatar} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{n.who}</div>
          <div style={{ fontSize: 11, color: t.textMuted, flexShrink: 0 }}>{n.time}</div>
        </div>
        <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2, lineHeight: 1.4 }}>{n.text}</div>
        {n.type === 'reply' && (
          <button onClick={() => setReply({ open: true, idx: `${group}-${i}` })} style={{
            background: 'none', border: 'none', padding: 0, marginTop: 6,
            color: t.primary, fontSize: 12, fontWeight: 700, cursor: 'pointer',
            fontFamily: 'inherit',
          }}>Reply</button>
        )}
      </div>
    </Card>
  );

  return (
    <>
      <NavHeader title="Notification" t={t}/>
      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>Today</div>
        {today.map((n, i) => <Row key={`t${i}`} n={n} i={i} group="t"/>)}
        <div style={{ fontSize: 15, fontWeight: 700, color: t.text, marginTop: 6 }}>Older</div>
        {older.map((n, i) => <Row key={`o${i}`} n={n} i={i} group="o"/>)}
      </div>

      {reply.open && (
        <div onClick={() => setReply({ open: false, idx: -1 })} style={{
          position: 'absolute', inset: 0, zIndex: 150,
          background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'flex-end',
        }}>
          <div onClick={e => e.stopPropagation()} style={{
            background: t.surface, width: '100%', borderRadius: '24px 24px 0 0',
            padding: '12px 18px 20px', animation: 'slideUp .25s ease',
          }}>
            <div style={{ width: 36, height: 4, background: t.textDim, borderRadius: 2, margin: '4px auto 14px' }}/>
            <div style={{ fontSize: 15, fontWeight: 700, color: t.text, marginBottom: 10 }}>Reply to @Mike Doe</div>
            <textarea rows={3} placeholder="Write a reply..." style={{
              width: '100%', background: t.surface3, border: 'none', borderRadius: 12,
              padding: 12, fontSize: 14, color: t.text, fontFamily: 'inherit',
              resize: 'none', outline: 'none',
            }}/>
            <button onClick={() => setReply({ open: false, idx: -1 })} style={{
              background: t.primary, color: t.onPrimary, border: 'none',
              padding: '14px', borderRadius: 14, width: '100%', marginTop: 10,
              fontSize: 14, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
              letterSpacing: 0.5,
            }}>SEND REPLY</button>
          </div>
        </div>
      )}
    </>
  );
}

// ────────────────────────────── Settings ──────────────────────────────
function SettingsScreen({ t, coach, dark, setDark, nav }) {
  const [units, setUnits]       = React.useState('Metric');
  const [lang, setLang]         = React.useState('English');
  const [health, setHealth]     = React.useState(false);
  const [email, setEmail]       = React.useState(true);
  const [push, setPush]         = React.useState(true);
  const [reminder, setReminder] = React.useState(true);

  const selectStyle = {
    background: 'none', border: 'none', outline: 'none',
    fontSize: 14, fontWeight: 600, color: t.text, fontFamily: 'inherit',
    padding: '4px 2px', cursor: 'pointer',
  };

  const Row = ({ label, children }) => (
    <Card t={t} style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{ flex: 1, fontSize: 14, fontWeight: 600, color: t.text }}>{label}</div>
      {children}
    </Card>
  );

  return (
    <>
      <NavHeader title="Settings" t={t}/>
      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <Row label="Units">
          <select value={units} onChange={e => setUnits(e.target.value)} style={selectStyle}>
            <option>Metric</option><option>Imperial</option>
          </select>
        </Row>
        <Row label="Language">
          <select value={lang} onChange={e => setLang(e.target.value)} style={selectStyle}>
            <option>English</option><option>Español</option><option>Français</option><option>Deutsch</option>
          </select>
        </Row>
        <Row label="Theme">
          <select value={dark ? 'Dark' : 'Light'} onChange={e => setDark(e.target.value === 'Dark')} style={selectStyle}>
            <option>Light</option><option>Dark</option>
          </select>
        </Row>

        <SectionLabel t={t} label="Health Connection"/>
        <Card t={t} style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 40, height: 40, borderRadius: 999, background: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: `1px solid ${t.border}`,
          }}>
            <Icon.Apple size={22}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>Apple Health</div>
            <div style={{ fontSize: 11, color: t.textMuted, marginTop: 2 }}>Connect to sync health data</div>
          </div>
          <Switch on={health} setOn={setHealth} t={t}/>
        </Card>

        <SectionLabel t={t} label="Notification"/>
        <Row label="Email Notification"><Switch on={email} setOn={setEmail} t={t}/></Row>
        <Row label="Push Notification"><Switch on={push} setOn={setPush} t={t}/></Row>
        <Row label="Reminder Notification"><Switch on={reminder} setOn={setReminder} t={t}/></Row>

        <div style={{ height: 2 }}/>
        {['Privacy & Data', 'Help & Support', 'Terms & Conditions', 'Log Out'].map((label, i) => (
          <button key={label} style={{
            background: t.surface, border: 'none', cursor: 'pointer',
            padding: '14px 16px', borderRadius: 14,
            display: 'flex', alignItems: 'center', gap: 12,
            fontFamily: 'inherit', textAlign: 'left',
            boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
          }}>
            <div style={{ flex: 1, fontSize: 14, fontWeight: 600,
              color: label === 'Log Out' ? '#E5573D' : t.text }}>{label}</div>
            {label !== 'Log Out' && <Icon.ChevronRight color={t.textDim}/>}
          </button>
        ))}
      </div>
    </>
  );
}

function SectionLabel({ t, label }) {
  return (
    <div style={{
      fontSize: 12, fontWeight: 700, color: t.textMuted,
      marginTop: 10, marginBottom: -2, padding: '0 4px',
    }}>{label}</div>
  );
}

// ────────────────────────────── Results ──────────────────────────────
function ResultsScreen({ t, coach, dark, nav }) {
  // Tiny sparkline path builder
  const spark = (pts, color) => {
    const w = 100, h = 30;
    const max = Math.max(...pts), min = Math.min(...pts);
    const d = pts.map((v, i) => {
      const x = (i / (pts.length - 1)) * w;
      const y = h - ((v - min) / (max - min || 1)) * h;
      return `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`;
    }).join(' ');
    return (
      <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: '100%', height: 30, marginTop: 8 }}>
        <path d={d} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    );
  };

  const cards = [
    { icon: <Icon.Scale  size={18} color={t.primary}/>, label: 'Weight',       value: '74.2 kg',   delta: '-0.8', down: true,  points: [76, 75.6, 75.1, 74.8, 74.5, 74.3, 74.2], color: t.primary, bg: t.primarySoft },
    { icon: <Icon.Workouts size={16} color={t.primary}/>,label: 'Workouts',     value: '12,400 kg', delta: '+8',   down: false, points: [8, 9, 9.5, 10.5, 11, 11.8, 12.4],        color: '#4FBF7E', bg: t.primarySoft },
    { icon: <Icon.Nutrition size={18} color={t.primary}/>,label: 'Nutrition',   value: '2,150 cal', delta: '-50',  down: true,  points: [2300, 2280, 2200, 2180, 2250, 2140, 2150],color: t.primary, bg: t.primarySoft },
    { icon: <Icon.Shoe size={18} color={t.primary}/>, label: 'Activity',     value: '7,200 steps',delta: '+340', down: false, points: [5000, 5500, 6200, 6800, 6900, 7100, 7200],color: '#6AA7F2', bg: t.primarySoft },
    { icon: <Icon.Ruler size={18} color={t.primary}/>, label: 'Measurements',value: '5 tracked',  delta: '',     down: null,  points: [3, 3, 4, 4, 4, 5, 5],                    color: '#A076F9', bg: t.primarySoft },
    { icon: <Icon.Camera size={18} color={t.primary}/>, label: 'Photos',     value: '12 sets',    delta: '+2',   down: false, points: [6, 7, 8, 9, 10, 11, 12],                 color: t.primary, bg: t.primarySoft },
  ];

  return (
    <>
      <NavHeader title="Your Results" t={t}/>
      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {cards.map((c, i) => (
            <Card key={i} t={t} style={{ padding: 14, position: 'relative' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
                <div style={{
                  width: 34, height: 34, borderRadius: 10, background: c.bg,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{c.icon}</div>
                {c.delta && (
                  <div style={{
                    fontSize: 11, fontWeight: 700,
                    color: c.down ? '#E5573D' : '#34C759',
                    display: 'flex', alignItems: 'center', gap: 3,
                  }}>
                    <svg width="14" height="10" viewBox="0 0 14 10" fill="none">
                      <path d={c.down ? 'M1 2l4 4 3-2 5 4' : 'M1 8l4-4 3 2 5-4'}
                        stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                    {c.delta}
                  </div>
                )}
              </div>
              <div style={{ fontSize: 11, color: t.textMuted, marginTop: 12, fontWeight: 600 }}>{c.label}</div>
              <div style={{ fontSize: 18, fontWeight: 800, color: t.text, marginTop: 2, letterSpacing: -0.3 }}>{c.value}</div>
              {spark(c.points, c.color)}
            </Card>
          ))}
        </div>

        {/* Streak */}
        <Card t={t} style={{ padding: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10, background: t.primarySoft,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><Icon.FlameFilled size={18} color={t.primary}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, color: t.textMuted, fontWeight: 600 }}>Current Streak</div>
              <div style={{ fontSize: 17, fontWeight: 800, color: t.text, letterSpacing: -0.3 }}>
                14 Days <span style={{ fontSize: 14 }}>{coach.habitEmoji || '🔥'}</span>
              </div>
            </div>
            <Icon.ChevronRight color={t.textDim}/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 6 }}>
            {['M','T','W','T','F','S','S'].map((d, i) => {
              const done = i < 5;
              return (
                <div key={i} style={{
                  height: 28, borderRadius: 7,
                  background: done ? t.primarySoft : t.surface3,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 700,
                  color: done ? t.primary : t.textDim,
                }}>{done ? <Icon.Check size={12} color={t.primary}/> : d}</div>
              );
            })}
          </div>
        </Card>

        {/* Health score */}
        <Card t={t} style={{
          padding: 14,
          background: t.primarySoft,
          border: `1px solid ${t.primary}33`,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <ProgressRing value={72} t={t} size={54} stroke={6} color={t.success} label={
              <Icon.Heart size={16} color={t.primary} filled/>
            }/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, color: t.text, fontWeight: 600 }}>Health Score</div>
              <div style={{ fontSize: 18, fontWeight: 800, color: t.text, letterSpacing: -0.3 }}>
                72 <span style={{ fontSize: 11, color: t.textMuted, fontWeight: 600 }}>/ 100</span>
              </div>
            </div>
            <div style={{
              fontSize: 12, fontWeight: 700, color: '#34C759',
              display: 'flex', alignItems: 'center', gap: 3,
            }}>
              <svg width="14" height="10" viewBox="0 0 14 10" fill="none">
                <path d="M1 8l4-4 3 2 5-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              +4
            </div>
            <Icon.ChevronRight color={t.textDim}/>
          </div>
        </Card>
      </div>
    </>
  );
}

// ────────────────────────────── Add Goal ──────────────────────────────
function AddGoalScreen({ t, coach, dark, nav }) {
  const [goal, setGoal]   = React.useState('');
  const [date, setDate]   = React.useState('');
  const [unit, setUnit]   = React.useState('Mi');
  const [target, setTarget] = React.useState('2');
  const [note, setNote]   = React.useState('');

  return (
    <>
      <NavHeader title="" t={t}/>
      <div style={{ padding: '0 18px 24px' }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
          <div style={{
            width: 58, height: 58, borderRadius: 14, background: t.primarySoft,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon.Target size={28} color={t.primary}/></div>
        </div>

        <FormLabel t={t}>Select Goal</FormLabel>
        <FormSelect t={t} value={goal} onChange={setGoal} placeholder="Select"
          options={['Run 5K', 'Lose 10 lbs', 'Build muscle', 'Hit 10k steps', 'Drink 3L water']}/>

        <FormLabel t={t}>Select Date</FormLabel>
        <input type="date" value={date} onChange={e => setDate(e.target.value)} style={{
          width: '100%', background: t.surface, border: `1px solid ${t.border}`,
          borderRadius: 12, padding: '14px 16px', fontSize: 14,
          color: date ? t.text : t.textMuted, fontFamily: 'inherit', outline: 'none',
          colorScheme: dark ? 'dark' : 'light',
        }}/>

        <FormLabel t={t}>Target</FormLabel>
        <div style={{ display: 'flex', gap: 10 }}>
          <FormSelect t={t} value={unit} onChange={setUnit}
            options={['Mi','Km','Reps','Lbs','Kg']} style={{ width: 100 }}/>
          <input value={target} onChange={e => setTarget(e.target.value)} style={{
            flex: 1, background: t.surface, border: `1px solid ${t.border}`,
            borderRadius: 12, padding: '14px 16px', fontSize: 14,
            color: t.text, fontFamily: 'inherit', outline: 'none',
          }}/>
        </div>

        <FormLabel t={t}>Note</FormLabel>
        <textarea value={note} onChange={e => setNote(e.target.value)} placeholder="Type here..." rows={4} style={{
          width: '100%', background: t.surface, border: `1px solid ${t.border}`,
          borderRadius: 12, padding: 14, fontSize: 14,
          color: t.text, fontFamily: 'inherit', outline: 'none', resize: 'none',
        }}/>

        <div style={{ height: 40 }}/>
        <button onClick={() => nav.pop()} style={{
          width: '100%', background: `linear-gradient(180deg, ${t.primary}, ${t.primary}cc)`,
          color: t.onPrimary, border: 'none', borderRadius: 14,
          padding: 16, fontSize: 14, fontWeight: 800, letterSpacing: 1,
          cursor: 'pointer', fontFamily: 'inherit',
          boxShadow: `0 8px 24px ${t.primary}55`,
        }}>ADD GOAL</button>
      </div>
    </>
  );
}

// ────────────────────────────── Add Habit ──────────────────────────────
function AddHabitScreen({ t, coach, dark, nav }) {
  const [habit, setHabit] = React.useState('');
  const [when, setWhen]   = React.useState('');

  return (
    <>
      <NavHeader title="" t={t}/>
      <div style={{ padding: '0 18px 24px' }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
          <div style={{
            width: 58, height: 58, borderRadius: 14, background: t.primarySoft,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon.FlameFilled size={26} color={t.primary}/></div>
        </div>

        <FormLabel t={t}>Select Habit</FormLabel>
        <FormSelect t={t} value={habit} onChange={setHabit} placeholder="Select"
          options={['Drink 8 glasses of water', 'Meditate 10 min', 'Sleep 8 hours', 'No sugar', 'Stretch']}/>

        <FormLabel t={t}>When To Complete</FormLabel>
        <FormSelect t={t} value={when} onChange={setWhen} placeholder="Select"
          options={['Morning', 'Afternoon', 'Evening', 'Anytime']}/>

        <div style={{ height: 320 }}/>
        <button onClick={() => nav.pop()} style={{
          width: '100%', background: `linear-gradient(180deg, ${t.primary}, ${t.primary}cc)`,
          color: t.onPrimary, border: 'none', borderRadius: 14,
          padding: 16, fontSize: 14, fontWeight: 800, letterSpacing: 1,
          cursor: 'pointer', fontFamily: 'inherit',
          boxShadow: `0 8px 24px ${t.primary}55`,
        }}>ADD HABIT</button>
      </div>
    </>
  );
}

// ────────────────────────────── Form primitives ──────────────────────────────
function FormLabel({ t, children }) {
  return (
    <div style={{ fontSize: 13, color: t.textMuted, fontWeight: 500, margin: '18px 0 8px' }}>{children}</div>
  );
}
function FormSelect({ t, value, onChange, options, placeholder, style = {} }) {
  return (
    <div style={{ position: 'relative', ...style }}>
      <select value={value} onChange={e => onChange(e.target.value)} style={{
        width: '100%', background: t.surface, border: `1px solid ${t.border}`,
        borderRadius: 12, padding: '14px 40px 14px 16px', fontSize: 14,
        color: value ? t.text : t.textMuted, fontFamily: 'inherit',
        outline: 'none', appearance: 'none', WebkitAppearance: 'none',
        cursor: 'pointer',
      }}>
        {placeholder && <option value="">{placeholder}</option>}
        {options.map(o => <option key={o} value={o}>{o}</option>)}
      </select>
      <div style={{ position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }}>
        <Icon.ChevronDown color={t.textMuted}/>
      </div>
    </div>
  );
}

// ────────────────────────────── Quick Log (Exercise Sets) ──────────────────────────────
// The expanded exercise detail with set grid, notes, and supersets.
function QuickLogScreen({ t, coach, dark, nav, exercise }) {
  const ex = exercise || { name: 'Barbell Bench Press', img: 'bench press' };

  const [sets, setSets] = React.useState([
    { reps: 6, weight: 185, rest: '2:00', done: false },
    { reps: 6, weight: 185, rest: '2:00', done: false },
    { reps: 6, weight: 185, rest: '2:00', done: false },
    { reps: 6, weight: 185, rest: '2:00', done: false },
  ]);
  const [note, setNote] = React.useState('');

  const update = (i, key, value) => setSets(s => s.map((x, j) => j === i ? { ...x, [key]: value } : x));
  const remove = (i) => setSets(s => s.filter((_, j) => j !== i));
  const addSet = () => setSets(s => [...s, { reps: 6, weight: 185, rest: '2:00', done: false }]);
  const markAll = () => setSets(s => s.map(x => ({ ...x, done: true })));

  const superset1 = [
    { name: 'Overhead Press',         img: 'overhead press' },
    { name: 'Incline Dumbbell Press', img: 'incline press' },
  ];
  const superset2 = [
    { name: 'Lateral Raises', img: 'lateral raises' },
    { name: 'Face Pulls',     img: 'face pulls' },
    { name: 'Tricep Pushdown',img: 'tricep' },
  ];

  return (
    <>
      <NavHeader title="" t={t}/>

      <div style={{ padding: '0 18px 90px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {/* Main exercise card */}
        <Card t={t} style={{ padding: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <div style={{ width: 44, height: 44, borderRadius: 10, overflow: 'hidden', flexShrink: 0 }}>
              <ImgPlaceholder label="bench" height={44} t={t} dark={dark}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{ex.name}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3 }}>
                <StrengthChip t={t}/>
                <span style={{ fontSize: 11, color: t.textMuted }}>0/{sets.length} sets</span>
              </div>
            </div>
            <Icon.ChevronUp color={t.textMuted}/>
          </div>

          {/* PR + History pills */}
          <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
            <div style={{
              background: t.primarySoft, color: t.primary,
              padding: '6px 10px', borderRadius: 999,
              fontSize: 11, fontWeight: 700,
              display: 'flex', alignItems: 'center', gap: 5,
            }}>
              <Icon.Trophy size={12} color={t.primary}/>
              PR: 225 lbs × 3
            </div>
            <div style={{
              background: t.surface3, color: t.textMuted,
              padding: '6px 10px', borderRadius: 999,
              fontSize: 11, fontWeight: 600,
              display: 'flex', alignItems: 'center', gap: 5,
            }}>
              <Icon.Clock size={12} color={t.textMuted}/>
              History
            </div>
          </div>

          <div style={{ fontSize: 11, color: t.textMuted, marginBottom: 10 }}>
            Target: 4×6-8 · Weight: 185 lbs · Rest: 2:00
          </div>

          {/* Set grid */}
          <div style={{
            display: 'grid', gridTemplateColumns: '28px 1fr 1fr 54px 30px 20px',
            gap: 6, alignItems: 'center',
            fontSize: 9, fontWeight: 700, color: t.textMuted,
            letterSpacing: 0.5, textTransform: 'uppercase',
            marginBottom: 6, padding: '0 4px',
          }}>
            <div>SET</div>
            <div style={{ textAlign: 'center' }}>REPS</div>
            <div style={{ textAlign: 'center' }}>WEIGHT</div>
            <div style={{ textAlign: 'center' }}>REST</div>
            <div/>
            <div/>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {sets.map((s, i) => (
              <div key={i} style={{
                display: 'grid', gridTemplateColumns: '28px 1fr 1fr 54px 30px 20px',
                gap: 6, alignItems: 'center',
              }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: t.text, paddingLeft: 4 }}>{i + 1}</div>
                <NumInput t={t} value={s.reps}   onChange={v => update(i, 'reps', v)}/>
                <NumInput t={t} value={s.weight} onChange={v => update(i, 'weight', v)} suffix="lbs"/>
                <div style={{
                  fontSize: 12, color: t.textMuted, textAlign: 'center', fontVariantNumeric: 'tabular-nums',
                }}>{s.rest}</div>
                <button onClick={() => update(i, 'done', !s.done)} style={{
                  width: 24, height: 24, borderRadius: 7, cursor: 'pointer',
                  border: `1.5px solid ${s.done ? t.primary : t.border}`,
                  background: s.done ? t.primary : 'transparent',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  padding: 0,
                }}>
                  {s.done && <Icon.Check size={12} color={t.onPrimary}/>}
                </button>
                <button onClick={() => remove(i)} style={{
                  background: 'none', border: 'none', cursor: 'pointer', padding: 0, color: t.textDim,
                }}><Icon.Close size={14} color={t.textDim}/></button>
              </div>
            ))}
          </div>

          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            marginTop: 12, paddingTop: 2,
          }}>
            <div style={{ display: 'flex', gap: 14 }}>
              <button onClick={addSet} style={{
                background: 'none', border: 'none', cursor: 'pointer', padding: 0,
                color: t.primary, fontSize: 12, fontWeight: 700, fontFamily: 'inherit',
              }}>+ Add Set</button>
              <button style={{
                background: 'none', border: 'none', cursor: 'pointer', padding: 0,
                color: t.primary, fontSize: 12, fontWeight: 700, fontFamily: 'inherit',
              }}>+ Drop Set</button>
            </div>
            <button onClick={markAll} style={{
              background: 'none', border: 'none', cursor: 'pointer', padding: 0,
              color: t.primary, fontSize: 12, fontWeight: 700, fontFamily: 'inherit',
              display: 'flex', alignItems: 'center', gap: 4,
            }}>Mark all <Icon.Check size={12} color={t.primary}/></button>
          </div>

          <div style={{ height: 1, background: t.border, margin: '14px 0 10px' }}/>

          <div style={{ fontSize: 10, fontWeight: 700, color: t.textMuted, letterSpacing: 0.5, marginBottom: 6, display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon.Comment size={11} color={t.textMuted}/>
            NOTES
          </div>
          <textarea value={note} onChange={e => setNote(e.target.value)}
            placeholder="Add a note for this exercise..." rows={2} style={{
              width: '100%', background: t.surface2, border: `1px solid ${t.border}`,
              borderRadius: 10, padding: 10, fontSize: 13, color: t.text,
              fontFamily: 'inherit', outline: 'none', resize: 'none',
            }}/>
        </Card>

        {/* Superset blocks */}
        <SupersetBlockCollapsed t={t} dark={dark} count={2} exercises={superset1}/>
        <SupersetBlockCollapsed t={t} dark={dark} count={3} exercises={superset2}/>
      </div>
    </>
  );
}

function NumInput({ t, value, onChange, suffix }) {
  return (
    <div style={{
      background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 8,
      padding: '8px 8px', display: 'flex', alignItems: 'center', justifyContent: 'center',
      gap: 3,
    }}>
      <input value={value} onChange={e => onChange(e.target.value)} style={{
        width: 30, background: 'transparent', border: 'none', outline: 'none',
        fontSize: 13, fontWeight: 700, color: t.text, textAlign: 'center',
        fontFamily: 'inherit', padding: 0,
      }}/>
      {suffix && <span style={{ fontSize: 10, color: t.textMuted, fontWeight: 600 }}>{suffix}</span>}
    </div>
  );
}

function StrengthChip({ t }) {
  return (
    <div style={{
      background: '#4EC1D822', color: '#3EAFCF',
      padding: '3px 8px', borderRadius: 999,
      fontSize: 10, fontWeight: 700,
      display: 'inline-flex', alignItems: 'center', gap: 4,
    }}>
      <svg width="10" height="10" viewBox="0 0 24 24" fill="none">
        <path d="M12 2L14 7H19L15 10L16 15L12 12L8 15L9 10L5 7H10L12 2Z" fill="#3EAFCF"/>
      </svg>
      Strength <Icon.Info size={9} color="#3EAFCF"/>
    </div>
  );
}

function SupersetBlockCollapsed({ t, dark, exercises, count }) {
  return (
    <div style={{
      background: t.primarySoft, borderRadius: 16, overflow: 'hidden',
      border: `1px solid ${t.primary}22`,
    }}>
      <div style={{
        padding: '10px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        fontSize: 10, fontWeight: 700, color: t.primary, letterSpacing: 0.5,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          <Icon.Repeat size={11} color={t.primary}/> SUPERSET
        </div>
        <div>{count} exercises</div>
      </div>
      <div style={{ background: t.surface, padding: 10, display: 'flex', flexDirection: 'column', gap: 8, borderRadius: 14, margin: '0 4px 4px' }}>
        {exercises.map((ex, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: 8, background: t.surface, borderRadius: 12,
            border: `1px solid ${t.border}`,
          }}>
            <div style={{ width: 40, height: 40, borderRadius: 8, overflow: 'hidden', flexShrink: 0 }}>
              <ImgPlaceholder label={ex.img} height={40} t={t} dark={dark}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: t.text }}>{ex.name}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3 }}>
                <StrengthChip t={t}/>
                <span style={{ fontSize: 10, color: t.textMuted }}>0/3 sets</span>
              </div>
            </div>
            <Icon.ChevronDown color={t.textMuted}/>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, {
  SplashScreen, NotificationsScreen, SettingsScreen, ResultsScreen,
  AddGoalScreen, AddHabitScreen, QuickLogScreen,
});
