// 하루결 — 운동 스케줄 화면

function ExerciseScreen({ navigate, exerciseId }) {
  if (exerciseId) {
    const ex = EXERCISES.find(e => e.id === exerciseId);
    if (!ex) return <ExerciseListScreen navigate={navigate} />;
    return <ExerciseDetailScreen navigate={navigate} exercise={ex} />;
  }
  return <ExerciseListScreen navigate={navigate} />;
}

function ExerciseListScreen({ navigate }) {
  const s = useStore();
  const today = todayISO();
  const week = buildWeekSchedule(s.profile.cycleStartDate, today);
  const todaySchedule = week.find(d => d.isToday);
  const cycleDay = todaySchedule ? todaySchedule.cycleDay : 1;
  const doneList = (s.exerciseLog && s.exerciseLog[today]) || [];

  const toneMap = {
    sage:  'var(--hg-sage)',
    clay:  'var(--hg-clay)',
    honey: 'var(--hg-honey)',
    mist:  'var(--hg-mist)',
  };
  const toneBg = {
    sage:  'var(--hg-sage-tint)',
    clay:  'var(--hg-clay-tint)',
    honey: 'var(--hg-honey-tint)',
    mist:  'var(--hg-mist-tint)',
  };

  return (
    <>
      <ScreenHeader
        title="오늘의 운동"
        sub={`회복 ${cycleDay}일차 · 무리하지 않는 강도`}
        back onBack={() => navigate('more')}
      />

      {/* 주간 캘린더 스트립 */}
      <div style={{ padding: '6px 22px 0' }}>
        <Panel style={{ padding: 14 }}>
          <Eyebrow>이번 주</Eyebrow>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4, marginTop: 8 }}>
            {week.map((d) => (
              <div key={d.iso} style={{
                padding: '8px 4px', borderRadius: 12, textAlign: 'center',
                background: d.isToday ? 'var(--hg-clay)' : d.isPast ? 'var(--hg-bg-deeper)' : 'transparent',
                color: d.isToday ? '#fff' : 'var(--hg-ink-2)',
                border: d.isToday ? 'none' : '1px solid var(--hg-line-soft)',
              }}>
                <div style={{ fontSize: 9, fontWeight: 700, opacity: d.isToday ? 0.8 : 0.6 }}>{d.label}</div>
                <div style={{ fontSize: 14, fontWeight: 700, marginTop: 2 }}>{d.dayNum}</div>
                <div style={{
                  fontSize: 9, marginTop: 4, fontWeight: 600,
                  color: d.isToday ? 'rgba(255,255,255,0.85)' : 'var(--hg-muted)',
                }}>{d.exercises.length}</div>
              </div>
            ))}
          </div>
        </Panel>
      </div>

      {/* 오늘 추천 운동 */}
      <div style={{ padding: '16px 22px 0' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)' }}>오늘 추천</div>
          <span style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600 }}>{doneList.length} / {todaySchedule.exercises.length} 완료</span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {todaySchedule.exercises.map((ex) => {
            const done = doneList.includes(ex.id);
            return (
              <div key={ex.id} style={{
                background: 'var(--hg-surface)',
                border: '1px solid var(--hg-line-soft)',
                borderRadius: 18, padding: 14,
                opacity: done ? 0.7 : 1,
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{
                  width: 48, height: 48, borderRadius: 14, flexShrink: 0,
                  background: toneBg[ex.tone], color: toneMap[ex.tone],
                  display: 'grid', placeItems: 'center',
                }}>
                  <ExerciseIcon name={ex.icon} color={toneMap[ex.tone]}/>
                </div>
                <button onClick={() => navigate(`exercise/${ex.id}`)} style={{
                  flex: 1, minWidth: 0, textAlign: 'left', background: 'none',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                    <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)' }}>{ex.name}</span>
                    <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 999, background: toneBg[ex.tone], color: toneMap[ex.tone] }}>
                      {intensityLabel(ex.intensity)}
                    </span>
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 500, lineHeight: 1.5 }}>
                    {ex.duration}분 · {ex.desc}
                  </div>
                </button>
                <button onClick={() => {
                  const log = { ...(s.exerciseLog || {}) };
                  const list = log[today] || [];
                  log[today] = done ? list.filter(id => id !== ex.id) : [...list, ex.id];
                  Store.save(K.exerciseLog, log);
                  if (!done) showToast('완료!');
                }} style={{ background: 'none', padding: 4 }}>
                  <Checkbox checked={done}/>
                </button>
              </div>
            );
          })}
        </div>
      </div>

      {/* 전체 운동 라이브러리 */}
      <div style={{ padding: '24px 22px 0' }}>
        <Eyebrow>다른 운동 둘러보기</Eyebrow>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {EXERCISES.filter(e => !todaySchedule.exercises.find(x => x.id === e.id)).map((ex) => (
            <button key={ex.id} onClick={() => navigate(`exercise/${ex.id}`)} style={{
              textAlign: 'left',
              background: 'var(--hg-surface)',
              border: '1px solid var(--hg-line-soft)',
              borderRadius: 16, padding: 14,
              display: 'flex', flexDirection: 'column', gap: 8,
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 12,
                background: toneBg[ex.tone], color: toneMap[ex.tone],
                display: 'grid', placeItems: 'center',
              }}>
                <ExerciseIcon name={ex.icon} color={toneMap[ex.tone]}/>
              </div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)' }}>{ex.name}</div>
                <div style={{ fontSize: 10, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 2 }}>{ex.duration}분 · {intensityLabel(ex.intensity)}</div>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* 안내 */}
      <div style={{ padding: '20px 22px 24px' }}>
        <div style={{
          padding: 14, borderRadius: 14,
          background: 'var(--hg-bg-deeper)',
          fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600,
          lineHeight: 1.6, textAlign: 'center',
        }}>
          무리한 운동은 금물이에요. 통증·어지러움이 있으면 즉시 멈추세요.<br/>
          운동 시작 시점은 담당 의료진과 상의하세요.
        </div>
      </div>
    </>
  );
}

