// 하루결 — 환자: 식사 가이드 & 기록

const MEAL_GUIDES = {
  nausea: {
    title: '메스꺼움이 있을 때',
    body: '강한 냄새와 기름진 음식을 피하고, 한 번에 많이 먹기보다 조금씩 자주 드세요.',
    img: 'tea',
    items: [
      { label: '미지근한 죽·누룽지',     hint: '소화 부담이 적어요' },
      { label: '바나나·크래커·토스트',   hint: '아침 메스꺼움에' },
      { label: '차갑게 식힌 단백질',     hint: '냄새가 덜해요' },
      { label: '물은 조금씩 자주',       hint: '한 번에 많이 X' },
    ],
    avoid: ['기름진 튀김', '강한 향신료', '날 음식·회', '카페인 과다', '뜨거운 음식'],
  },
  mouth: {
    title: '입안이 헐 때',
    body: '맵고 뜨겁고 거친 음식은 자극이 됩니다. 부드럽고 촉촉한 식감으로 바꾸어 드세요.',
    img: 'meal',
    items: [
      { label: '계란찜·두부',  hint: '부드러운 단백질' },
      { label: '요거트·스무디', hint: '시원하고 부드럽게' },
      { label: '크림수프',      hint: '삼키기 편해요' },
      { label: '잘게 다진 닭', hint: '씹기 편하게' },
    ],
    avoid: ['뜨거운 국물', '신맛 강한 과일', '탄산음료', '딱딱한 견과류', '매운 음식'],
  },
  fatigue: {
    title: '피로가 심한 날',
    body: '요리 부담을 줄이면서도 단백질과 열량을 놓치지 않게. 보호자가 미리 소분해두면 좋아요.',
    img: 'meal',
    items: [
      { label: '삶은 달걀·두유', hint: '준비 쉬운 단백질' },
      { label: '닭죽·소고기죽',  hint: '한 그릇 식사' },
      { label: '견과류 간식',    hint: '소량씩 자주' },
      { label: '냉동 반조리',    hint: '조리 시간 단축' },
    ],
    avoid: ['요리 시간 긴 메뉴', '외식 강한 향', '늦은 시간 과식'],
  },
  normal: {
    title: '평소 식사 가이드',
    body: '균형 잡힌 한 끼와 충분한 수분이 가장 중요해요. 단백질을 빼먹지 마세요.',
    img: 'tea',
    items: [
      { label: '단백질 1 손바닥', hint: '두부·계란·생선' },
      { label: '곡물 ½ 공기',     hint: '잡곡밥 권장' },
      { label: '채소 1 ~ 2종',   hint: '익힌 채소' },
      { label: '물 6 ~ 8잔',     hint: '하루 총량' },
    ],
    avoid: ['날 음식·회', '면역 약할 땐 생채소'],
  },
};

