// 하루결 — 안전 확인 (보호자 연락) + 동기 / 생일 / 메시지

// ════════════════════════════════════════════════════════════
// 시간 헬퍼
// ════════════════════════════════════════════════════════════
function hoursSince(iso) {
  if (!iso) return Infinity;
  return (Date.now() - new Date(iso).getTime()) / 3_600_000;
}
function fmtRelative(ts) {
  const diff = Date.now() - (typeof ts === 'number' ? ts : new Date(ts).getTime());
  const mins = Math.floor(diff / 60_000);
  if (mins < 1) return '방금';
  if (mins < 60) return `${mins}분 전`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}시간 전`;
  const days = Math.floor(hrs / 24);
  if (days < 7) return `${days}일 전`;
  return new Date(typeof ts === 'number' ? ts : ts).toLocaleDateString('ko-KR');
}

function daysUntilBirthday(birthday, today = todayISO()) {
  if (!birthday) return null;
  const [y, m, d] = birthday.split('-').map(Number);
  const todayD = new Date(today + 'T00:00:00');
  const yearNow = todayD.getFullYear();
  let next = new Date(yearNow, m - 1, d);
  if (next < todayD) next = new Date(yearNow + 1, m - 1, d);
  return Math.round((next - todayD) / 86_400_000);
}

// ════════════════════════════════════════════════════════════
// 안전 확인 화면
// ════════════════════════════════════════════════════════════
function SafetyScreen({ navigate }) {
  const s = useStore();
  const profile = s.profile;
  const safety = s.safety;
  const hoursIdle = hoursSince(safety.lastCheckIn);
  const threshold = safety.thresholdHours || 24;
  const overdue = hoursIdle > threshold;
  const pct = Math.min(100, Math.round((hoursIdle / threshold) * 100));

  const checkIn = () => {
    s.checkIn();
    showToast('오늘 안전 체크 완료');
  };

  const callPhone = (phone) => { window.location.href = `tel:${phone}`; };
  const sendSMS = () => {
    const body = encodeURIComponent(`안녕하세요. ${profile.name}이에요. 잠시 연락드릴게요.`);
    window.location.href = `sms:${profile.caregiverPhone}?body=${body}`;
  };

  const thresholds = [12, 24, 48, 72];

  return (
    <>
      <ScreenHeader
        title="안전 확인"
        sub="혼자 있을 때 든든하게"
        back onBack={() => navigate('more')}
      />

      {/* 오늘 체크인 카드 */}
      <div style={{ padding: '6px 22px 0' }}>
        <Panel style={{
          padding: 22,
          background: overdue
            ? 'linear-gradient(135deg, #FCEEEC, var(--hg-surface) 130%)'
            : 'linear-gradient(135deg, var(--hg-sage-tint), var(--hg-surface) 130%)',
          borderColor: overdue ? 'rgba(194,85,74,0.32)' : 'var(--hg-sage-soft)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ position: 'relative', width: 84, height: 84 }}>
              <svg width="84" height="84" viewBox="0 0 84 84" style={{ transform: 'rotate(-90deg)' }}>
                <circle cx="42" cy="42" r="38" fill="none" stroke={overdue ? 'rgba(194,85,74,0.18)' : 'rgba(143,166,126,0.18)'} strokeWidth="6"/>
                <circle cx="42" cy="42" r="38" fill="none" stroke={overdue ? 'var(--hg-rose)' : 'var(--hg-sage)'} strokeWidth="6"
                  strokeDasharray={`${38 * 2 * Math.PI * pct/100} ${38 * 2 * Math.PI}`} strokeLinecap="round"/>
              </svg>
              <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>
                <span style={{ fontSize: 24, lineHeight: 1 }}>{overdue ? '⚠️' : '✓'}</span>
              </div>
            </div>
            <div style={{ flex: 1 }}>
              <Eyebrow color={overdue ? 'var(--hg-rose)' : 'var(--hg-sage)'}>
                {overdue ? `${Math.round(hoursIdle)}시간 연락 없음` : '안전 체크 정상'}
              </Eyebrow>
              <div className="hg-serif" style={{ fontSize: 18, fontWeight: 600, color: 'var(--hg-ink)', letterSpacing: '-0.02em', lineHeight: 1.3, marginTop: 4 }}>
                {overdue ? '오늘 안전 체크를 해주세요' : `${Math.round(hoursIdle)}시간 전 마지막 체크`}
              </div>
              <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 6 }}>
                {threshold}시간 이상 활동 없으면 보호자에게 알림
              </div>
            </div>
          </div>

          <button onClick={checkIn} style={{
            marginTop: 16, width: '100%', minHeight: 54,
            background: 'var(--hg-sage)', color: '#fff',
            fontSize: 15, fontWeight: 700, borderRadius: 14,
            boxShadow: '0 6px 16px rgba(143,166,126,0.32)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <svg width="18" height="18" viewBox="0 0 16 16" fill="none">
              <path d="M3 8l4 4 6-8" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            오늘 안전해요
          </button>
        </Panel>
      </div>

      {/* 보호자 빠른 연락 */}
      <div style={{ padding: '16px 22px 0' }}>
        <Eyebrow color="var(--hg-clay)">보호자에게 빠르게</Eyebrow>
        <Panel style={{ padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
            <div style={{
              width: 48, height: 48, borderRadius: '50%',
              background: 'var(--hg-mist)', color: '#fff',
              display: 'grid', placeItems: 'center', flexShrink: 0,
              fontWeight: 700, fontSize: 16,
            }}>{(profile.caregiverName || '?').slice(0, 1)}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)' }}>{profile.caregiverName || '보호자'}</div>
              <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 2 }}>{profile.caregiverPhone}</div>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <button onClick={() => callPhone(profile.caregiverPhone)} style={{
              padding: 14, borderRadius: 14,
              background: 'var(--hg-clay)', color: '#fff',
              fontSize: 13, fontWeight: 700,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              boxShadow: '0 4px 12px rgba(181,117,90,0.28)',
            }}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="#fff"><path d="M4 2.2l2.2-.7 1.4 2.7-1.4 1.4c.7 2.2 2.2 3.7 4.4 4.4l1.4-1.4 2.7 1.4-.7 2.2c-3.7 0-10.3-6.5-10.3-10.3z"/></svg>
              전화
            </button>
            <button onClick={sendSMS} style={{
              padding: 14, borderRadius: 14,
              background: 'var(--hg-honey)', color: '#fff',
              fontSize: 13, fontWeight: 700,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              boxShadow: '0 4px 12px rgba(217,166,108,0.28)',
            }}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="#fff"><path d="M1.5 3.5h13v8h-9l-4 3z"/></svg>
              문자
            </button>
          </div>
        </Panel>
      </div>

      {/* 위급 응급 */}
      <div style={{ padding: '12px 22px 0' }}>
        <button onClick={() => navigate('emergency')} style={{
          width: '100%', textAlign: 'left',
          padding: 16, borderRadius: 18,
          background: 'linear-gradient(120deg, #FCEEEC, var(--hg-surface))',
          border: '1px solid rgba(194,85,74,0.24)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 40, height: 40, borderRadius: '50%',
            background: 'var(--hg-rose)', color: '#fff',
            display: 'grid', placeItems: 'center', flexShrink: 0,
            fontSize: 18, fontWeight: 700,
          }}>!</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 }}>병원·119 호출 화면으로</div>
          </div>
          <span style={{ color: 'var(--hg-rose)', fontSize: 16 }}>›</span>
        </button>
      </div>

      {/* 알림 임계값 설정 */}
      <div style={{ padding: '20px 22px 0' }}>
        <Eyebrow>활동 없음 알림 기준</Eyebrow>
        <Panel style={{ padding: 14 }}>
          <div style={{ fontSize: 12, color: 'var(--hg-muted)', fontWeight: 600, lineHeight: 1.6, marginBottom: 12 }}>
            설정한 시간 동안 앱 활동이 없으면 보호자 모드에서 알림이 켜져요.
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            {thresholds.map(h => (
              <button key={h} onClick={() => s.setSafety({ thresholdHours: h })} style={{
                flex: 1, padding: '10px 0', borderRadius: 12,
                background: threshold === h ? 'var(--hg-clay)' : 'var(--hg-bg-deeper)',
                color: threshold === h ? '#fff' : 'var(--hg-ink-2)',
                fontSize: 12, fontWeight: 700,
              }}>{h}시간</button>
            ))}
          </div>
        </Panel>
      </div>

      {/* 어떻게 작동하나요 */}
      <div style={{ padding: '16px 22px 24px' }}>
        <Panel style={{ padding: 16, background: 'var(--hg-bg-deeper)' }}>
          <Eyebrow color="var(--hg-muted)">어떻게 작동하나요</Eyebrow>
          <div style={{ fontSize: 12, color: 'var(--hg-ink-2)', lineHeight: 1.7, fontWeight: 500, marginTop: 4 }}>
            · 앱을 열거나 기록을 남기면 활동 시간이 갱신돼요.<br/>
            · 설정한 시간을 넘기면 보호자 모드 화면에 알림이 떠요.<br/>
            · '오늘 안전해요' 버튼은 명시적으로 안전을 확인하는 신호.<br/>
            · 위급할 때는 119 또는 병원으로 즉시.
          </div>
        </Panel>
      </div>
    </>
  );
}

// ════════════════════════════════════════════════════════════
// 동기 / 생일 / 메시지
// ════════════════════════════════════════════════════════════
function BuddiesScreen({ navigate, buddyId }) {
  if (buddyId) {
    const buddy = (useStore().buddies || []).find(b => b.id === buddyId);
    if (!buddy) return <BuddiesListScreen navigate={navigate} />;
    return <BuddyChatScreen navigate={navigate} buddy={buddy} />;
  }
  return <BuddiesListScreen navigate={navigate} />;
}

function BuddiesListScreen({ navigate }) {
  const s = useStore();
  const today = todayISO();
  const [openAdd, setOpenAdd] = React.useState(false);

  const buddies = s.buddies || [];
  // 생일 임박 정렬
  const withDays = buddies.map(b => ({ ...b, daysToBirthday: daysUntilBirthday(b.birthday, today) }));
  const upcoming = [...withDays].sort((a, b) => a.daysToBirthday - b.daysToBirthday);
  const todayBirthdays = upcoming.filter(b => b.daysToBirthday === 0);
  const within30 = upcoming.filter(b => b.daysToBirthday > 0 && b.daysToBirthday <= 30);
  const others = upcoming.filter(b => b.daysToBirthday > 30);

  // 내 생일까지
  const myDays = daysUntilBirthday(s.profile.birthday, today);

  // 마지막 메시지 (per buddy)
  const lastMsgOf = (id) => {
    const list = (s.buddyMsgs || []).filter(m => m.buddyId === id);
    return list.length ? list[list.length - 1] : null;
  };
  const unreadOf = (id) => {
    const list = (s.buddyMsgs || []).filter(m => m.buddyId === id);
    // 단순화: 마지막 메시지가 상대고 1시간 이내면 unread 처리
    const last = list[list.length - 1];
    if (last && last.from === 'them' && Date.now() - last.ts < 3_600_000) return true;
    return false;
  };

  return (
    <>
      <ScreenHeader
        title="동기와 생일"
        sub="같은 길의 친구들"
        back onBack={() => navigate('more')}
        action={<FAB onClick={() => setOpenAdd(true)} />}
      />

      {/* 오늘 생일 / 내 생일 */}
      <div style={{ padding: '6px 22px 0' }}>
        {todayBirthdays.length > 0 ? (
          <Panel style={{
            padding: 18,
            background: 'linear-gradient(135deg, var(--hg-honey-tint), var(--hg-clay-tint))',
            borderColor: 'var(--hg-honey-soft)',
          }}>
            <Eyebrow color="var(--hg-clay)">🎂 오늘은 생일</Eyebrow>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 8 }}>
              {todayBirthdays.map(b => (
                <button key={b.id} onClick={() => navigate(`buddies/${b.id}`)} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: 12, borderRadius: 12,
                  background: 'var(--hg-surface-2)',
                  border: '1px solid var(--hg-line-soft)',
                  textAlign: 'left',
                }}>
                  <Avatar value={b.avatar} size={44}/>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)' }}>{b.nick} 님</div>
                    <div style={{ fontSize: 11, color: 'var(--hg-clay-dark)', fontWeight: 700, marginTop: 2 }}>생신 축하 메시지 보내기 →</div>
                  </div>
                  <span style={{ fontSize: 18 }}>🎉</span>
                </button>
              ))}
            </div>
          </Panel>
        ) : (
          <Panel style={{ padding: 16, background: 'var(--hg-bg-deeper)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ fontSize: 26 }}>🎂</span>
              <div style={{ flex: 1 }}>
                <Eyebrow>내 생일까지</Eyebrow>
                <div className="hg-serif" style={{ fontSize: 18, fontWeight: 600, color: 'var(--hg-ink)', letterSpacing: '-0.02em' }}>
                  {myDays === 0 ? '오늘이에요!' : myDays === null ? '생일 미등록' : `${myDays}일 남음`}
                </div>
              </div>
              <button onClick={() => navigate('settings')} style={{ padding: '8px 12px', borderRadius: 10, background: 'var(--hg-surface)', border: '1px solid var(--hg-line)', fontSize: 11, fontWeight: 700, color: 'var(--hg-ink-2)' }}>
                {myDays === null ? '등록' : '수정'}
              </button>
            </div>
          </Panel>
        )}
      </div>

      {/* 30일 이내 다가오는 생일 */}
      {within30.length > 0 && (
        <div style={{ padding: '16px 22px 0' }}>
          <Eyebrow color="var(--hg-honey)">다가오는 생일</Eyebrow>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {within30.map(b => (
              <BuddyRow key={b.id} buddy={b} lastMsg={lastMsgOf(b.id)} unread={unreadOf(b.id)} navigate={navigate} highlight/>
            ))}
          </div>
        </div>
      )}

      {/* 모든 동기 */}
      <div style={{ padding: '16px 22px 0' }}>
        <Eyebrow>나의 동기 ({buddies.length})</Eyebrow>
        {buddies.length === 0 ? (
          <div style={{ padding: 24, textAlign: 'center', color: 'var(--hg-muted)', fontSize: 13, background: 'var(--hg-surface)', borderRadius: 16, border: '1px dashed var(--hg-line)' }}>
            아직 동기가 없어요.<br/>커뮤니티에서 마음 통하는 분을 동기로 등록해보세요.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[...todayBirthdays, ...others].map(b => (
              <BuddyRow key={b.id} buddy={b} lastMsg={lastMsgOf(b.id)} unread={unreadOf(b.id)} navigate={navigate}/>
            ))}
          </div>
        )}
      </div>

      <div style={{ padding: '16px 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',
        }}>
          데모 단계로 친구 답글은 AI가 따뜻하게 돌려드려요.<br/>
          실제 친구 연결은 서버가 필요합니다.
        </div>
      </div>

      {openAdd && <AddBuddySheet onClose={() => setOpenAdd(false)} onAdd={(b) => { s.addBuddy(b); showToast('동기로 등록됨'); setOpenAdd(false); }}/>}
    </>
  );
}

function BuddyRow({ buddy: b, lastMsg, unread, navigate, highlight }) {
  return (
    <button onClick={() => navigate(`buddies/${b.id}`)} style={{
      width: '100%', textAlign: 'left',
      display: 'flex', alignItems: 'center', gap: 12,
      padding: 14, borderRadius: 16,
      background: highlight ? 'var(--hg-honey-tint)' : 'var(--hg-surface)',
      border: '1px solid ' + (highlight ? 'var(--hg-honey-soft)' : 'var(--hg-line-soft)'),
    }}>
      <Avatar value={b.avatar} size={44}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
          <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)' }}>{b.nick}</span>
          <Chip bg={getStage(b.stage).bg} color={getStage(b.stage).color} style={{ fontSize: 9, padding: '2px 6px' }}>{getStage(b.stage).label}</Chip>
          {unread && <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--hg-rose)', marginLeft: 'auto' }}/>}
        </div>
        <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 500, lineHeight: 1.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {lastMsg ? lastMsg.body : `생일 ${b.birthday?.slice(5).replace('-','월 ')}일`}
        </div>
      </div>
      {b.daysToBirthday !== undefined && (
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div style={{ fontSize: 10, color: b.daysToBirthday === 0 ? 'var(--hg-rose)' : 'var(--hg-honey)', fontWeight: 700 }}>
            {b.daysToBirthday === 0 ? '🎂 오늘' : `🎂 D-${b.daysToBirthday}`}
          </div>
          {lastMsg && <div style={{ fontSize: 10, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 2 }}>{fmtRelative(lastMsg.ts)}</div>}
        </div>
      )}
    </button>
  );
}

function AddBuddySheet({ onClose, onAdd }) {
  const [form, setForm] = React.useState({ nick: '', avatar: '🌸', stage: 'II', birthday: '' });
  const emojis = ['🌸','🌿','☀️','🌙','☕','🤍','🌱','🌷','🍀','🦋','📚','🧸','🕊️','🌻','🍵','🌾'];

  return (
    <Sheet title="동기 등록" onClose={onClose}>
      <label className="hg-label">별칭</label>
      <input className="hg-input" placeholder="예: 봄을 기다리는" value={form.nick} onChange={(e) => setForm({ ...form, nick: e.target.value })}/>

      <label className="hg-label" style={{ marginTop: 14 }}>아바타</label>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {emojis.map(em => (
          <button key={em} onClick={() => setForm({ ...form, avatar: em })} style={{
            width: 42, height: 42, borderRadius: 12,
            background: form.avatar === em ? 'var(--hg-clay-tint)' : 'var(--hg-bg-deeper)',
            border: '1px solid ' + (form.avatar === em ? 'var(--hg-clay)' : 'var(--hg-line-soft)'),
            fontSize: 22, lineHeight: 1,
          }}>{em}</button>
        ))}
      </div>

      <label className="hg-label" style={{ marginTop: 14 }}>병기</label>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {STAGES.map(st => (
          <button key={st.id} onClick={() => setForm({ ...form, stage: st.id })} style={{
            flex: '1 1 auto', minWidth: 50, padding: '8px 0', borderRadius: 12,
            background: form.stage === st.id ? st.color : st.bg,
            color: form.stage === st.id ? '#fff' : st.color,
            fontSize: 12, fontWeight: 700,
          }}>{st.label}</button>
        ))}
      </div>

      <label className="hg-label" style={{ marginTop: 14 }}>생일</label>
      <input type="date" className="hg-input" value={form.birthday} onChange={(e) => setForm({ ...form, birthday: e.target.value })}/>

      <div style={{ marginTop: 18 }}>
        <PrimaryButton disabled={!form.nick} onClick={() => onAdd(form)}>저장</PrimaryButton>
      </div>
    </Sheet>
  );
}

// ════════════════════════════════════════════════════════════
// 동기 1:1 채팅 화면
// ════════════════════════════════════════════════════════════
function BuddyChatScreen({ navigate, buddy }) {
  const s = useStore();
  const messages = (s.buddyMsgs || []).filter(m => m.buddyId === buddy.id);
  const [draft, setDraft] = React.useState('');
  const [posting, setPosting] = React.useState(false);
  const stage = getStage(buddy.stage);
  const days = daysUntilBirthday(buddy.birthday);

  React.useEffect(() => {
    const root = document.querySelector('.hg-app__scroll');
    if (root) root.scrollTop = root.scrollHeight;
  }, [messages.length]);

  const send = async (preset) => {
    const text = (preset || draft).trim();
    if (!text || posting) return;
    setPosting(true);
    s.sendBuddyMsg(buddy.id, text);
    setDraft('');

    try {
      const recent = messages.slice(-4).map(m => `${m.from === 'me' ? '나' : buddy.nick}: ${m.body}`).join('\n');
      const isBirthday = days === 0;
      const prompt = `당신은 한국의 ${stage.fullLabel} 유방암 환자 동료 '${buddy.nick}'입니다. 익명 1:1 친구 채팅에 답합니다.

