// Home and Workouts screens

function HomeScreen({ t, coach, dark, onMenu, onCommunity, onNotifications }) {
  const nav = useNav();
  const [habits, setHabits] = React.useState([
    { text: 'I drink a large glass of water', sub: 'After I brush my teeth at night', count: null,  checked: false },
    { text: 'I drink a large glass of water', sub: 'After I brush my teeth at night', count: 6,     checked: false },
    { text: 'I drink a large glass of water', sub: 'After I brush my teeth at night', count: null,  checked: false },
  ]);
  const toggleHabit = i => setHabits(h => h.map((x, idx) => idx === i ? { ...x, checked: !x.checked } : x));

  return (
    <>
      <ContentHeader t={t} coach={coach} onMenu={onMenu} onCommunity={onCommunity} onNotifications={onNotifications}/>
      <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 14 }}>

        {/* Complete profile card with progress ring */}
        <Card t={t} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px' }}>
          <ProgressRing value={70} t={t} size={50} stroke={5} label="70%"/>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>Complete your profile</div>
            <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>Answer remaining questions to get started</div>
          </div>
          <Icon.ChevronRight color={t.textDim}/>
        </Card>

        {/* Check-in due banner */}
        <button onClick={() => nav.push(p => <WorkoutCompleteScreen {...p}/>)} style={{
          background: t.primary, color: t.onPrimary, border: 'none', cursor: 'pointer',
          borderRadius: 18, padding: '14px 16px',
          display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left',
          fontFamily: 'inherit',
        }}>
          <div style={{
            width: 38, height: 38, borderRadius: 10,
            background: 'rgba(255,255,255,0.18)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon.Check size={18} color={t.onPrimary}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 700 }}>Check-In Due</div>
            <div style={{ fontSize: 12, opacity: 0.85 }}>August 18</div>
          </div>
          <div style={{
            background: 'rgba(255,255,255,0.18)', padding: '8px 12px',
            borderRadius: 999, fontSize: 12, fontWeight: 600,
            display: 'flex', alignItems: 'center', gap: 4,
          }}>View Check-in <Icon.ChevronRight size={12} color={t.onPrimary}/></div>
        </button>

        {/* Plans */}
        <SectionTitle t={t} title="Plans" action="View All"/>
        <div onClick={() => nav.push(p => <ProgramDetailsScreen {...p}/>)} style={{ cursor: 'pointer' }}>
          <ProgramCard t={t} dark={dark} title="Upper Body Workout" sessions={3}/>
        </div>

        {/* Habits */}
        <SectionTitle t={t} title="Habits" action="0/4" actionColor={t.primary}/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {habits.map((h, i) => (
            <Card key={i} t={t} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '14px 14px 14px 0', position: 'relative',
            }}>
              <div style={{
                width: 4, height: 36, background: t.primary, borderRadius: 4,
                marginRight: 12, marginLeft: 14,
              }}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{h.text}</div>
                <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>{h.sub}</div>
              </div>
              {h.count != null && (
                <div style={{ fontSize: 14, color: t.primary, fontWeight: 700 }}>{h.count}</div>
              )}
              {h.checked && (
                <div style={{
                  fontSize: 18, lineHeight: 1,
                  animation: 'fadeIn .25s ease',
                }} title="Habit streak">{coach.habitEmoji || '🔥'}</div>
              )}
              <button onClick={() => toggleHabit(i)} style={{
                width: 24, height: 24, borderRadius: 6,
                border: `2px solid ${h.checked ? t.primary : t.textDim}`,
                background: h.checked ? t.primary : 'transparent',
                cursor: 'pointer', padding: 0,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{h.checked && <Icon.Check size={12} color={t.onPrimary}/>}</button>
            </Card>
          ))}
        </div>
        <div style={{ height: 100 }}/>
      </div>
      <FAB t={t}/>
    </>
  );
}