function MealsScreen({ navigate, initialOpen }) {
  const s = useStore();
  const today = todayISO();
  const [mode, setMode] = React.useState('nausea');
  const [openAdd, setOpenAdd] = React.useState(initialOpen || false);
  const guide = MEAL_GUIDES[mode];

  const todayMeals = s.meals.filter(m => m.date === today);
  const waterCount = todayMeals.filter(m => m.type === '수분').length;
  const tabs = [
    { v: 'nausea',  l: '메스꺼움' },
    { v: 'mouth',   l: '구내염' },
    { v: 'fatigue', l: '피로' },
    { v: 'normal',  l: '평소' },
  ];

  return (
    <>
      <ScreenHeader title="식사" sub={`오늘은 ${tabs.find(t => t.v === mode).l} 모드`} />

      {/* 상황 탭 */}
      <div style={{ padding: '6px 22px 0' }}>
        <div style={{
          display: 'flex', gap: 6, padding: 4,
          background: 'var(--hg-bg-deeper)',
          borderRadius: 14, border: '1px solid var(--hg-line-soft)',
        }}>
          {tabs.map((t) => (
            <button key={t.v} onClick={() => setMode(t.v)} style={{
              flex: 1, textAlign: 'center', padding: '10px 0', borderRadius: 11,
              background: mode === t.v ? 'var(--hg-surface-2)' : 'transparent',
              color: mode === t.v ? 'var(--hg-clay-dark)' : 'var(--hg-muted)',
              fontSize: 13, fontWeight: mode === t.v ? 700 : 600,
              boxShadow: mode === t.v ? '0 1px 3px rgba(74,54,32,0.08)' : 'none',
            }}>{t.l}</button>
          ))}
        </div>
      </div>

      {/* 가이드 카드 */}
      <div style={{ padding: '14px 22px 0' }}>
        <Panel style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ position: 'relative', height: 140 }}>
            <MoodImage src={IMG[guide.img]} alt={guide.title}
              style={{ position: 'absolute', inset: 0 }} />
            <div style={{
              position: 'absolute', inset: 0,
              background: 'linear-gradient(180deg, rgba(42,36,29,0.0), rgba(42,36,29,0.45))',
            }} />
            <div style={{ position: 'absolute', left: 18, right: 18, bottom: 14, color: '#fff' }}>
              <div style={{ fontSize: 11, fontWeight: 700, marginBottom: 4, opacity: 0.9, letterSpacing: '0.05em', textTransform: 'uppercase' }}>오늘의 추천</div>
              <div className="hg-serif" style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em' }}>{guide.title}</div>
            </div>
          </div>
          <div style={{ padding: 18 }}>
            <p style={{ fontSize: 13, color: 'var(--hg-ink-2)', lineHeight: 1.7, margin: 0 }}>{guide.body}</p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 14 }}>
              {guide.items.map((it) => (
                <div key={it.label} style={{
                  background: 'var(--hg-sage-tint)',
                  border: '1px solid var(--hg-sage-soft)',
                  borderRadius: 14, padding: 12,
                }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--hg-ink)', marginBottom: 2 }}>{it.label}</div>
                  <div style={{ fontSize: 10, color: 'var(--hg-muted)', fontWeight: 600 }}>{it.hint}</div>
                </div>
              ))}
            </div>
          </div>
        </Panel>
      </div>

      {/* 피해야 할 것 */}
      <div style={{ padding: '12px 22px 0' }}>
        <Panel style={{ background: 'var(--hg-surface-2)', borderColor: 'rgba(194,85,74,0.18)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <span style={{
              width: 22, height: 22, borderRadius: '50%',
              background: 'var(--hg-rose-soft)', color: 'var(--hg-rose)',
              display: 'grid', placeItems: 'center', fontSize: 14, fontWeight: 700,
            }}>!</span>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)' }}>지금은 피해주세요</div>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {guide.avoid.map((t) => (
              <span key={t} style={{
                padding: '6px 11px', borderRadius: 999,
                background: 'var(--hg-bg-deeper)', color: 'var(--hg-ink-2)',
                fontSize: 11, fontWeight: 600, border: '1px solid var(--hg-line-soft)',
              }}>{t}</span>
            ))}
          </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 }}>{todayMeals.length}개 · 수분 {waterCount}잔</span>
        </div>
        {todayMeals.length === 0 ? (
          <div style={{ padding: 20, textAlign: 'center', color: 'var(--hg-muted)', fontSize: 13, background: 'var(--hg-surface)', borderRadius: 16, border: '1px dashed var(--hg-line)' }}>
            아직 기록이 없어요
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {todayMeals.map((r) => (
              <div key={r.id} style={{
                display: 'flex', alignItems: 'center', gap: 14,
                padding: 14, borderRadius: 16,
                background: 'var(--hg-surface)',
                border: '1px solid var(--hg-line-soft)',
              }}>
                <div style={{
                  width: 44, height: 44, borderRadius: 12,
                  background: r.tone === 'ok' ? 'var(--hg-sage-tint)' : 'var(--hg-honey-tint)',
                  border: `1px solid ${r.tone === 'ok' ? 'var(--hg-sage-soft)' : 'var(--hg-honey-soft)'}`,
                  display: 'grid', placeItems: 'center',
                  fontSize: 10, fontWeight: 700,
                  color: r.tone === 'ok' ? 'var(--hg-sage)' : 'var(--hg-honey)',
                  flexShrink: 0,
                }}>{r.type}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)' }}>{r.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600 }}>{r.amount}</div>
                  </div>
                  {r.memo && <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 500, marginTop: 2 }}>{r.memo}</div>}
                </div>
                <button onClick={() => { s.removeMeal(r.id); showToast('삭제됨'); }} style={{
                  width: 26, height: 26, borderRadius: '50%',
                  background: 'var(--hg-bg-deeper)', color: 'var(--hg-muted)', fontSize: 11,
                }}>✕</button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 더 알아보기 — 도서관 링크 */}
      <div style={{ padding: '14px 22px 0' }}>
        <button onClick={() => navigate('library')} style={{
          width: '100%', textAlign: 'left',
          padding: 14, borderRadius: 16,
          background: 'var(--hg-surface-2)',
          border: '1px dashed var(--hg-line)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 32, height: 32, borderRadius: 10,
            background: 'var(--hg-sage-tint)', color: 'var(--hg-sage)',
            display: 'grid', placeItems: 'center', flexShrink: 0,
          }}>
            <svg width="16" height="16" viewBox="0 0 22 22" fill="none">
              <path d="M4 4h14v14H4z M4 8h14 M9 4v14" stroke="currentColor" strokeWidth="1.6" fill="none"/>
            </svg>
          </div>
          <div style={{ flex: 1 }}>
            <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-muted)', fontSize: 16 }}>›</span>
        </button>
      </div>

      {/* 빠른 추가 */}
      <div style={{ padding: '16px 22px 24px' }}>
        <PrimaryButton onClick={() => setOpenAdd(true)}>
          <span style={{ marginRight: 6, fontSize: 18, fontWeight: 300 }}>＋</span> 먹은 것 기록하기
        </PrimaryButton>
      </div>

      {openAdd && <AddMealSheet onClose={() => setOpenAdd(false)} onAdd={(x) => { s.addMeal(x); showToast('기록됨'); setOpenAdd(false); }} />}
    </>
  );
}