function ExerciseDetailScreen({ navigate, exercise: ex }) {
  const s = useStore();
  const today = todayISO();
  const doneList = (s.exerciseLog && s.exerciseLog[today]) || [];
  const done = doneList.includes(ex.id);

  const toneC = { sage: 'var(--hg-sage)', clay: 'var(--hg-clay)', honey: 'var(--hg-honey)', mist: 'var(--hg-mist)' }[ex.tone];
  const toneBg = { sage: 'var(--hg-sage-tint)', clay: 'var(--hg-clay-tint)', honey: 'var(--hg-honey-tint)', mist: 'var(--hg-mist-tint)' }[ex.tone];

  const markDone = () => {
    const log = { ...(s.exerciseLog || {}) };
    const list = log[today] || [];
    log[today] = done ? list.filter(id => id !== ex.id) : [...list, ex.id];
    Store.save(K.exerciseLog, log);
    showToast(done ? '취소됨' : '완료!');
  };

  return (
    <>
      <ScreenHeader title={ex.name} sub={`${ex.duration}분 · ${intensityLabel(ex.intensity)}`}
        back onBack={() => navigate('exercise')} />

      {/* 히어로 */}
      <div style={{ padding: '6px 22px 0' }}>
        <div style={{
          background: `linear-gradient(135deg, ${toneBg}, var(--hg-surface) 130%)`,
          borderRadius: 22, padding: 20,
          display: 'flex', alignItems: 'center', gap: 16,
          border: `1px solid ${toneC}33`,
        }}>
          <div style={{
            width: 64, height: 64, borderRadius: 18, flexShrink: 0,
            background: toneC, color: '#fff',
            display: 'grid', placeItems: 'center',
          }}>
            <ExerciseIcon name={ex.icon} color="#fff" size={32}/>
          </div>
          <div style={{ flex: 1 }}>
            <div className="hg-serif" style={{ fontSize: 20, fontWeight: 600, color: 'var(--hg-ink)', letterSpacing: '-0.02em', marginBottom: 4 }}>
              {ex.name}
            </div>
            <div style={{ fontSize: 12, color: 'var(--hg-ink-2)', fontWeight: 500, lineHeight: 1.6 }}>{ex.desc}</div>
          </div>
        </div>
      </div>

      {/* 따라하는 단계 */}
      <div style={{ padding: '16px 22px 0' }}>
        <Eyebrow>따라하기</Eyebrow>
        <Panel style={{ padding: 4 }}>
          {ex.steps.map((step, i) => (
            <div key={i} style={{
              display: 'flex', gap: 12,
              padding: '14px 14px',
              borderBottom: i < ex.steps.length - 1 ? '1px solid var(--hg-line-soft)' : 'none',
            }}>
              <div style={{
                minWidth: 24, height: 24, borderRadius: '50%', flexShrink: 0,
                background: toneBg, color: toneC,
                display: 'grid', placeItems: 'center',
                fontFamily: '"Noto Serif KR", serif', fontSize: 12, fontWeight: 700,
              }}>{i + 1}</div>
              <div style={{ fontSize: 13, color: 'var(--hg-ink-2)', lineHeight: 1.7 }}>{step}</div>
            </div>
          ))}
        </Panel>
      </div>

      {/* 주의 */}
      <div style={{ padding: '16px 22px 0' }}>
        <Panel style={{ padding: 14, background: 'var(--hg-honey-tint)', borderColor: 'var(--hg-honey-soft)' }}>
          <div style={{ display: 'flex', gap: 10 }}>
            <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--hg-honey)', color: '#fff', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 12, flexShrink: 0 }}>!</span>
            <div style={{ fontSize: 12, color: 'var(--hg-ink-2)', fontWeight: 600, lineHeight: 1.6 }}>
              {ex.caution}
            </div>
          </div>
        </Panel>
      </div>

      {/* 완료 버튼 */}
      <div style={{ padding: '20px 22px 24px' }}>
        <PrimaryButton onClick={markDone} color={done ? 'var(--hg-muted)' : toneC} shadow={`0 8px 20px ${toneC}40`}>
          {done ? '✓ 완료됨 · 취소' : '오늘 완료로 표시'}
        </PrimaryButton>
      </div>
    </>
  );
}

