// 하루결 — 커뮤니티 채팅방 (기수별, 환자/보호자 분리)

function CommunityScreen({ navigate, roomId }) {
  if (roomId) {
    return <CommunityRoomScreen navigate={navigate} roomId={roomId} />;
  }
  return <CommunityListScreen navigate={navigate} />;
}

function CommunityListScreen({ navigate }) {
  const s = useStore();
  const mode = s.mode; // patient | caregiver
  const myStage = s.profile.stage || 'I';

  return (
    <>
      <ScreenHeader
        title="같은 길의 동료들"
        sub={mode === 'caregiver' ? '같은 기수 보호자 모임' : '같은 기수 환자 모임'}
        back onBack={() => navigate('more')}
      />

      {/* 데모 안내 */}
      <div style={{ padding: '6px 22px 0' }}>
        <Panel style={{ padding: 14, background: 'var(--hg-mist-tint)', borderColor: 'var(--hg-mist-soft)' }}>
          <div style={{ display: 'flex', gap: 10 }}>
            <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--hg-mist)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700, flexShrink: 0 }}>i</span>
            <div style={{ fontSize: 11, color: 'var(--hg-ink-2)', fontWeight: 500, lineHeight: 1.6 }}>
              같은 기수 동료들이 익명으로 만나는 공간입니다.<br/>
              <span style={{ color: 'var(--hg-muted)' }}>현재 데모 단계로, 실제 연결되려면 서버가 필요해요. AI 동료가 응답해드립니다.</span>
            </div>
          </div>
        </Panel>
      </div>

      {/* 내 방 강조 */}
      <div style={{ padding: '14px 22px 0' }}>
        <Eyebrow>내 기수 방</Eyebrow>
        <CommunityRoomCard
          stage={getStage(myStage)}
          mode={mode}
          highlighted
          onClick={() => navigate(`community/${getRoomId(myStage, mode)}`)}
        />
      </div>

      {/* 다른 기수 방 */}
      <div style={{ padding: '16px 22px 0' }}>
        <Eyebrow color="var(--hg-muted)">다른 기수도 둘러보기</Eyebrow>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {STAGES.filter(st => st.id !== myStage).map(st => (
            <CommunityRoomCard
              key={st.id}
              stage={st}
              mode={mode}
              onClick={() => navigate(`community/${getRoomId(st.id, mode)}`)}
            />
          ))}
        </div>
      </div>

      {/* 가이드라인 */}
      <div style={{ padding: '20px 22px 24px' }}>
        <Eyebrow>커뮤니티 가이드</Eyebrow>
        <Panel style={{ padding: 16, background: 'var(--hg-bg-deeper)' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 12, color: 'var(--hg-ink-2)', fontWeight: 500, lineHeight: 1.6 }}>
            <div>· 서로의 경험을 존중하고 따뜻한 말로 응원해요.</div>
            <div>· 의학적 결정은 자신의 담당 의료진과 상의하세요.</div>
            <div>· 약·민간요법을 단정적으로 권하지 않습니다.</div>
            <div>· 익명이지만 사적인 정보는 공유하지 마세요.</div>
          </div>
        </Panel>
      </div>
    </>
  );
}

function CommunityRoomCard({ stage, mode, highlighted, onClick }) {
  const s = useStore();
  const roomId = getRoomId(stage.id, mode);
  const myPosts = (s.community || []).filter(p => p.roomId === roomId);
  const seedCount = getRoomSeed(stage.id, mode).length;
  const total = seedCount + myPosts.length;

  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left',
      padding: 16, borderRadius: 18,
      background: highlighted
        ? `linear-gradient(135deg, ${stage.bg}, var(--hg-surface) 130%)`
        : 'var(--hg-surface)',
      border: highlighted ? `1px solid ${stage.color}33` : '1px solid var(--hg-line-soft)',
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{
        width: 48, height: 48, borderRadius: 14,
        background: stage.color, color: '#fff',
        display: 'grid', placeItems: 'center', flexShrink: 0,
        fontFamily: '"Noto Serif KR", serif', fontSize: 18, fontWeight: 600,
      }}>{stage.label}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)' }}>
          {stage.fullLabel}
        </div>
        <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 500, marginTop: 4, lineHeight: 1.5, overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
          {stage.short}
        </div>
        <div style={{ fontSize: 10, color: stage.color, fontWeight: 700, marginTop: 6 }}>
          글 {total}개 {highlighted && '· 내 기수'}
        </div>
      </div>
      <span style={{ color: 'var(--hg-muted)', fontSize: 16, flexShrink: 0 }}>›</span>
    </button>
  );
}

