// 하루결 — 환자: 오늘 홈

function HomeScreen({ navigate }) {
  const s = useStore();
  const today = todayISO();
  const profile = s.profile;
  const mood = s.mood[today] || null;
  const checks = s.checks[today] || {};
  const checkItems = [
    { key: 'water',   t: '미지근한 물 6잔 이상', d: '한 번에 많이 말고 조금씩' },
    { key: 'protein', t: '단백질 식사 한 끼',     d: '두부, 계란찜, 부드러운 생선' },
    { key: 'walk',    t: '짧은 산책 또는 스트레칭', d: '5–10분이면 충분해요' },
    { key: 'log',     t: '오늘 증상 기록',         d: '저녁에 메모 한 줄' },
  ];
  const doneCount = checkItems.filter(i => checks[i.key]).length;

  // 회복 일차
  const recoveryDay = daysBetween(profile.cycleStartDate, today) + 1;
  const upcoming = s.schedules
    .filter(x => x.date >= today)
    .sort((a, b) => (a.date + a.time).localeCompare(b.date + b.time))[0];

  // 오늘 복용 도즈 계산
  const dailyMeds = (s.meds || []).filter(m => m.type === 'daily' && m.schedule.length > 0);
  const todayTaken = dailyMeds.reduce((sum, m) =>
    sum + m.schedule.filter(t => getDoseStatus(s.medsLog, today, m.id, t) === 'taken').length, 0);
  const todayTotal = dailyMeds.reduce((sum, m) => sum + m.schedule.length, 0);

  const moodOptions = [
    { v: 'good',      l: '좋음',      c: 'var(--hg-sage)',  bg: 'var(--hg-sage-tint)' },
    { v: 'ok',        l: '괜찮음',    c: 'var(--hg-honey)', bg: 'var(--hg-honey-tint)' },
    { v: 'hard',      l: '힘듦',      c: 'var(--hg-clay)',  bg: 'var(--hg-clay-tint)' },
    { v: 'very-hard', l: '많이 힘듦',  c: 'var(--hg-rose)',  bg: 'var(--hg-rose-soft)' },
  ];

  return (
    <>
      {/* 인사 헤더 */}
      <div style={{ padding: '54px 22px 6px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 12, color: 'var(--hg-muted)', fontWeight: 600, marginBottom: 2 }}>{fmtDateKR(today)}</div>
          <div className="hg-serif" style={{ fontSize: 24, fontWeight: 600, letterSpacing: '-0.025em', color: 'var(--hg-ink)' }}>
            안녕하세요, {profile.name}님
          </div>
        </div>
        <button onClick={() => navigate('settings')} aria-label="설정" style={{
          width: 40, height: 40, borderRadius: '50%',
          background: 'var(--hg-clay-tint)',
          border: '1px solid var(--hg-line)',
          color: 'var(--hg-clay-dark)', fontWeight: 700, fontSize: 14,
        }}>{profile.name.slice(0, 1)}</button>
      </div>

      {/* 무드 카드 */}
      <div style={{ padding: '16px 22px 0' }}>
        <div style={{
          position: 'relative', borderRadius: 26, overflow: 'hidden',
          height: 220, boxShadow: 'var(--hg-shadow-md)',
        }}>
          <MoodImage src={IMG.morning} alt="아침 빛"
            style={{ position: 'absolute', inset: 0 }} />
          <div style={{
            position: 'absolute', inset: 0,
            background: 'linear-gradient(180deg, rgba(143,166,126,0.0) 30%, rgba(74,54,32,0.45) 100%)',
          }} />
          <div style={{
            position: 'absolute', top: 16, left: 16,
            padding: '6px 12px', borderRadius: 999,
            background: 'rgba(255,253,247,0.86)',
            backdropFilter: 'blur(10px)',
            fontSize: 11, fontWeight: 700, color: 'var(--hg-clay-dark)',
            letterSpacing: '-0.02em',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{
              padding: '2px 7px', borderRadius: 999,
              background: getStage(profile.stage).color, color: '#fff',
              fontSize: 10, fontWeight: 700,
            }}>{getStage(profile.stage).label}</span>
            {profile.cycle}차 항암 · 회복 {recoveryDay}일차
          </div>
          <div style={{ position: 'absolute', left: 18, right: 18, bottom: 16, color: '#fff' }}>
            <div className="hg-serif" style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1.3 }}>
              오늘은 천천히<br/>몸이 회복되는 날이에요
            </div>
          </div>
        </div>
      </div>

      {/* 컨디션 선택 */}
      <div style={{ padding: '18px 22px 0' }}>
        <Panel style={{ padding: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)' }}>오늘 컨디션은 어때요?</div>
            {mood && <span style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600 }}>변경</span>}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
            {moodOptions.map((m) => {
              const on = mood === m.v;
              return (
                <button key={m.v} onClick={() => { s.setMood(today, m.v); showToast(`컨디션: ${m.l}`); }} style={{
                  aspectRatio: '1 / 1', borderRadius: 16,
                  background: on ? m.bg : 'var(--hg-surface-2)',
                  border: on ? `1.5px solid ${m.c}` : '1px solid var(--hg-line-soft)',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4,
                  padding: 0, transition: 'all 160ms',
                }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: '50%',
                    background: on ? m.c : 'transparent',
                    border: `1.5px solid ${m.c}`,
                  }} />
                  <span style={{ fontSize: 11, fontWeight: on ? 700 : 600, color: on ? m.c : 'var(--hg-muted)' }}>{m.l}</span>
                </button>
              );
            })}
          </div>
        </Panel>
      </div>

      {/* 다음 진료 + 복약 (둘 다 한 줄 카드 강조) */}
      <div style={{ padding: '12px 22px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <button onClick={() => navigate('schedule')} style={{
          textAlign: 'left', padding: 14, borderRadius: 18,
          background: 'linear-gradient(135deg, var(--hg-mist-tint), var(--hg-surface) 130%)',
          border: '1px solid var(--hg-mist-soft)',
        }}>
          <Eyebrow color="var(--hg-mist)">다음 진료</Eyebrow>
          {upcoming ? (
            <>
              <div className="hg-serif" style={{ fontSize: 18, fontWeight: 600, color: 'var(--hg-ink)', lineHeight: 1.25, letterSpacing: '-0.02em' }}>
                {fmtMonth(upcoming.date).replace(' ', '\u00A0')}
              </div>
              <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 6 }}>
                {upcoming.time} · {upcoming.dept}
              </div>
            </>
          ) : (
            <div style={{ fontSize: 13, color: 'var(--hg-muted)' }}>예약 없음</div>
          )}
        </button>
        <button onClick={() => navigate('meds')} style={{
          textAlign: 'left', padding: 14, borderRadius: 18,
          background: 'linear-gradient(135deg, var(--hg-honey-tint), var(--hg-surface) 130%)',
          border: '1px solid var(--hg-honey-soft)',
        }}>
          <Eyebrow color="var(--hg-honey)">오늘 복약</Eyebrow>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
            <span className="hg-serif" style={{ fontSize: 24, fontWeight: 600, color: 'var(--hg-ink)', letterSpacing: '-0.02em', lineHeight: 1 }}>{todayTaken}</span>
            <span style={{ fontSize: 13, color: 'var(--hg-muted)', fontWeight: 600 }}>/ {todayTotal}회</span>
          </div>
          <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 6 }}>
            매일 약 {dailyMeds.length}가지
          </div>
        </button>
      </div>

      {/* 보호자 빠른 연락 + 안전 체크 */}
      <div style={{ padding: '12px 22px 0' }}>
        <button onClick={() => navigate('safety')} style={{
          width: '100%', textAlign: 'left',
          padding: 14, borderRadius: 18,
          background: 'linear-gradient(120deg, var(--hg-sage-tint), var(--hg-surface))',
          border: '1px solid var(--hg-sage-soft)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 40, height: 40, borderRadius: 12,
            background: 'var(--hg-sage)', color: '#fff',
            display: 'grid', placeItems: 'center', flexShrink: 0,
          }}>
            <svg width="20" height="20" viewBox="0 0 22 22" fill="none">
              <path d="M11 3l7 3v6c0 4-3 7-7 7s-7-3-7-7V6l7-3z" stroke="#fff" strokeWidth="1.6" strokeLinejoin="round"/>
              <path d="M8 11l2.5 2.5L15 9" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)' }}>안전 확인 · 보호자 빠른 연락</div>
            <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 2 }}>혼자 있을 때 든든하게</div>
          </div>
          <span style={{ color: 'var(--hg-sage)', fontSize: 16, flexShrink: 0 }}>›</span>
        </button>
      </div>

      {/* 오늘의 목표 */}
      <div style={{ padding: '12px 22px 0' }}>
        <button onClick={() => navigate('goals')} style={{
          width: '100%', textAlign: 'left',
          padding: 16, borderRadius: 22,
          background: 'linear-gradient(135deg, var(--hg-honey-tint), var(--hg-surface) 130%)',
          border: '1px solid rgba(217,166,108,0.24)',
          display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <div style={{
            width: 42, height: 42, borderRadius: 12,
            background: 'var(--hg-honey)', color: '#fff',
            display: 'grid', placeItems: 'center', flexShrink: 0,
            fontFamily: '"Noto Serif KR", serif', fontWeight: 600, fontSize: 16,
          }}>
            {s.goals.filter(g => !g.done).length}
          </div>
          <div style={{ flex: 1 }}>
            <Eyebrow color="var(--hg-honey)">오늘의 목표</Eyebrow>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--hg-ink)', lineHeight: 1.5 }}>
              {s.goals.filter(g => !g.done).length === 0
                ? '작은 목표 하나로 시작해볼까요?'
                : `${s.goals.filter(g => !g.done && g.period === 'daily').length}개 진행 중 · 완료 ${s.goals.filter(g => g.done).length}`}
            </div>
          </div>
          <span style={{ color: 'var(--hg-honey)', fontSize: 18, flexShrink: 0 }}>›</span>
        </button>
      </div>

      {/* 오늘 할 일 */}
      <div style={{ padding: '12px 22px 0' }}>
        <Panel>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)' }}>오늘의 회복 체크</div>
            <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 700 }}>{doneCount} / {checkItems.length}</div>
          </div>
          {checkItems.map((c) => {
            const on = !!checks[c.key];
            return (
              <button key={c.key} onClick={() => s.setCheck(today, c.key, !on)} style={{
                display: 'flex', alignItems: 'flex-start', gap: 12,
                padding: '10px 0', width: '100%', textAlign: 'left',
                borderTop: '1px solid var(--hg-line-soft)',
              }}>
                <Checkbox checked={on} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: on ? 'var(--hg-muted)' : 'var(--hg-ink)', textDecoration: on ? 'line-through' : 'none' }}>{c.t}</div>
                  <div style={{ fontSize: 12, color: 'var(--hg-muted)', marginTop: 2 }}>{c.d}</div>
                </div>
              </button>
            );
          })}
        </Panel>
      </div>

      {/* 빠른 기록 */}
      <div style={{ padding: '14px 22px 24px' }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--hg-muted)', marginBottom: 10, letterSpacing: '0.08em', textTransform: 'uppercase' }}>빠른 기록</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {[
            { l: '몸 상태',   s: '메스꺼움·통증·저림', c: 'var(--hg-clay)',  bg: 'var(--hg-clay-tint)',  go: 'symptom-new' },
            { l: '식사·수분', s: '먹은 것과 양',       c: 'var(--hg-sage)',  bg: 'var(--hg-sage-tint)',  go: 'meal-new' },
            { l: '복용 약',   s: '항암제·진통제',      c: 'var(--hg-honey)', bg: 'var(--hg-honey-tint)', go: 'meds' },
            { l: '진료 질문', s: '메모 추가',          c: 'var(--hg-mist)',  bg: 'var(--hg-mist-tint)',  go: 'questions-new' },
          ].map((q) => (
            <button key={q.l} onClick={() => navigate(q.go)} style={{
              padding: 14, borderRadius: 18, textAlign: 'left',
              background: q.bg, border: `1px solid ${q.c}33`,
              display: 'flex', flexDirection: 'column', gap: 4,
            }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: q.c }}>{q.l}</div>
              <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600 }}>{q.s}</div>
              <div style={{ marginTop: 8, alignSelf: 'flex-end' }}>
                <span style={{
                  width: 28, height: 28, borderRadius: '50%', background: q.c, color: '#fff',
                  display: 'grid', placeItems: 'center', fontSize: 16, fontWeight: 400,
                }}>＋</span>
              </div>
            </button>
          ))}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { HomeScreen });