function WorkoutsScreen({ t, coach, dark, onMenu, onCommunity, onNotifications }) {
  const [tab, setTab] = React.useState('Workout');
  const nav = useNav();
  return (
    <>
      <ContentHeader t={t} coach={coach} onMenu={onMenu} onCommunity={onCommunity} onNotifications={onNotifications}/>
      <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <PillToggle options={['Workout', 'History']} value={tab} onChange={setTab} t={t}/>

        {tab === 'Workout' && (
          <>
            <SectionTitle t={t} title="Programs"/>
            <div onClick={() => nav.push(p => <ProgramDetailsScreen {...p}/>)} style={{ cursor: 'pointer' }}>
              <ProgramCard t={t} dark={dark} title="Upper Body Workout" sessions={3} ago="2 days ago"/>
            </div>

            <SectionTitle t={t} title="Activities" action="Add Activity" actionColor={t.primary}/>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { name: 'Cycling',     kcal: 500 },
                { name: 'Field Sports', kcal: 100 },
              ].map((a, i) => (
                <Card key={i} t={t} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14 }}>
                  <div style={{
                    width: 38, height: 38, borderRadius: 999, background: t.primarySoft,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <Icon.Bolt color={t.primary}/>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{a.name}</div>
                    <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>{a.kcal} kcal</div>
                  </div>
                </Card>
              ))}
            </div>
          </>
        )}

        {tab === 'History' && <WorkoutHistoryView t={t} dark={dark}/>}

        <div style={{ height: 100 }}/>
      </div>
      <FAB t={t}/>
    </>
  );
}

// ────────────────── Workout History (calendar + list) ──────────────────
function WorkoutHistoryView({ t, dark }) {
  // 5-week grid for "Aug 1 - Aug 31". Previous/next month cells shown in muted,
  // past workout days show a small photo circle, today (15) is ringed,
  // remaining days this month show just a number.
  const WORKOUT_IMG = 'https://images.unsplash.com/photo-1534438327276-14e5300c3a48?w=160&q=70&auto=format&fit=crop';

  // Week rows — Mon..Sun. null = empty slot shown as prev-/next-month number.
  // isToday marks the ringed cell. done = has a photo circle.
  // Based on reference: grid spans Mon Jul 29 → Sun Sep 3.
  const rows = [
    // Mon=29, Tue=30 (prev month), Wed..Sun = Aug 1..4
    [ { num: 29, prev: true }, { num: 30, prev: true },
      { num: 1, done: true }, { num: 2, done: true }, { num: 3, done: true }, { num: 4 }, { num: 5, done: true } ],
    // Aug 6..12 — reference shows done on 6,7,8,9,10(blank shown as number?) — simplify: done most days
    [ { num: 6 }, { num: 7, done: true }, { num: 8, done: true }, { num: 9, done: true }, { num: 10 }, { num: 11, done: true }, { num: 12 } ],
    // Aug 13..19 — today = 15 (ringed)
    [ { num: 13, done: true }, { num: 14 }, { num: 15, isToday: true, done: true }, { num: 16 },
      { num: 17, done: true }, { num: 18, done: true }, { num: 19, done: true } ],
    // Aug 20..26
    [ { num: 20, done: true }, { num: 21 }, { num: 22, done: true }, { num: 23, done: true },
      { num: 24, done: true }, { num: 25, done: true }, { num: 26 } ],
    // Aug 27..31 + Sep 1,2,3 (next month)
    [ { num: 27 }, { num: 28, done: true }, { num: 29 }, { num: 30, done: true }, { num: 31, done: true },
      { num: 1, next: true }, { num: 2, next: true } ],
  ];

  const history = [
    { title: 'Upper body workout',   sessions: 3, ago: '3 hrs ago' },
    { title: 'Workout name Comes here', sessions: 3, ago: '1 days ago' },
  ];

  const dayLabels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

  return (
    <>
      {/* Month pill */}
      <button style={{
        alignSelf: 'flex-start', background: 'none', border: 'none',
        display: 'flex', alignItems: 'center', gap: 6, padding: 0, marginTop: 2,
        cursor: 'pointer', fontFamily: 'inherit',
      }}>
        <Icon.Calendar size={18} color={t.primary}/>
        <span style={{ fontSize: 15, fontWeight: 700, color: t.primary }}>Aug 1 - Aug 31</span>
        <Icon.ChevronRight size={14} color={t.primary}/>
      </button>

      {/* Day-of-week header */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2,
        marginTop: -4,
      }}>
        {dayLabels.map(d => (
          <div key={d} style={{
            fontSize: 12, color: t.textMuted, textAlign: 'center', fontWeight: 500,
          }}>{d}</div>
        ))}
      </div>

      {/* Calendar grid */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: -8 }}>
        {rows.map((row, ri) => (
          <div key={ri} style={{
            display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2,
          }}>
            {row.map((cell, ci) => (
              <div key={ci} style={{
                aspectRatio: '1 / 1', display: 'flex', alignItems: 'center',
                justifyContent: 'center', position: 'relative',
              }}>
                {cell.done ? (
                  <div style={{ position: 'relative', width: '78%', aspectRatio: '1/1' }}>
                    {cell.isToday && (
                      <div style={{
                        position: 'absolute', inset: -4, borderRadius: 999,
                        border: `2px solid ${t.primary}`,
                      }}/>
                    )}
                    <div style={{
                      width: '100%', height: '100%', borderRadius: 999,
                      overflow: 'hidden', position: 'relative',
                    }}>
                      <img src={WORKOUT_IMG} alt="" style={{
                        width: '100%', height: '100%', objectFit: 'cover',
                        filter: dark ? 'brightness(0.85)' : 'none',
                      }}/>
                    </div>
                  </div>
                ) : (
                  <div style={{
                    fontSize: 13, fontWeight: 500,
                    color: cell.prev || cell.next ? t.textDim : t.text,
                  }}>{cell.num}</div>
                )}
              </div>
            ))}
          </div>
        ))}
      </div>

      {/* Workout History list */}
      <div style={{ fontSize: 17, fontWeight: 700, color: t.text, marginTop: 6 }}>
        Workout History
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {history.map((h, i) => (
          <Card key={i} t={t} style={{
            padding: 12, display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, color: t.textMuted }}>
                {h.sessions} Session • Completed {h.ago}
              </div>
              <div style={{ fontSize: 15, fontWeight: 700, color: t.text, marginTop: 4 }}>
                {h.title}
              </div>
            </div>
            <div style={{
              width: 76, height: 56, borderRadius: 10, overflow: 'hidden', flexShrink: 0,
            }}>
              <img src={WORKOUT_IMG} alt="" style={{
                width: '100%', height: '100%', objectFit: 'cover',
              }}/>
            </div>
          </Card>
        ))}
      </div>
    </>
  );
}