// ──────────────────────────────────────────────────────────
// 방 상세
// ──────────────────────────────────────────────────────────
function CommunityRoomScreen({ navigate, roomId }) {
  const s = useStore();
  const [stage, mode] = parseRoomId(roomId);
  const stageInfo = getStage(stage);

  // 내가 저장한 글들과 시드 합치기
  const seedMessages = getRoomSeed(stage, mode).map((m, i) => ({
    ...m, id: 'seed-' + i, isMine: false, isAI: false,
  }));
  const myMessages = (s.community || []).filter(p => p.roomId === roomId);
  const all = [...seedMessages, ...myMessages.map(m => ({ ...m, isMine: !m.isAI }))];

  const [draft, setDraft] = React.useState('');
  const [posting, setPosting] = React.useState(false);
  const scrollRef = React.useRef(null);
  const myNick = s.profile.chatNick || pickNickname(mode);
  const myAvatar = s.profile.chatAvatar || '🌸';

  // 최신글 위치로
  React.useEffect(() => {
    const root = document.querySelector('.hg-app__scroll');
    if (root) root.scrollTop = root.scrollHeight;
  }, [all.length]);

  const post = async () => {
    if (!draft.trim() || posting) return;
    setPosting(true);
    const text = draft.trim();
    setDraft('');

    const myMsg = {
      id: 'my-' + Date.now(),
      roomId,
      nick: myNick,
      avatar: myAvatar,
      body: text,
      ago: '방금',
      ts: Date.now(),
    };
    const next = [...(s.community || []), myMsg];
    Store.save(K.community, next);

    // AI 동료 답글
    try {
      const recentContext = all.slice(-4).map(m => `${m.nick}: ${m.body}`).join('\n');
      const prompt = `당신은 한국의 ${stageInfo.fullLabel} ${mode === 'caregiver' ? '보호자' : '환자'} 익명 커뮤니티의 동료입니다. 같은 처지의 사람으로서 짧고 따뜻하게 응답하세요.

규칙:
- 1~3문장, 한국어 반말 아닌 부드러운 존댓말
- 의료 조언이나 약 권유 금지 ("담당 의료진과 상의하세요" 같은 안전 문구 포함 권장)
- 자기 경험을 짧게 공유하거나, 공감하거나, 작은 팁 제공
- 친구처럼 자연스럽게
- 닉네임이나 인사 말머리 없이 바로 본문만

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

답글:`;

      const reply = await window.claude.complete(prompt);
      const aiMsg = {
        id: 'ai-' + Date.now(),
        roomId,
        nick: pickNickname(mode),
        body: reply.trim(),
        ago: '방금',
        ts: Date.now() + 1,
        isAI: true,
      };
      Store.save(K.community, [...Store.load(K.community, []), aiMsg]);
    } catch (err) {
      console.error('AI reply failed', err);
    } finally {
      setPosting(false);
    }
  };

  return (
    <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <ScreenHeader
        title={stageInfo.fullLabel.replace(/^\S+\s—\s/, '')}
        sub={`${stageInfo.label} · ${mode === 'caregiver' ? '보호자' : '환자'} 방`}
        back onBack={() => navigate('community')}
        action={
          <span style={{
            padding: '6px 10px', borderRadius: 999,
            background: stageInfo.bg, color: stageInfo.color,
            fontSize: 11, fontWeight: 700,
          }}>{stageInfo.label}</span>
        }
      />

      {/* 안내 배너 */}
      <div style={{ padding: '6px 22px 0' }}>
        <div style={{
          padding: 12, borderRadius: 14,
          background: 'var(--hg-mist-tint)',
          border: '1px dashed var(--hg-mist-soft)',
          fontSize: 11, color: 'var(--hg-ink-2)', fontWeight: 500, lineHeight: 1.5, textAlign: 'center',
        }}>
          익명으로 만나는 곳. 의학 판단은 담당 의료진과.
        </div>
      </div>

      {/* 메시지 */}
      <div style={{ padding: '14px 16px 0', flex: 1 }}>
        <div ref={scrollRef} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {all.map((m) => (
            <MessageBubble key={m.id} m={m} stage={stageInfo} myNick={myNick}/>
          ))}
          {posting && (
            <div style={{ alignSelf: 'flex-start', maxWidth: '80%' }}>
              <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600, marginBottom: 4, marginLeft: 4 }}>
                동료가 답글 작성중...
              </div>
              <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: stageInfo.color, animation: 'hg-bounce 1.2s ease infinite' }}/>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: stageInfo.color, animation: 'hg-bounce 1.2s ease 0.2s infinite' }}/>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: stageInfo.color, animation: 'hg-bounce 1.2s ease 0.4s infinite' }}/>
              </div>
            </div>
          )}
        </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={post} disabled={!draft.trim() || posting} style={{
            width: 38, height: 38, borderRadius: '50%',
            background: draft.trim() ? stageInfo.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 style={{ marginTop: 6, fontSize: 10, color: 'var(--hg-muted)', textAlign: 'center', fontWeight: 600, display: 'inline-flex', justifyContent: 'center', alignItems: 'center', gap: 6, width: '100%' }}>
          <Avatar value={myAvatar} size={18}/>
          <span>{myNick}으로 표시 · <button onClick={() => { window.location.hash = 'settings'; }} style={{ color: 'var(--hg-clay)', fontWeight: 700 }}>변경</button></span>
        </div>
      </div>

      <style>{`
        @keyframes hg-bounce {
          0%, 100% { transform: translateY(0); opacity: 0.4; }
          50% { transform: translateY(-4px); opacity: 1; }
        }
      `}</style>
    </div>
  );
}