function AddMealSheet({ onClose, onAdd }) {
  const [form, setForm] = React.useState({
    date: todayISO(), time: nowHM(), name: '', type: '아침', amount: '', memo: '', tone: 'ok',
  });
  const types = ['아침', '점심', '저녁', '간식', '수분'];
  const tones = [
    { v: 'ok',  l: '잘 먹음' },
    { v: 'low', l: '조금만'  },
    { v: 'bad', l: '거의 못함' },
  ];

  return (
    <Sheet title="식사 기록" onClose={onClose}>
      <label className="hg-label">유형</label>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {types.map(t => (
          <button key={t} onClick={() => setForm({ ...form, type: t })} style={{
            padding: '8px 16px', borderRadius: 999,
            background: form.type === t ? 'var(--hg-sage)' : 'var(--hg-bg-deeper)',
            color: form.type === t ? '#fff' : 'var(--hg-ink-2)',
            fontSize: 12, fontWeight: 700,
          }}>{t}</button>
        ))}
      </div>

      <label className="hg-label" style={{ marginTop: 14 }}>먹은 것</label>
      <input className="hg-input" placeholder={form.type === '수분' ? '예: 미지근한 물' : '예: 닭죽'} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}/>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14 }}>
        <div>
          <label className="hg-label">양</label>
          <input className="hg-input" placeholder="½ 공기 / 1잔" value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })}/>
        </div>
        <div>
          <label className="hg-label">시간</label>
          <input type="time" className="hg-input" value={form.time} onChange={(e) => setForm({ ...form, time: e.target.value })}/>
        </div>
      </div>

      <label className="hg-label" style={{ marginTop: 14 }}>먹은 정도</label>
      <div style={{ display: 'flex', gap: 6 }}>
        {tones.map(t => (
          <button key={t.v} onClick={() => setForm({ ...form, tone: t.v })} style={{
            flex: 1, padding: '10px 0', borderRadius: 12,
            background: form.tone === t.v ? 'var(--hg-clay)' : 'var(--hg-bg-deeper)',
            color: form.tone === t.v ? '#fff' : 'var(--hg-ink-2)',
            fontSize: 12, fontWeight: 700,
          }}>{t.l}</button>
        ))}
      </div>

      <label className="hg-label" style={{ marginTop: 14 }}>메모 (선택)</label>
      <textarea className="hg-textarea" placeholder="기억해둘 점" value={form.memo} onChange={(e) => setForm({ ...form, memo: e.target.value })}/>

      <div style={{ marginTop: 18 }}>
        <PrimaryButton disabled={!form.name} onClick={() => onAdd(form)} color="var(--hg-sage)" shadow="0 8px 20px rgba(143,166,126,0.32)">저장</PrimaryButton>
      </div>
    </Sheet>
  );
}

Object.assign(window, { MealsScreen, MEAL_GUIDES });