function intensityLabel(i) {
  return i === 'gentle' ? '아주 가볍게' : i === 'light' ? '가볍게' : '보통';
}

function ExerciseIcon({ name, color, size = 22 }) {
  const sw = 1.6, c = color;
  const s = size;
  if (name === 'breath')   return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><path d="M3 13c4-4 12-4 16 0M3 11c4-3 12-3 16 0M5 15c3-2 9-2 12 0" stroke={c} strokeWidth={sw} strokeLinecap="round"/><circle cx="11" cy="6" r="2" stroke={c} strokeWidth={sw}/></svg>;
  if (name === 'stretch')  return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><circle cx="11" cy="5" r="2" stroke={c} strokeWidth={sw}/><path d="M11 7v6M4 10l7 3 7-3M8 19l3-6 3 6" stroke={c} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"/></svg>;
  if (name === 'arm')      return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><circle cx="6" cy="5" r="2" stroke={c} strokeWidth={sw}/><path d="M6 7v6M6 10l4 4 5-7" stroke={c} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"/></svg>;
  if (name === 'walk')     return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><circle cx="12" cy="4" r="2" stroke={c} strokeWidth={sw}/><path d="M12 6l-3 6 3 2v5M9 12l-3 1M14 9l3 2" stroke={c} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"/></svg>;
  if (name === 'chair')    return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><circle cx="11" cy="4" r="2" stroke={c} strokeWidth={sw}/><path d="M11 6v6M7 12h8M7 12v6M15 12v6M4 18h14" stroke={c} strokeWidth={sw} strokeLinecap="round"/></svg>;
  if (name === 'balance')  return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><circle cx="11" cy="3.5" r="1.5" stroke={c} strokeWidth={sw}/><path d="M11 5v8M11 9l-4-2M11 9l4-2M11 13l-2 6M11 13v6" stroke={c} strokeWidth={sw} strokeLinecap="round"/></svg>;
  if (name === 'massage')  return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><path d="M4 13c2-2 5-3 7-3s5 1 7 3M4 10c2-2 5-3 7-3s5 1 7 3M4 16c2-2 5-3 7-3s5 1 7 3" stroke={c} strokeWidth={sw} strokeLinecap="round"/></svg>;
  if (name === 'mind')     return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><path d="M11 3a6 6 0 016 6c0 3-2 5-4 6v3M11 3a6 6 0 00-6 6c0 3 2 5 4 6v3M9 18h4" stroke={c} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"/></svg>;
  return null;
}

Object.assign(window, { ExerciseScreen, ExerciseListScreen, ExerciseDetailScreen, ExerciseIcon, intensityLabel });
