// screens-chat.jsx — Group chat (opens only after approval)

function ChatScreen({ run, nav }) {
  const host = USERS[run.host];
  const messages = CHAT;
  const [draft, setDraft] = React.useState('');
  const [sheetUser, setSheetUser] = React.useState(null);
  const [blockStep, setBlockStep] = React.useState('profile'); // 'profile' | 'block' | 'done'
  const [blockReason, setBlockReason] = React.useState('');
  const [blockNote, setBlockNote] = React.useState('');

  const isHost = run.host === ME.id;

  const openSheet = (userKey) => {
    setSheetUser(USERS[userKey]);
    setBlockStep('profile');
    setBlockReason('');
    setBlockNote('');
  };
  const closeSheet = () => setSheetUser(null);
  const goBlock = () => setBlockStep('block');
  const confirmBlock = () => setBlockStep('done');

  const REASONS = [
    'Didn\'t show up',
    'Made me uncomfortable',
    'Abusive behaviour',
    'Other',
  ];

  return (
    <div style={{ background: PACER.bg, minHeight: '100%', color: PACER.text, fontFamily: PACER.font,
        display: 'flex', flexDirection: 'column' }}>

      {/* Header — single line with run summary */}
      <div style={{
        padding: `${SCREEN_TOP}px 14px 12px`,
        borderBottom: `1px solid ${PACER.border}`,
        background: PACER.bg,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <button onClick={() => nav('runDetail')} style={{
            width: 36, height: 36, borderRadius: 10,
            background: 'transparent', border: 'none',
            color: PACER.text, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>
            <Icon name="chevL" size={22} color={PACER.text}/>
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: -6, marginRight: 4 }}>
            {run.joined.slice(0, 3).map((u, i) => (
              <div key={u} style={{ marginLeft: i === 0 ? 0 : -8, border: `2px solid ${PACER.bg}`, borderRadius: '50%' }}>
                <Avatar name={USERS[u].name} size={28}/>
              </div>
            ))}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: PACER.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {run.title}
            </div>
            <div style={{ fontFamily: PACER.mono, fontSize: 11, color: PACER.textDim, marginTop: 1 }}>
              {run.dateLong} · {run.area}
            </div>
          </div>
          <button style={{
            width: 36, height: 36, borderRadius: 10,
            background: 'transparent', border: 'none', color: PACER.textDim,
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="dots" size={20} color={PACER.textDim}/>
          </button>
        </div>
      </div>

      {/* Closing-soon banner */}
      <div style={{
        margin: '12px 16px 0', padding: '8px 12px',
        background: 'rgba(255,255,255,0.025)', border: `1px solid ${PACER.border}`,
        borderRadius: 10, display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <Icon name="clock" size={13} color={PACER.textMute}/>
        <span style={{ fontSize: 11.5, color: PACER.textMute }}>
          Chat closes 12 hours after the run · Only members of this run can message here.
        </span>
      </div>

      {/* Messages */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 14px 12px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {messages.map((m, i) => {
          if (m.system) {
            return (
              <div key={m.id} style={{
                textAlign: 'center', fontSize: 11.5, color: PACER.textMute,
                padding: '6px 16px', fontFamily: PACER.font,
              }}>
                {m.text}
              </div>
            );
          }
          const isMe = m.from === 'me';
          const user = isMe ? { name: 'You', firstName: 'You' } : USERS[m.from];
          const prev = messages[i - 1];
          const showAvatar = !isMe && (!prev || prev.from !== m.from || prev.system);
          return (
            <div key={m.id} style={{
              display: 'flex', justifyContent: isMe ? 'flex-end' : 'flex-start',
              gap: 8, alignItems: 'flex-end',
            }}>
              {!isMe && (
                <div onClick={() => openSheet(m.from)}
                  style={{ width: 28, visibility: showAvatar ? 'visible' : 'hidden', cursor: 'pointer' }}>
                  <Avatar name={user.name} size={28}/>
                </div>
              )}
              <div style={{ maxWidth: '75%' }}>
                {showAvatar && !isMe && (
                  <div onClick={() => openSheet(m.from)} style={{
                    fontSize: 11, color: PACER.textDim, fontWeight: 500,
                    marginBottom: 3, marginLeft: 4, cursor: 'pointer',
                  }}>{user.name.split(' ')[0]}</div>
                )}
                <div style={{
                  padding: '9px 13px',
                  background: isMe ? PACER.lime : PACER.card,
                  color: isMe ? PACER.limeInk : PACER.text,
                  borderRadius: 16,
                  borderBottomRightRadius: isMe ? 4 : 16,
                  borderBottomLeftRadius: isMe ? 16 : 4,
                  border: isMe ? 'none' : `1px solid ${PACER.border}`,
                  fontSize: 14.5, lineHeight: 1.4, fontWeight: isMe ? 500 : 400,
                }}>
                  {m.text}
                </div>
                <div style={{
                  fontFamily: PACER.mono, fontSize: 10, color: PACER.textSubtle,
                  marginTop: 3, textAlign: isMe ? 'right' : 'left',
                  paddingLeft: isMe ? 0 : 4, paddingRight: isMe ? 4 : 0,
                }}>{m.time}</div>
              </div>
            </div>
          );
        })}

        {/* System reminder */}
        <div style={{
          alignSelf: 'center', margin: '8px 0',
          padding: '8px 14px',
          background: PACER.limeSoft, border: `1px solid ${PACER.limeBorder}`,
          borderRadius: 99,
          fontSize: 11.5, color: PACER.lime, fontWeight: 500,
          display: 'flex', alignItems: 'center', gap: 6,
        }}>
          <Icon name="bolt" size={11} color={PACER.lime}/>
          Run starts in 4 hours · meet at the bandstand
        </div>
      </div>

      {/* Composer */}
      <div style={{
        padding: '10px 14px 30px',
        borderTop: `1px solid ${PACER.border}`,
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <input
          value={draft}
          onChange={e => setDraft(e.target.value)}
          placeholder="Message the group…"
          style={{
            flex: 1, height: 42, padding: '0 16px',
            background: PACER.inset, border: `1px solid ${PACER.border}`,
            borderRadius: 99, color: PACER.text, fontFamily: PACER.font, fontSize: 14,
            outline: 'none',
          }}
        />
        <button onClick={() => setDraft('')} style={{
          width: 42, height: 42, borderRadius: '50%',
          background: draft.trim() ? PACER.lime : 'rgba(255,255,255,0.05)',
          border: 'none', color: draft.trim() ? PACER.limeInk : PACER.textSubtle,
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'all .15s',
        }}>
          <Icon name="send" size={18} color={draft.trim() ? PACER.limeInk : PACER.textSubtle}/>
        </button>
      </div>

      {/* Profile sheet + block flow overlay */}
      {sheetUser && blockStep === 'profile' && (
        <OtherProfileSheet
          user={sheetUser}
          isHost={isHost}
          onClose={closeSheet}
          onReportBlock={goBlock}
        />
      )}

      {sheetUser && blockStep === 'block' && (() => {
        const firstName = sheetUser.name.split(' ')[0];
        return (
          <div style={{
            position: 'absolute', inset: 0, zIndex: 20,
            fontFamily: PACER.font, color: PACER.text,
          }}>
            <div onClick={closeSheet} style={{
              position: 'absolute', inset: 0,
              background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(8px)',
              WebkitBackdropFilter: 'blur(8px)',
            }}/>
            <div style={{
              position: 'absolute', bottom: 0, left: 0, right: 0,
              background: PACER.bg, borderTopLeftRadius: 26, borderTopRightRadius: 26,
              boxShadow: '0 -20px 60px rgba(0,0,0,0.6)',
              borderTop: `1px solid ${PACER.borderStrong}`,
              padding: '14px 20px 34px',
              maxHeight: '88%', overflowY: 'auto',
            }}>
              <div onClick={closeSheet} style={{
                width: 40, height: 4, borderRadius: 99, background: PACER.borderStrong,
                margin: '0 auto 20px', cursor: 'pointer',
              }}/>

              <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: -0.5, marginBottom: 6 }}>
                Block {firstName}?
              </div>

              {/* Consequence callout */}
              <div style={{
                padding: '12px 14px', borderRadius: 14, marginBottom: 20,
                background: 'rgba(255,95,95,0.07)',
                border: '1px solid rgba(255,95,95,0.2)',
                fontSize: 13, color: '#ff9a9a', lineHeight: 1.55,
              }}>
                {firstName} will be removed from all runs you host and won't be able to contact you or request to join your future runs.
              </div>

              {/* Reason chips */}
              <div style={{
                fontSize: 11, fontWeight: 600, color: PACER.textMute,
                textTransform: 'uppercase', letterSpacing: 1.4, marginBottom: 10,
              }}>What happened?</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 14 }}>
                {REASONS.map(r => (
                  <button key={r} onClick={() => setBlockReason(r === blockReason ? '' : r)} style={{
                    padding: '8px 13px', borderRadius: 99,
                    background: blockReason === r ? 'rgba(255,95,95,0.12)' : 'transparent',
                    border: `1px solid ${blockReason === r ? 'rgba(255,95,95,0.4)' : PACER.border}`,
                    color: blockReason === r ? '#ff9a9a' : PACER.textDim,
                    fontFamily: PACER.font, fontSize: 13, cursor: 'pointer',
                    transition: 'all .12s',
                  }}>{r}</button>
                ))}
              </div>

              {/* Optional note */}
              <textarea
                value={blockNote}
                onChange={e => setBlockNote(e.target.value)}
                placeholder="Add more detail (optional)…"
                style={{
                  width: '100%', boxSizing: 'border-box', minHeight: 90,
                  background: PACER.inset, border: `1px solid ${PACER.border}`,
                  borderRadius: 14, padding: '12px 14px', marginBottom: 16,
                  color: PACER.text, fontFamily: PACER.font, fontSize: 14, lineHeight: 1.5,
                  outline: 'none', resize: 'none',
                }}
              />

              {/* CTAs */}
              <button onClick={confirmBlock} style={{
                width: '100%', padding: '15px', borderRadius: 14, border: 'none',
                background: 'rgba(255,95,95,0.15)', color: '#ff7a7a',
                fontFamily: PACER.font, fontSize: 15, fontWeight: 600, cursor: 'pointer',
                marginBottom: 12,
              }}>
                Block and remove {firstName}
              </button>
              <button onClick={confirmBlock} style={{
                width: '100%', padding: '10px', borderRadius: 14, border: 'none',
                background: 'transparent', color: PACER.textMute,
                fontFamily: PACER.font, fontSize: 13, cursor: 'pointer',
              }}>
                Just report without blocking
              </button>
            </div>
          </div>
        );
      })()}

      {sheetUser && blockStep === 'done' && (() => {
        const firstName = sheetUser.name.split(' ')[0];
        return (
          <div style={{
            position: 'absolute', inset: 0, zIndex: 20,
            fontFamily: PACER.font, color: PACER.text,
          }}>
            <div onClick={closeSheet} style={{
              position: 'absolute', inset: 0,
              background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(8px)',
              WebkitBackdropFilter: 'blur(8px)',
            }}/>
            <div style={{
              position: 'absolute', bottom: 0, left: 0, right: 0,
              background: PACER.bg, borderTopLeftRadius: 26, borderTopRightRadius: 26,
              boxShadow: '0 -20px 60px rgba(0,0,0,0.6)',
              borderTop: `1px solid ${PACER.borderStrong}`,
              padding: '32px 24px 40px',
              display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
            }}>
              <div style={{
                width: 56, height: 56, borderRadius: '50%',
                background: 'rgba(255,95,95,0.12)', border: '1px solid rgba(255,95,95,0.25)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                marginBottom: 16,
              }}>
                <Icon name="check" size={24} color="#ff7a7a"/>
              </div>
              <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: -0.4, marginBottom: 8 }}>
                {isHost ? `${firstName} removed` : `${firstName} blocked`}
              </div>
              <div style={{ fontSize: 14, color: PACER.textDim, lineHeight: 1.55, marginBottom: 28, maxWidth: 280 }}>
                {isHost
                  ? `${firstName} has been removed from this run and blocked from your future runs.`
                  : `${firstName} has been blocked and reported. You won't hear from them again.`
                }
              </div>
              <button onClick={closeSheet} style={{
                padding: '13px 32px', borderRadius: 14, border: 'none',
                background: PACER.card, color: PACER.text,
                fontFamily: PACER.font, fontSize: 15, fontWeight: 500, cursor: 'pointer',
              }}>
                Done
              </button>
            </div>
          </div>
        );
      })()}
    </div>
  );
}

const BLOCK_REASONS = ['Didn\'t show up', 'Made me uncomfortable', 'Abusive behaviour', 'Other'];

function BlockReportSheet({ user, isHost = false }) {
  const firstName = user.name.split(' ')[0];
  const [reason, setReason] = React.useState('Made me uncomfortable');
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 20, fontFamily: PACER.font, color: PACER.text }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
      }}/>
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        background: PACER.bg, borderTopLeftRadius: 26, borderTopRightRadius: 26,
        boxShadow: '0 -20px 60px rgba(0,0,0,0.6)',
        borderTop: `1px solid ${PACER.borderStrong}`,
        padding: '14px 20px 34px',
        maxHeight: '88%', overflowY: 'auto',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 99, background: PACER.borderStrong, margin: '0 auto 20px' }}/>
        <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: -0.5, marginBottom: 6 }}>
          Block {firstName}?
        </div>
        <div style={{
          padding: '12px 14px', borderRadius: 14, marginBottom: 20,
          background: 'rgba(255,95,95,0.07)',
          border: '1px solid rgba(255,95,95,0.2)',
          fontSize: 13, color: '#ff9a9a', lineHeight: 1.55,
        }}>
          {firstName} will be removed from all runs you host and won't be able to contact you or request to join your future runs.
        </div>
        <div style={{ fontSize: 11, fontWeight: 600, color: PACER.textMute, textTransform: 'uppercase', letterSpacing: 1.4, marginBottom: 10 }}>
          What happened?
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 14 }}>
          {BLOCK_REASONS.map(r => (
            <button key={r} onClick={() => setReason(r === reason ? '' : r)} style={{
              padding: '8px 13px', borderRadius: 99,
              background: reason === r ? 'rgba(255,95,95,0.12)' : 'transparent',
              border: `1px solid ${reason === r ? 'rgba(255,95,95,0.4)' : PACER.border}`,
              color: reason === r ? '#ff9a9a' : PACER.textDim,
              fontFamily: PACER.font, fontSize: 13, cursor: 'pointer',
            }}>{r}</button>
          ))}
        </div>
        <textarea placeholder="Add more detail (optional)…" style={{
          width: '100%', boxSizing: 'border-box', minHeight: 90,
          background: PACER.inset, border: `1px solid ${PACER.border}`,
          borderRadius: 14, padding: '12px 14px', marginBottom: 16,
          color: PACER.text, fontFamily: PACER.font, fontSize: 14, lineHeight: 1.5,
          outline: 'none', resize: 'none',
        }}/>
        <button style={{
          width: '100%', padding: '15px', borderRadius: 14, border: 'none',
          background: 'rgba(255,95,95,0.15)', color: '#ff7a7a',
          fontFamily: PACER.font, fontSize: 15, fontWeight: 600, cursor: 'pointer', marginBottom: 12,
        }}>
          Block and remove {firstName}
        </button>
        <button style={{
          width: '100%', padding: '10px', borderRadius: 14, border: 'none',
          background: 'transparent', color: PACER.textMute,
          fontFamily: PACER.font, fontSize: 13, cursor: 'pointer',
        }}>
          Just report without blocking
        </button>
      </div>
    </div>
  );
}

