// screens1.jsx — Home (3 layouts) + Plan

function greeting() {
  const h = new Date().getHours();
  if (h < 12) return 'Good morning';
  if (h < 18) return 'Good afternoon';
  return 'Good evening';
}
function todayLabel() {
  return new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' }).toUpperCase();
}

function StreakPill({ value, glass }) {
  const c = useTheme();
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 12px 7px 10px',
      borderRadius: 999, flexShrink: 0, whiteSpace: 'nowrap', background: glass ? 'rgba(0,0,0,0.45)' : 'var(--surface-2)',
      border: glass ? '1px solid rgba(255,255,255,0.14)' : '1px solid var(--border)',
      backdropFilter: glass ? 'blur(8px)' : 'none', WebkitBackdropFilter: glass ? 'blur(8px)' : 'none' }}>
      <span style={{ color: c.accent, display: 'flex' }}><Icon name="flame" size={17} /></span>
      <span style={{ fontFamily: 'var(--font-display)', fontSize: 16, color: glass ? '#fff' : 'var(--text)' }}>{value}</span>
      <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700, letterSpacing: 0.5, whiteSpace: 'nowrap',
        color: glass ? 'rgba(255,255,255,0.7)' : 'var(--muted)', textTransform: 'uppercase' }}>day streak</span>
    </div>
  );
}

function StatTile({ icon, label, value, unit, spark, big }) {
  const c = useTheme();
  return (
    <Card pad={14} style={{ display: 'flex', flexDirection: 'column', gap: 10, minWidth: 0 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ color: 'var(--muted)', display: 'flex' }}><Icon name={icon} size={17} /></span>
        {spark && <MiniSpark data={spark} accent={c.accent} />}
      </div>
      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: big ? 32 : 26, color: 'var(--text)', lineHeight: 0.9 }}>{value}</span>
          {unit && <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 700, color: 'var(--muted)' }}>{unit}</span>}
        </div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, fontWeight: 600, letterSpacing: 0.4,
          textTransform: 'uppercase', color: 'var(--dim)', marginTop: 4 }}>{label}</div>
      </div>
    </Card>
  );
}

// Today plan summary card (used in layouts A & B)
function TodayPlanCard({ plan, pct, onStart, onOpen }) {
  const c = useTheme();
  const total = plan.exercises.reduce((s, e) => s + e.sets.length, 0);
  const done = plan.exercises.reduce((s, e) => s + e.sets.filter(x => x.done).length, 0);
  return (
    <Card pad={16} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <ProgressRing pct={pct} accent={c.accent} size={62} stroke={7} track={c.surface3}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 17, color: 'var(--text)' }}>{pct}<span style={{ fontSize: 10 }}>%</span></span>
        </ProgressRing>
        <div style={{ flex: 1, minWidth: 0 }} onClick={onOpen}>
          <Eyebrow style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{plan.subtitle}</Eyebrow>
          <Display size={26} style={{ margin: '4px 0 5px' }}>{plan.title}</Display>
          <div style={{ display: 'flex', gap: 14, color: 'var(--muted)', fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 600 }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="dumbbell" size={14} />{plan.exercises.length} lifts</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="check" size={14} />{done}/{total} sets</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="clock" size={14} />{plan.durationMin}m</span>
          </div>
        </div>
      </div>
      <AccentButton onClick={onStart} icon={<Icon name="bolt" size={18} />}>{done > 0 ? 'Continue Workout' : 'Start Workout'}</AccentButton>
    </Card>
  );
}

