// Messages module — DMs between users + chat rooms for agenda events

const DM_THREADS = [
  {
    id: 'dm1', kind: 'dm',
    user: { name: 'Marina Castro', handle: 'marina.c', avatar: 'MC', color: '#F5A623' },
    lastMessage: 'cê vai no workshop de portfólio amanhã?',
    lastTime: '14:22', unread: 2, online: true,
    messages: [
      { id: 'm1', from: 'them', text: 'ei, gostei demais da sua pergunta hoje na abertura', time: '14:18' },
      { id: 'm2', from: 'them', text: 'cê vai no workshop de portfólio amanhã?', time: '14:22' },
    ],
  },
  {
    id: 'dm2', kind: 'dm',
    user: { name: 'Pedro Hanazaki', handle: 'p.hana', avatar: 'PH', color: '#3A56B0' },
    lastMessage: 'combinado, te vejo lá 👊',
    lastTime: 'ontem', unread: 0, online: false,
    messages: [
      { id: 'm1', from: 'me', text: 'opa, vai no tour do campus?', time: 'ontem 19:40' },
      { id: 'm2', from: 'them', text: 'combinado, te vejo lá 👊', time: 'ontem 19:42' },
    ],
  },
  {
    id: 'dm3', kind: 'dm',
    user: { name: 'Júlia Arruda', handle: 'juu.arruda', avatar: 'JA', color: '#E0457B' },
    lastMessage: 'te mando o material depois',
    lastTime: 'seg', unread: 0, online: false,
    messages: [
      { id: 'm1', from: 'them', text: 'te mando o material depois', time: 'seg 20:10' },
    ],
  },
];

// Chat rooms are keyed by event id. Auto-appear when user subscribes.
const CHAT_ROOM_DATA = {
  e1: {
    members: 312,
    messages: [
      { id: 'r1', from: 'other', user: { name: 'Luna Ferraz', avatar: 'LF', color: '#F5A623' }, text: 'Gente, material das referências tá no drive da IBMEC', time: '09:22' },
      { id: 'r2', from: 'other', user: { name: 'Thiago Nunes', avatar: 'TN', color: '#3A56B0' }, text: 'Alguém tá na fila pra perguntar? Posso passar na frente?', time: '09:24' },
      { id: 'r3', from: 'other', user: { name: 'Beatriz Lima', avatar: 'BL', color: '#0FA89B' }, text: 'Anotando tudo. Essa parte sobre autoconhecimento ficou forte.', time: '09:31' },
    ],
  },
  e2: {
    members: 38,
    messages: [
      { id: 'r1', from: 'other', user: { name: 'Rafa Otsuka', avatar: 'RO', color: '#0FA89B' }, text: 'Trouxe notebook, mas tá sem carregador. Alguém tem sobrando?', time: '10:45' },
      { id: 'r2', from: 'other', user: { name: 'Isa Ventura', avatar: 'IV', color: '#6B2EA8' }, text: 'Eu tenho USB-C, te empresto', time: '10:46' },
      { id: 'r3', from: 'other', user: { name: 'Marina Castro', avatar: 'MC', color: '#F5A623' }, text: 'Pro portfólio é melhor usar Figma ou Notion mesmo?', time: '10:52' },
    ],
  },
  e8: {
    members: 298,
    messages: [
      { id: 'r1', from: 'other', user: { name: 'Pedro Hanazaki', avatar: 'PH', color: '#3A56B0' }, text: 'Alguém vai ficar pro Q&A?', time: '11:02' },
      { id: 'r2', from: 'other', user: { name: 'Júlia Arruda', avatar: 'JA', color: '#E0457B' }, text: 'Eu vou! Tenho uma pergunta sobre a primeira empresa dela', time: '11:03' },
    ],
  },
};