// --- shared bits used by Home + Workouts ---
function SectionTitle({ t, title, action, actionColor }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
      <div style={{ fontSize: 17, fontWeight: 700, color: t.text }}>{title}</div>
      {action && (
        <div style={{ fontSize: 13, fontWeight: 600, color: actionColor || t.primary }}>{action}</div>
      )}
    </div>
  );
}

function ProgramCard({ t, dark, title, sessions, ago }) {
  return (
    <div style={{ position: 'relative', borderRadius: 18, overflow: 'hidden' }}>
      <ImgPlaceholder label="gym hero image" height={170} t={t} dark={true}/>
      <div style={{
        position: 'absolute', top: 12, left: 12,
        background: t.primary, color: t.onPrimary,
        padding: '5px 10px', borderRadius: 6,
        fontSize: 11, fontWeight: 600,
      }}>Assigned Program</div>
      <div style={{
        position: 'absolute', bottom: 12, left: 14, right: 14,
        color: '#fff',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, opacity: 0.9 }}>
          <div>No. of sessions: {sessions}</div>
          {ago && <div>{ago}</div>}
        </div>
        <div style={{ fontSize: 18, fontWeight: 700, marginTop: 4 }}>{title}</div>
      </div>
    </div>
  );
}

function ProgressRing({ value, t, size = 50, stroke = 5, label, color }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const dash = c * (value / 100);
  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} stroke={t.primarySoft} strokeWidth={stroke} fill="none"/>
        <circle cx={size/2} cy={size/2} r={r}
          stroke={color || t.primary} strokeWidth={stroke} fill="none"
          strokeDasharray={`${dash} ${c}`} strokeLinecap="round"/>
      </svg>
      {label && (
        <div style={{
          position: 'absolute', inset: 0, display: 'flex',
          alignItems: 'center', justifyContent: 'center',
          fontSize: size > 80 ? 22 : 12, fontWeight: 700, color: t.text,
        }}>{label}</div>
      )}
    </div>
  );
}

Object.assign(window, { HomeScreen, WorkoutsScreen, SectionTitle, ProgramCard, ProgressRing });