function BlockDoneSheet({ user, isHost = false }) {
  const firstName = user.name.split(' ')[0];
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 20, fontFamily: PACER.font, color: PACER.text }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
      }}/>
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        background: PACER.bg, borderTopLeftRadius: 26, borderTopRightRadius: 26,
        boxShadow: '0 -20px 60px rgba(0,0,0,0.6)',
        borderTop: `1px solid ${PACER.borderStrong}`,
        padding: '32px 24px 40px',
        display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: '50%',
          background: 'rgba(255,95,95,0.12)', border: '1px solid rgba(255,95,95,0.25)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16,
        }}>
          <Icon name="check" size={24} color="#ff7a7a"/>
        </div>
        <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: -0.4, marginBottom: 8 }}>
          {isHost ? `${firstName} removed` : `${firstName} blocked`}
        </div>
        <div style={{ fontSize: 14, color: PACER.textDim, lineHeight: 1.55, marginBottom: 28, maxWidth: 280 }}>
          {isHost
            ? `${firstName} has been removed from this run and blocked from your future runs.`
            : `${firstName} has been blocked and reported. You won't hear from them again.`
          }
        </div>
        <button style={{
          padding: '13px 32px', borderRadius: 14, border: 'none',
          background: PACER.card, color: PACER.text,
          fontFamily: PACER.font, fontSize: 15, fontWeight: 500, cursor: 'pointer',
        }}>Done</button>
      </div>
    </div>
  );
}

Object.assign(window, { ChatScreen, BlockReportSheet, BlockDoneSheet });
