// supervise.jsx — Supervision + messages screen (perspective-aware bubbles)
function SuperviseScreen() {
  const T = useTheme();
  const app = useApp();
  const { A, B, names, goal, messages, sendMessage, poke, like, role } = app;
  const [draft, setDraft] = React.useState('');
  const scrollRef = React.useRef(null);
  const bPct = Math.round(((B.start - B.cur) / (B.start - goal.B)) * 100);
  const card = { background: T.card, borderRadius: T.r, boxShadow: T.shadow };
  const quick = ['今天也要加油呀 💪', '坚持住，你超棒！', '晚上一起散步？🚶', '少吃一口，瘦一斤 😆'];

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages.length]);

  const send = (text) => { if (!text.trim()) return; sendMessage(text.trim()); setDraft(''); };

  return (
    <>
      <PageTitle title="互相监督" sub={`和 ${names.B} 一起，彼此见证`} />
      <div ref={scrollRef} style={{ flex: 1, overflow: 'auto', padding: '8px 20px 14px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {/* partner card */}
        <div style={{ ...card, padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ position: 'relative', flexShrink: 0 }}>
              <Avatar who="B" size={56} ring />
              <div style={{ position: 'absolute', bottom: 0, right: 0, width: 16, height: 16, borderRadius: '50%', background: B.checkedToday ? T.good : T.faint, border: `2.5px solid ${T.card}` }} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 17, fontWeight: 700, color: T.ink }}>{names.B}</div>
              <div style={{ fontSize: 12.5, color: T.sub, marginTop: 2 }}>{B.checkedToday ? '今天已打卡 ✓' : '今天还没打卡'} · 连续 {B.streak} 天</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, color: T.Bd, whiteSpace: 'nowrap' }}>
              <Flame size={16} color={T.Bc} /><span style={{ fontFamily: T.NUM, fontWeight: 800, fontSize: 18 }}>{B.streak}</span>
            </div>
          </div>
          {/* B stats */}
          <div style={{ display: 'flex', marginTop: 16, background: T.bg2, borderRadius: T.rSm, padding: '12px 0' }}>
            {[['当前', `${B.cur}`, 'kg'], ['距目标', `${(B.cur-goal.B).toFixed(1)}`, 'kg'], ['本周', `-${B.weekLoss}`, 'kg'], ['完成', `${bPct}`, '%']].map((s, i) => (
              <div key={i} style={{ flex: 1, textAlign: 'center', borderLeft: i ? `1px solid ${T.line}` : 'none' }}>
                <div style={{ fontFamily: T.NUM, fontSize: 18, fontWeight: 800, color: i===2?T.good:T.ink }}>{s[1]}<span style={{ fontSize: 11 }}>{s[2]}</span></div>
                <div style={{ fontSize: 10.5, color: T.faint, marginTop: 1 }}>{s[0]}</div>
              </div>
            ))}
          </div>
          {/* B sparkline */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 14 }}>
            <span style={{ fontSize: 12, color: T.sub, fontWeight: 600, whiteSpace: 'nowrap' }}>近 7 天</span>
            <div style={{ flex: 1 }}><Sparkline data={B.series.slice(-7)} who="B" w={180} h={42} /></div>
          </div>
          {/* actions */}
          <div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
            <button onClick={() => like('B')} style={{ flex: 1, height: 42, borderRadius: T.rSm, border: `1.5px solid ${app.liked?T.Bc:T.line}`, background: app.liked?T.Bs:T.card, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, fontFamily: T.FONT, fontWeight: 700, fontSize: 14, color: T.Bd }}>
              <Heart size={18} filled={app.liked} />点赞 TA
            </button>
            <button onClick={() => poke('B')} style={{ flex: 1, height: 42, borderRadius: T.rSm, border: 'none', background: `linear-gradient(135deg, ${T.Bc}, ${T.Bd})`, color: '#fff', cursor: 'pointer', fontFamily: T.FONT, fontWeight: 700, fontSize: 14 }}>
              {B.checkedToday ? '夸夸 TA 👍' : '催 TA 打卡 👀'}
            </button>
          </div>
        </div>

        {/* messages */}
        <div style={{ fontSize: 12.5, fontWeight: 700, color: T.sub, letterSpacing: 1, padding: '0 2px' }}>留言板</div>
        {messages.length === 0 && <div style={{ fontSize: 13, color: T.faint, padding: '4px 2px' }}>还没有留言，给 {names.B} 发一条吧 👇</div>}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {messages.map((m, i) => {
            const mine = m.from === role;            // perspective: my own messages on the right
            const slot = mine ? 'A' : 'B';           // color slot: me = A-color, partner = B-color
            return (
              <div key={i} style={{ display: 'flex', flexDirection: mine ? 'row-reverse' : 'row', gap: 9, alignItems: 'flex-end' }}>
                <Avatar who={slot} size={32} />
                <div style={{ maxWidth: '74%' }}>
                  <div style={{ background: mine ? `linear-gradient(135deg, ${T.Ac}, ${T.Ad})` : T.card, color: mine ? '#fff' : T.ink, padding: '10px 14px', borderRadius: mine ? `${T.rSm}px ${T.rSm}px 4px ${T.rSm}px` : `4px ${T.rSm}px ${T.rSm}px ${T.rSm}px`, fontSize: 14.5, lineHeight: 1.45, boxShadow: T.shadow }}>{m.text}</div>
                  <div style={{ fontSize: 10.5, color: T.faint, marginTop: 4, textAlign: mine ? 'right' : 'left' }}>{m.time}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* composer */}
      <div style={{ flexShrink: 0, borderTop: `1px solid ${T.line}`, background: T.card, padding: '10px 16px 12px' }}>
        <div style={{ display: 'flex', gap: 7, marginBottom: 9, overflowX: 'auto', paddingBottom: 2 }}>
          {quick.map((q, i) => (
            <button key={i} onClick={() => send(q)} style={{ flexShrink: 0, border: `1px solid ${T.line}`, background: T.bg2, color: T.sub, borderRadius: 999, padding: '6px 12px', fontFamily: T.FONT, fontSize: 12.5, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' }}>{q}</button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 9, alignItems: 'center' }}>
          <input value={draft} onChange={(e) => setDraft(e.target.value)} onKeyDown={(e) => { if (e.key==='Enter') send(draft); }} placeholder={`给 ${names.B} 留言…`} style={{ flex: 1, height: 42, borderRadius: 999, border: `1.5px solid ${T.line}`, background: T.bg, padding: '0 16px', fontFamily: T.FONT, fontSize: 14, color: T.ink, outline: 'none' }} />
          <button onClick={() => send(draft)} style={{ width: 42, height: 42, borderRadius: '50%', border: 'none', background: draft.trim() ? `linear-gradient(135deg, ${T.Ac}, ${T.Ad})` : T.line, cursor: draft.trim() ? 'pointer' : 'default', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <svg width="20" height="20" viewBox="0 0 24 24"><path d="M4 12l16-8-6 16-3-7-7-1z" fill="#fff"/></svg>
          </button>
        </div>
      </div>
    </>
  );
}
window.SuperviseScreen = SuperviseScreen;