function MessageBubble({ m, stage, myNick }) {
  const mine = m.isMine || m.nick === myNick || m.nick === '나';
  const avatar = m.avatar || nickToEmoji(m.nick);
  return (
    <div style={{
      alignSelf: mine ? 'flex-end' : 'flex-start',
      maxWidth: '86%',
      display: 'flex', flexDirection: mine ? 'row-reverse' : 'row',
      alignItems: 'flex-end', gap: 8,
    }}>
      <Avatar value={avatar} size={32}/>
      <div style={{ minWidth: 0 }}>
        {!mine && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4, marginLeft: 4 }}>
            <span style={{ fontSize: 11, color: 'var(--hg-ink-2)', fontWeight: 700 }}>{m.nick}</span>
            {m.isAI && <Chip bg="var(--hg-mist-tint)" color="var(--hg-mist)" style={{ padding: '1px 7px', fontSize: 9 }}>AI 동료</Chip>}
            <span style={{ fontSize: 10, color: 'var(--hg-muted)', fontWeight: 500 }}>{m.ago}</span>
          </div>
        )}
        <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>
        {mine && (
          <div style={{ marginTop: 4, marginRight: 4, textAlign: 'right' }}>
            <span style={{ fontSize: 10, color: 'var(--hg-muted)', fontWeight: 500 }}>{m.ago || '방금'}</span>
          </div>
        )}
      </div>
    </div>
  );
}

function Avatar({ value, size = 32 }) {
  const isPhoto = value && typeof value === 'string' && value.startsWith('data:');
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: isPhoto ? '#000' : 'var(--hg-bg-deeper)',
      backgroundImage: isPhoto ? `url(${value})` : 'none',
      backgroundSize: 'cover', backgroundPosition: 'center',
      display: 'grid', placeItems: 'center',
      fontSize: size * 0.55, lineHeight: 1,
      border: '1px solid var(--hg-line-soft)',
      flexShrink: 0,
    }}>
      {!isPhoto && (value || '🌸')}
    </div>
  );
}

// 시드 닉네임 → 일관된 이모지
function nickToEmoji(nick) {
  const pool = ['🌸','🌿','☀️','🌙','☕','🤍','🌱','🌷','🍀','🦋','📚','🧸','🕊️','🌻','🍵','🌾'];
  if (!nick) return '🌸';
  let h = 0;
  for (let i = 0; i < nick.length; i++) h = (h * 31 + nick.charCodeAt(i)) >>> 0;
  return pool[h % pool.length];
}

function parseRoomId(id) {
  const idx = id.indexOf('-');
  return [id.slice(idx + 1), id.slice(0, idx)]; // [stage, mode]
}

Object.assign(window, { CommunityScreen, CommunityListScreen, CommunityRoomScreen, parseRoomId, Avatar, nickToEmoji });