규칙:
- 1~2문장, 따뜻한 존댓말
- 의료 조언 금지 (필요시 "담당 의료진과 상의해 보세요")
- 친구처럼 자연스럽게 공감·짧은 경험 공유
- ${isBirthday ? '오늘이 본인의 생일임을 기억하세요. 축하받았다면 짧게 감사 인사.' : ''}
- 닉네임·인사말 없이 본문만

최근 대화:
${recent}
나: ${text}

답글:`;

      const reply = await window.claude.complete(prompt);
      setTimeout(() => { s.receiveBuddyMsg(buddy.id, reply.trim()); setPosting(false); }, 800);
    } catch (err) {
      console.error(err);
      setPosting(false);
    }
  };

  const presets = days === 0
    ? ['🎂 생신 축하드려요!', '오늘 좋은 하루 보내세요 💐']
    : ['오늘 컨디션 어떠세요?', '같이 화이팅해요 🌿', '잘 챙겨드세요'];

  return (
    <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <ScreenHeader
        title={buddy.nick}
        sub={`${stage.label} · ${buddy.lastSeen || '활동 정보 없음'}`}
        back onBack={() => navigate('buddies')}
        action={<Avatar value={buddy.avatar} size={40}/>}
      />

      {/* 생일 카드 */}
      {days !== null && days <= 30 && (
        <div style={{ padding: '6px 22px 0' }}>
          <div style={{
            padding: 14, borderRadius: 16,
            background: days === 0
              ? 'linear-gradient(135deg, var(--hg-honey-tint), var(--hg-clay-tint))'
              : 'var(--hg-honey-tint)',
            border: '1px solid var(--hg-honey-soft)',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <span style={{ fontSize: 26 }}>🎂</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)' }}>
                {days === 0 ? '오늘이 생신이에요!' : `생일까지 D-${days}`}
              </div>
              <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 2 }}>
                {buddy.birthday} · {buddy.birthday.slice(5).replace('-','월 ') + '일'}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 메시지 */}
      <div style={{ padding: '14px 16px 0', flex: 1 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {messages.length === 0 && (
            <div style={{ padding: 24, textAlign: 'center', color: 'var(--hg-muted)', fontSize: 12, background: 'var(--hg-surface)', borderRadius: 16, border: '1px dashed var(--hg-line)' }}>
              {buddy.nick}님과의 첫 메시지를 보내보세요
            </div>
          )}
          {messages.map(m => (
            <BuddyMessageBubble key={m.id} m={m} buddy={buddy} stage={stage}/>
          ))}
          {posting && (
            <div style={{ alignSelf: 'flex-start', display: 'flex', gap: 8, alignItems: 'flex-end' }}>
              <Avatar value={buddy.avatar} size={32}/>
              <div style={{
                padding: '12px 14px', borderRadius: 16, borderTopLeftRadius: 6,
                background: 'var(--hg-surface)',
                border: '1px solid var(--hg-line-soft)',
                display: 'flex', gap: 6,
              }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: stage.color, animation: 'hg-bounce 1.2s ease infinite' }}/>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: stage.color, animation: 'hg-bounce 1.2s ease 0.2s infinite' }}/>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: stage.color, animation: 'hg-bounce 1.2s ease 0.4s infinite' }}/>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 빠른 응원 */}
      <div style={{ padding: '14px 16px 0' }}>
        <div style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 4 }}>
          {presets.map((p, i) => (
            <button key={i} onClick={() => send(p)} style={{
              flexShrink: 0, padding: '8px 14px', borderRadius: 999,
              background: 'var(--hg-surface)', border: '1px solid var(--hg-line)',
              fontSize: 12, fontWeight: 700, color: 'var(--hg-ink-2)',
              whiteSpace: 'nowrap',
            }}>{p}</button>
          ))}
        </div>
      </div>

      {/* 입력창 */}
      <div style={{
        position: 'sticky', bottom: 0, left: 0, right: 0,
        padding: '12px 16px',
        paddingBottom: 'calc(20px + env(safe-area-inset-bottom))',
        background: 'rgba(251,246,236,0.94)',
        backdropFilter: 'blur(14px)',
        WebkitBackdropFilter: 'blur(14px)',
        borderTop: '1px solid var(--hg-line-soft)',
      }}>
        <div style={{
          display: 'flex', gap: 8, alignItems: 'flex-end',
          background: 'var(--hg-surface)',
          border: '1px solid var(--hg-line)',
          borderRadius: 22, padding: '6px 6px 6px 16px',
        }}>
          <textarea
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder="응원의 한마디를 보내보세요"
            rows={1}
            style={{
              flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontSize: 14, color: 'var(--hg-ink)', resize: 'none',
              fontFamily: 'inherit', lineHeight: 1.5,
              padding: '8px 0', minHeight: 24, maxHeight: 100,
            }}
            onInput={(e) => { e.target.style.height = 'auto'; e.target.style.height = Math.min(e.target.scrollHeight, 100) + 'px'; }}
          />
          <button onClick={() => send()} disabled={!draft.trim() || posting} style={{
            width: 38, height: 38, borderRadius: '50%',
            background: draft.trim() ? stage.color : 'var(--hg-line)',
            color: '#fff', flexShrink: 0,
            display: 'grid', placeItems: 'center',
            opacity: posting ? 0.5 : 1,
          }}>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M2 14L14 8 2 2v5l8 1-8 1v5z" fill="#fff"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}

function BuddyMessageBubble({ m, buddy, stage }) {
  const mine = m.from === 'me';
  return (
    <div style={{
      alignSelf: mine ? 'flex-end' : 'flex-start',
      maxWidth: '86%',
      display: 'flex', flexDirection: mine ? 'row-reverse' : 'row',
      alignItems: 'flex-end', gap: 8,
    }}>
      {!mine && <Avatar value={buddy.avatar} size={32}/>}
      <div style={{ minWidth: 0 }}>
        <div style={{
          padding: '12px 14px',
          borderRadius: 16,
          borderTopLeftRadius: mine ? 16 : 6,
          borderTopRightRadius: mine ? 6 : 16,
          background: mine ? stage.color : 'var(--hg-surface)',
          color: mine ? '#fff' : 'var(--hg-ink-2)',
          border: mine ? 'none' : '1px solid var(--hg-line-soft)',
          fontSize: 13, lineHeight: 1.6, fontWeight: 500,
          whiteSpace: 'pre-wrap',
        }}>{m.body}</div>
        <div style={{ marginTop: 4, marginLeft: mine ? 0 : 4, marginRight: mine ? 4 : 0, textAlign: mine ? 'right' : 'left' }}>
          <span style={{ fontSize: 10, color: 'var(--hg-muted)', fontWeight: 500 }}>{fmtRelative(m.ts)}</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SafetyScreen, BuddiesScreen, BuddiesListScreen, BuddyChatScreen, hoursSince, fmtRelative, daysUntilBirthday });