// MessagesScreen — list of threads (DMs + subscribed-event chat rooms)
const MessagesScreen = ({ subscribed, onOpen }) => {
  const [filter, setFilter] = React.useState('all'); // all | dm | rooms
  const rooms = [...subscribed].map(eid => {
    const ev = EVENTS.find(e => e.id === eid);
    if (!ev) return null;
    const data = CHAT_ROOM_DATA[eid];
    const last = data?.messages[data.messages.length - 1];
    return {
      id: 'room-' + eid, kind: 'room', event: ev,
      members: data?.members || 12,
      lastMessage: last ? `${last.user.name.split(' ')[0]}: ${last.text}` : 'Comece a conversa',
      lastTime: last?.time || ev.time,
      unread: eid === 'e1' ? 5 : 0,
    };
  }).filter(Boolean);

  const dms = DM_THREADS;
  const all = [...rooms, ...dms];
  const list = filter === 'dm' ? dms : filter === 'rooms' ? rooms : all;
  const totalUnread = all.reduce((s, t) => s + (t.unread || 0), 0);

  return (
    <div className="screen">
      <StatusBar />
      <div style={{ padding: '4px 20px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', color: 'var(--text-mute)', marginBottom: 6 }}>
            CONVERSAS {totalUnread > 0 && <span style={{ color: 'var(--amber)' }}>· {totalUnread} novas</span>}
          </div>
          <h1 style={{ fontSize: 28, margin: 0, fontWeight: 600, letterSpacing: '-0.02em' }}>Mensagens</h1>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6, padding: '0 20px 14px' }}>
        {[
          { id: 'all', label: 'Todas', count: all.length },
          { id: 'rooms', label: 'Eventos', count: rooms.length },
          { id: 'dm', label: 'Diretas', count: dms.length },
        ].map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            padding: '8px 14px', cursor: 'pointer', font: 'inherit',
            background: filter === f.id ? 'rgba(255,255,255,0.08)' : 'transparent',
            border: `1px solid ${filter === f.id ? 'var(--line-strong)' : 'var(--line)'}`,
            color: filter === f.id ? '#fff' : 'var(--text-dim)',
            borderRadius: 999, fontSize: 12, fontWeight: 500,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            {f.label}
            <span style={{
              fontSize: 10, padding: '0 6px', borderRadius: 999,
              background: 'rgba(255,255,255,0.08)', color: 'var(--text-mute)', fontWeight: 600,
            }}>{f.count}</span>
          </button>
        ))}
      </div>

      {list.length === 0 ? (
        <div style={{ padding: '40px 32px', textAlign: 'center', color: 'var(--text-mute)' }}>
          <IconMessage size={36} stroke={1.4} />
          <div style={{ marginTop: 14, fontSize: 14, color: 'var(--text-dim)', lineHeight: 1.5 }}>
            {filter === 'rooms' ? 'Inscreva-se em um evento para entrar no chat da talk.' : 'Nenhuma conversa ainda.'}
          </div>
        </div>
      ) : (
        <div>
          {list.map(t => <ThreadRow key={t.id} thread={t} onOpen={() => onOpen(t)} />)}
        </div>
      )}
    </div>
  );
};