function HomeScreen({ layout, plan, pct, go, streak }) {
  const c = useTheme();
  const stats = PROFILE.stats;
  const cleared = c.cleared;
  const sStreak = cleared ? 0 : stats.streak;
  const sPrs = cleared ? 0 : stats.prs;
  const sWorkouts = cleared ? 0 : stats.workouts;
  const sBest = cleared ? 0 : stats.bestStreak;
  const sWeekVol = cleared ? 0 : 74000;
  const heat = cleared ? HEATMAP.map(() => 0) : HEATMAP;

  // ── Layout A: HERO ─────────────────────────────────────────
  if (layout === 'Hero') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <HeroSlot id="home-hero" height={310} placeholder="Drop a hero photo — shirtless / training shot">
          <div style={{ position: 'absolute', top: 14, left: 16, right: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', pointerEvents: 'auto' }}>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 700, letterSpacing: 1, color: 'rgba(255,255,255,0.85)', whiteSpace: 'nowrap' }}>{todayLabel()}</div>
            <StreakPill value={streak} glass />
          </div>
          <div style={{ position: 'absolute', left: 16, bottom: 16, right: 16 }}>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 600, color: 'rgba(255,255,255,0.8)', marginBottom: 4 }}>{greeting()}, {PROFILE.name.split(' ')[0]}.</div>
            <Display size={44} style={{ color: '#fff' }}>Time to<br/>get after it.</Display>
          </div>
        </HeroSlot>
        <TodayPlanCard plan={plan} pct={pct} onStart={() => go('log')} onOpen={() => go('plan')} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
          <StatTile icon="flame" label="Streak" value={sStreak} unit="d" />
          <StatTile icon="bolt" label="This wk" value={c.abbrWt(sWeekVol)} unit={c.wtLabel} />
          <StatTile icon="trophy" label="PRs" value={sPrs} />
        </div>
        <Card pad={16}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <Eyebrow>Last 12 weeks</Eyebrow>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 700, color: 'var(--accent)' }} onClick={() => go('progress')}>View progress →</span>
          </div>
          <Heatmap values={heat} accent={c.accent} empty={c.surface3} />
        </Card>
      </div>
    );
  }

  // ── Layout B: STATS-FIRST ──────────────────────────────────
  if (layout === 'Stats') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600, color: 'var(--muted)' }}>{greeting()},</div>
            <Display size={30}>{PROFILE.name.split(' ')[0]}</Display>
          </div>
          <StreakPill value={streak} />
        </div>
        <Card pad={20} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,
          background: `radial-gradient(120% 80% at 50% 0%, ${c.accent}1a, transparent 60%), var(--surface)` }}>
          <Eyebrow>{plan.subtitle}</Eyebrow>
          <ProgressRing pct={pct} accent={c.accent} size={148} stroke={13} track={c.surface3}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 46, color: 'var(--text)', lineHeight: 0.85 }}>{pct}<span style={{ fontSize: 18 }}>%</span></span>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', color: 'var(--muted)' }}>{plan.title}</span>
          </ProgressRing>
          <AccentButton onClick={() => go('log')} icon={<Icon name="bolt" size={18} />}>{pct > 0 ? 'Continue Workout' : 'Start Workout'}</AccentButton>
        </Card>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <StatTile icon="flame" label="Streak" value={sStreak} unit="days" />
          <StatTile icon="bolt" label="Volume / wk" value={c.abbrWt(sWeekVol)} unit={c.wtLabel} spark={VOLUME_SERIES.slice(-6).map(v => v.volume)} />
          <StatTile icon="trophy" label="Total PRs" value={sPrs} />
          <StatTile icon="dumbbell" label="Workouts" value={sWorkouts} />
        </div>
        <HeroSlot id="home-hero-b" height={150} placeholder="Drop a motivation photo">
          <div style={{ position: 'absolute', left: 16, bottom: 14 }}>
            <Eyebrow style={{ color: 'rgba(255,255,255,0.7)' }}>Today's focus</Eyebrow>
            <Display size={26} style={{ color: '#fff' }}>{plan.title}</Display>
          </div>
        </HeroSlot>
      </div>
    );
  }

  // ── Layout C: EDITORIAL / BOLD ─────────────────────────────
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 700, letterSpacing: 1, color: 'var(--muted)' }}>{todayLabel()}</div>
        <span style={{ color: 'var(--muted)' }}><Icon name="bell" size={20} /></span>
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10 }}>
        <span style={{ fontFamily: 'var(--font-display)', fontSize: 110, lineHeight: 0.78, color: 'var(--accent)' }}>{streak}</span>
        <div style={{ paddingBottom: 12 }}>
          <Display size={32} style={{ lineHeight: 0.9 }}>Day<br/>streak</Display>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 600, color: 'var(--muted)', marginTop: 6 }}>Best: {sBest} days · keep it alive 🔥</div>
        </div>
      </div>
      <div style={{ height: 1, background: 'var(--border)' }} />
      <div>
        <Eyebrow style={{ marginBottom: 10 }}>On the bar today</Eyebrow>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {plan.exercises.map((e, i) => {
            const ex = exById(e.id);
            const done = e.sets.every(s => s.done);
            return (
              <div key={e.id} onClick={() => go('log')} style={{ display: 'flex', alignItems: 'center', gap: 14,
                padding: '13px 0', borderBottom: '1px solid var(--border)', cursor: 'pointer' }}>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 20, color: 'var(--dim)', width: 26 }}>{String(i + 1).padStart(2, '0')}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 16, color: 'var(--text)' }}>{ex.name}</div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--muted)' }}>{e.sets.length} sets · {ex.muscle}</div>
                </div>
                <span style={{ color: done ? c.accent : 'var(--dim)' }}><Icon name={done ? 'check' : 'chevR'} size={done ? 20 : 18} /></span>
              </div>
            );
          })}
        </div>
      </div>
      <AccentButton onClick={() => go('log')} icon={<Icon name="bolt" size={18} />}>{pct > 0 ? 'Continue Workout' : 'Start Workout'}</AccentButton>
    </div>
  );
}

// ── PLAN SCREEN ──────────────────────────────────────────────
function PlanScreen({ plan, pct, toggleSet, go }) {
  const c = useTheme();
  const [open, setOpen] = React.useState(plan.exercises[0]?.id);
  const todayIdx = new Date().getDay() === 0 ? 6 : new Date().getDay() - 1;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <ScreenHeader eyebrow={todayLabel()} title="Today's Plan"
        right={<ProgressRing pct={pct} accent={c.accent} size={48} stroke={6} track={c.surface3}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 14, color: 'var(--text)' }}>{pct}</span>
        </ProgressRing>} />

      <HeroSlot id="plan-hero" height={140} placeholder="Drop a workout photo">
        <div style={{ position: 'absolute', left: 16, bottom: 14, right: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
          <div>
            <Eyebrow style={{ color: 'rgba(255,255,255,0.7)' }}>{plan.subtitle}</Eyebrow>
            <Display size={30} style={{ color: '#fff' }}>{plan.title}</Display>
          </div>
          <div style={{ display: 'flex', gap: 12, color: 'rgba(255,255,255,0.85)', fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 700 }}>
            <span>{plan.exercises.length} lifts</span><span>·</span><span>{plan.durationMin} min</span>
          </div>
        </div>
      </HeroSlot>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {plan.exercises.map((e, ei) => {
          const ex = exById(e.id);
          const isOpen = open === e.id;
          const dn = e.sets.filter(s => s.done).length;
          return (
            <Card key={e.id} pad={0} style={{ overflow: 'hidden' }}>
              <div onClick={() => setOpen(isOpen ? null : e.id)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 15, cursor: 'pointer' }}>
                <div style={{ width: 38, height: 38, borderRadius: 'var(--radius-sm)', background: dn === e.sets.length ? c.accent : 'var(--surface-2)',
                  color: dn === e.sets.length ? c.accentInk : 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <Icon name={dn === e.sets.length ? 'check' : 'dumbbell'} size={19} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 16, color: 'var(--text)' }}>{ex.name}</div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--muted)' }}>{ex.muscle} · {ex.gear} · {dn}/{e.sets.length} sets</div>
                </div>
                <span style={{ color: 'var(--dim)', transform: isOpen ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }}><Icon name="chevD" size={18} /></span>
              </div>
              {isOpen && (
                <div style={{ padding: '0 15px 14px' }}>
                  <div style={{ display: 'flex', fontFamily: 'var(--font-body)', fontSize: 10.5, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', color: 'var(--dim)', padding: '6px 0', gap: 8 }}>
                    <span style={{ width: 28 }}>Set</span><span style={{ flex: 1 }}>Reps</span><span style={{ flex: 1 }}>Weight</span><span style={{ width: 44, textAlign: 'center' }}>Done</span>
                  </div>
                  {e.sets.map((s, si) => (
                    <div key={si} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 0', borderTop: '1px solid var(--border)' }}>
                      <span style={{ width: 28, fontFamily: 'var(--font-display)', fontSize: 17, color: 'var(--muted)' }}>{si + 1}</span>
                      <span style={{ flex: 1, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15, color: 'var(--text)' }}>{s.reps} <span style={{ fontSize: 11, color: 'var(--muted)' }}>reps</span></span>
                      <span style={{ flex: 1, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15, color: 'var(--text)' }}>{c.toDisp(s.weight)} <span style={{ fontSize: 11, color: 'var(--muted)' }}>{c.wtLabel}</span></span>
                      <div style={{ width: 44, display: 'flex', justifyContent: 'center' }}>
                        <button onClick={() => toggleSet(ei, si)} style={{ width: 30, height: 30, borderRadius: 9, cursor: 'pointer',
                          border: '1px solid ' + (s.done ? 'transparent' : 'var(--border)'),
                          background: s.done ? c.accent : 'transparent', color: c.accentInk, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          {s.done && <Icon name="check" size={16} />}
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </Card>
          );
        })}
      </div>

      <AccentButton onClick={() => go('log')} icon={<Icon name="bolt" size={18} />}>Log This Workout</AccentButton>

      <div>
        <Eyebrow style={{ marginBottom: 10 }}>This week</Eyebrow>
        <div style={{ display: 'flex', gap: 7 }}>
          {WEEK_SPLIT.map((d, i) => (
            <div key={i} style={{ flex: 1, textAlign: 'center', padding: '11px 2px', borderRadius: 'var(--radius-sm)',
              background: i === todayIdx ? c.accent : 'var(--surface)', border: '1px solid ' + (i === todayIdx ? 'transparent' : 'var(--border)') }}>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 10.5, fontWeight: 700, color: i === todayIdx ? c.accentInk : 'var(--muted)' }}>{d.day}</div>
              <div style={{ marginTop: 6, color: i === todayIdx ? c.accentInk : (d.rest ? 'var(--dim)' : 'var(--text)') }}>
                <Icon name={d.rest ? 'heart' : 'dumbbell'} size={16} style={{ margin: '0 auto' }} />
              </div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 9, fontWeight: 600, marginTop: 5, color: i === todayIdx ? c.accentInk : 'var(--dim)' }}>{d.focus}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen, PlanScreen, StatTile, StreakPill, TodayPlanCard });