const ThreadRow = ({ thread, onOpen }) => {
  if (thread.kind === 'room') {
    const ev = thread.event;
    return (
      <button onClick={onOpen} style={{
        width: '100%', padding: '12px 20px', color: '#fff',
        background: thread.unread > 0 ? 'rgba(245,166,35,0.04)' : 'transparent',
        border: 'none', borderBottom: '1px solid var(--line)',
        cursor: 'pointer', font: 'inherit', textAlign: 'left',
        display: 'flex', gap: 12, alignItems: 'center',
      }}>
        <div style={{
          width: 48, height: 48, borderRadius: 12,
          background: `linear-gradient(135deg, var(--navy-800), var(--navy-950))`,
          border: '1px solid rgba(245,166,35,0.3)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--amber)', flexShrink: 0,
        }}><IconCalendar size={20} stroke={1.8} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
            <span style={{ fontSize: 14, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ev.title}</span>
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-mute)', marginBottom: 3, fontFamily: "'Geist Mono', monospace", letterSpacing: '0.08em' }}>
            SALA · {thread.members} membros
          </div>
          <div style={{ fontSize: 12, color: thread.unread > 0 ? '#fff' : 'var(--text-dim)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {thread.lastMessage}
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6, flexShrink: 0 }}>
          <span className="mono" style={{ fontSize: 10, color: 'var(--text-mute)' }}>{thread.lastTime}</span>
          {thread.unread > 0 && <span style={{
            minWidth: 18, height: 18, padding: '0 6px', borderRadius: 999,
            background: 'var(--amber)', color: '#05080F',
            fontSize: 10, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{thread.unread}</span>}
        </div>
      </button>
    );
  }
  return (
    <button onClick={onOpen} style={{
      width: '100%', padding: '12px 20px', color: '#fff',
      background: thread.unread > 0 ? 'rgba(245,166,35,0.04)' : 'transparent',
      border: 'none', borderBottom: '1px solid var(--line)',
      cursor: 'pointer', font: 'inherit', textAlign: 'left',
      display: 'flex', gap: 12, alignItems: 'center',
    }}>
      <div style={{ position: 'relative', flexShrink: 0 }}>
        <Avatar user={thread.user} size={48} />
        {thread.online && <span style={{
          position: 'absolute', bottom: 0, right: 0,
          width: 12, height: 12, borderRadius: '50%',
          background: '#4ADE80', border: '2px solid #05080F',
        }} />}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {thread.user.name}
        </div>
        <div style={{ fontSize: 12, color: thread.unread > 0 ? '#fff' : 'var(--text-dim)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {thread.lastMessage}
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6, flexShrink: 0 }}>
        <span className="mono" style={{ fontSize: 10, color: 'var(--text-mute)' }}>{thread.lastTime}</span>
        {thread.unread > 0 && <span style={{
          minWidth: 18, height: 18, padding: '0 6px', borderRadius: 999,
          background: 'var(--amber)', color: '#05080F',
          fontSize: 10, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{thread.unread}</span>}
      </div>
    </button>
  );
};

// ChatScreen — used for both DMs and chat rooms
const ChatScreen = ({ thread, onBack, currentUser }) => {
  const initialMessages = thread.kind === 'room'
    ? (CHAT_ROOM_DATA[thread.event.id]?.messages || [])
    : (thread.messages || []);
  const [messages, setMessages] = React.useState(initialMessages);
  const [draft, setDraft] = React.useState('');
  const scrollRef = React.useRef(null);

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

  const send = () => {
    if (!draft.trim()) return;
    setMessages(m => [...m, {
      id: 'new-' + Date.now(), from: thread.kind === 'room' ? 'me' : 'me',
      user: { name: currentUser.name, avatar: currentUser.avatar, color: currentUser.color },
      text: draft, time: 'agora',
    }]);
    setDraft('');
  };

  const isRoom = thread.kind === 'room';
  const title = isRoom ? thread.event.title : thread.user.name;
  const subtitle = isRoom
    ? `${thread.members} membros · ${thread.event.time}`
    : (thread.online ? 'online agora' : '@' + thread.user.handle);

  return (
    <div className="screen" style={{ display: 'flex', flexDirection: 'column' }}>
      <StatusBar />
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '8px 16px 12px', borderBottom: '1px solid var(--line)',
      }}>
        <button className="btn btn-nav" onClick={onBack} style={{ flexShrink: 0 }}>
          <IconChevronLeft size={20} />
        </button>
        <div style={{ flexShrink: 0 }}>
          {isRoom ? (
            <div style={{
              width: 40, height: 40, borderRadius: 10,
              background: 'linear-gradient(135deg, var(--navy-800), var(--navy-950))',
              border: '1px solid rgba(245,166,35,0.3)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--amber)',
            }}><IconCalendar size={18} stroke={1.8} /></div>
          ) : (
            <Avatar user={thread.user} size={40} />
          )}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title}</div>
          <div style={{ fontSize: 11, color: isRoom ? 'var(--amber)' : 'var(--text-mute)', marginTop: 1 }}>{subtitle}</div>
        </div>
        <button className="btn btn-nav" style={{ flexShrink: 0 }}>
          <IconMore size={18} />
        </button>
      </div>

      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 12px' }}>
        {isRoom && (
          <div style={{
            padding: '10px 14px', marginBottom: 16,
            background: 'rgba(245,166,35,0.06)',
            border: '1px dashed rgba(245,166,35,0.25)',
            borderRadius: 12, fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.4,
          }}>
            Sala oficial do evento. Apenas inscritos participam. Seja respeitoso com palestrantes e colegas.
          </div>
        )}
        {messages.map((m, i) => {
          const isMe = m.from === 'me';
          const showAvatar = isRoom && !isMe && (i === 0 || messages[i - 1].from === 'me' || messages[i - 1].user?.name !== m.user?.name);
          return (
            <div key={m.id} style={{
              display: 'flex', gap: 8, marginBottom: 10,
              flexDirection: isMe ? 'row-reverse' : 'row',
              alignItems: 'flex-end',
            }}>
              {isRoom && !isMe && (
                <div style={{ width: 28, flexShrink: 0 }}>
                  {showAvatar && <Avatar user={m.user} size={28} />}
                </div>
              )}
              <div style={{ maxWidth: '72%' }}>
                {isRoom && !isMe && showAvatar && (
                  <div style={{ fontSize: 11, color: 'var(--text-mute)', marginBottom: 3, paddingLeft: 2, fontWeight: 500 }}>
                    {m.user.name}
                  </div>
                )}
                <div style={{
                  padding: '9px 13px', borderRadius: 16,
                  background: isMe ? 'var(--amber)' : 'rgba(255,255,255,0.06)',
                  color: isMe ? '#05080F' : '#fff',
                  fontSize: 14, lineHeight: 1.4,
                  borderBottomRightRadius: isMe ? 4 : 16,
                  borderBottomLeftRadius: !isMe ? 4 : 16,
                }}>{m.text}</div>
                <div style={{
                  fontSize: 10, color: 'var(--text-mute)', marginTop: 3,
                  textAlign: isMe ? 'right' : 'left', paddingLeft: 2, paddingRight: 2,
                }}>{m.time}</div>
              </div>
            </div>
          );
        })}
      </div>

      <div style={{
        padding: '10px 12px 16px', borderTop: '1px solid var(--line)',
        display: 'flex', gap: 8, alignItems: 'center',
      }}>
        <input className="input" value={draft} onChange={e => setDraft(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && send()}
          placeholder={isRoom ? 'Mensagem para a sala...' : 'Mensagem...'}
          style={{ flex: 1 }} />
        <button onClick={send} disabled={!draft.trim()} style={{
          width: 40, height: 40, borderRadius: 12, flexShrink: 0,
          background: draft.trim() ? 'var(--amber)' : 'rgba(255,255,255,0.08)',
          color: draft.trim() ? '#05080F' : 'var(--text-mute)',
          border: 'none', cursor: draft.trim() ? 'pointer' : 'default',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <IconArrowRight size={18} stroke={2.2} />
        </button>
      </div>
    </div>
  );
};

Object.assign(window, { DM_THREADS, CHAT_ROOM_DATA, MessagesScreen, ChatScreen });
