// ============ Yap — messaging screens ============

// Group avatar: two overlapping member avatars
function GroupAvatar({ group, size = 52 }) {
  const ms = group.members || [];
  const a = size * 0.66;
  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      <div style={{ position: 'absolute', right: 0, bottom: 0 }}>
        <Avatar who={ms[1] || ms[0]} size={a} />
      </div>
      <div style={{ position: 'absolute', left: 0, top: 0, borderRadius: '50%',
        boxShadow: '0 0 0 2.5px var(--bg)' }}>
        <Avatar who={ms[0]} size={a} />
      </div>
    </div>
  );
}

function lastPreview(conv, msgs) {
  const list = msgs || conv.messages;
  const m = list[list.length - 1];
  if (!m) return '';
  const prefix = m.from === 'me' ? 'Toi : ' : (conv.group ? person(m.from).name.split(' ')[0] + ' : ' : '');
  const body = m.kind === 'image' ? '📷 Photo' : m.text;
  return prefix + body;
}

// ---------- Conversation list ----------
function ChatListScreen({ allMessages, onOpen, query, setQuery }) {
  const convs = CONVERSATIONS.filter(c => {
    if (!query) return true;
    const name = c.group ? c.group.name : person(c.peer).name;
    return name.toLowerCase().includes(query.toLowerCase());
  });
  return (
    <div className="screen page-fade">
      <TopBar>
        <div className="brandmark" style={{ fontSize: 30, color: 'var(--brand)', flex: 1 }}>Yap</div>
        <button className="iconbtn"><Icon name="camera" size={23} /></button>
        <button className="iconbtn" style={{ background: 'var(--brand)', color: 'var(--on-brand)' }}>
          <Icon name="edit" size={20} />
        </button>
      </TopBar>

      <div style={{ padding: '2px 16px 10px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '11px 15px',
          background: 'var(--surface-2)', borderRadius: 99 }}>
          <Icon name="search" size={19} color="var(--ink-faint)" />
          <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Rechercher"
            style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontSize: 15, fontWeight: 500 }} />
        </div>
      </div>

      <div className="scroll">
        {/* Stories row */}
        <div style={{ display: 'flex', gap: 16, padding: '6px 16px 14px', overflowX: 'auto' }}>
          {STORIES.map(s => (
            <button key={s.id} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center',
              gap: 7, flexShrink: 0, width: 64 }}>
              <div style={{ position: 'relative' }}>
                {s.isMe ? (
                  <div style={{ position: 'relative' }}>
                    <Avatar who={ME} size={58} />
                    <span style={{ position: 'absolute', right: -2, bottom: -2, width: 22, height: 22,
                      borderRadius: '50%', background: 'var(--brand)', color: 'white',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      border: '2.5px solid var(--bg)' }}><Icon name="plus" size={13} stroke={3} /></span>
                  </div>
                ) : <Avatar who={s.person} size={58} story seen={s.seen} />}
              </div>
              <span style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-soft)',
                maxWidth: 64, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {s.isMe ? 'Ta story' : s.person.name.split(' ')[0]}
              </span>
            </button>
          ))}
        </div>

        <div className="divider" style={{ margin: '0 16px' }} />

        {/* Conversation rows */}
        <div className="stagger" style={{ padding: '6px 8px 16px' }}>
          {convs.map((c, i) => {
            const msgs = allMessages[c.id] || c.messages;
            const isGroup = !!c.group;
            const p = isGroup ? null : person(c.peer);
            const name = isGroup ? c.group.name : p.name;
            return (
              <button key={c.id} onClick={() => onOpen(c.id)}
                style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 13,
                  padding: '11px 12px', borderRadius: 20, textAlign: 'left',
                  animationDelay: (i * 0.03) + 's',
                  transition: 'background 0.15s var(--ease)' }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-2)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                {isGroup ? <GroupAvatar group={c.group} size={54} />
                  : <Presence online={p.online}><Avatar who={p} size={54} /></Presence>}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    {c.pinned && <Icon name="pin" size={13} color="var(--ink-faint)" />}
                    <span style={{ fontWeight: 700, fontSize: 15.5, color: 'var(--ink)',
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{name}</span>
                  </div>
                  <div style={{ fontSize: 13.5, color: c.unread ? 'var(--ink)' : 'var(--ink-faint)',
                    fontWeight: c.unread ? 600 : 500, whiteSpace: 'nowrap', overflow: 'hidden',
                    textOverflow: 'ellipsis', marginTop: 2 }}>
                    {lastPreview(c, msgs)}
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
                  <span style={{ fontSize: 12, fontWeight: 600,
                    color: c.unread ? 'var(--brand)' : 'var(--ink-faint)' }}>{c.time}</span>
                  {c.unread > 0 && (
                    <span style={{ minWidth: 20, height: 20, padding: '0 6px', background: 'var(--brand)',
                      color: 'var(--on-brand)', borderRadius: 99, fontSize: 11.5, fontWeight: 800,
                      display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{c.unread}</span>
                  )}
                </div>
              </button>
            );
          })}
          {convs.length === 0 && (
            <div style={{ textAlign: 'center', color: 'var(--ink-faint)', padding: '48px 0', fontSize: 14 }}>
              Aucune conversation pour « {query} »
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ---------- Chat detail ----------
function ChatDetailScreen({ conv, messages, onBack, onSend, typing }) {
  const [draft, setDraft] = useState('');
  const scrollRef = useRef(null);
  const isGroup = !!conv.group;
  const p = isGroup ? null : person(conv.peer);
  const name = isGroup ? conv.group.name : p.name;

  useLayoutEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages.length, typing]);

  function submit(e) {
    e.preventDefault();
    const t = draft.trim();
    if (!t) return;
    onSend(t);
    setDraft('');
  }

  // group consecutive messages by sender, insert one date separator at top
  return (
    <div className="screen slide-in">
      <TopBar border style={{ paddingTop: 12, paddingBottom: 11 }}>
        <button className="iconbtn" style={{ width: 36, marginLeft: -6 }} onClick={onBack}>
          <Icon name="back" size={24} />
        </button>
        {isGroup ? <GroupAvatar group={conv.group} size={40} />
          : <Presence online={p.online} size={11}><Avatar who={p} size={40} /></Presence>}
        <div style={{ flex: 1, minWidth: 0, lineHeight: 1.2 }}>
          <div style={{ fontWeight: 700, fontSize: 16, whiteSpace: 'nowrap', overflow: 'hidden',
            textOverflow: 'ellipsis' }}>{name}</div>
          <div style={{ fontSize: 12, color: typing ? 'var(--brand)' : 'var(--ink-faint)', fontWeight: 600 }}>
            {typing ? 'écrit…' : (isGroup
              ? conv.group.members.length + ' membres'
              : (p.online ? 'en ligne' : 'vu récemment'))}
          </div>
        </div>
        <button className="iconbtn"><Icon name="phone" size={21} /></button>
        <button className="iconbtn" style={{ marginRight: -6 }}><Icon name="video" size={22} /></button>
      </TopBar>

      <div className="scroll" ref={scrollRef} style={{ padding: '14px 14px 8px',
        display: 'flex', flexDirection: 'column', gap: 3,
        background: 'linear-gradient(180deg, var(--bg), oklch(0.965 0.012 280))' }}>
        <div style={{ alignSelf: 'center', fontSize: 11.5, fontWeight: 700, color: 'var(--ink-faint)',
          background: 'var(--surface-2)', padding: '5px 13px', borderRadius: 99, margin: '2px 0 12px' }}>
          Aujourd'hui
        </div>
        {messages.map((m, i) => {
          const mine = m.from === 'me';
          const prev = messages[i - 1];
          const next = messages[i + 1];
          const showName = isGroup && !mine && (!prev || prev.from !== m.from);
          const groupedTop = prev && prev.from === m.from;
          return (
            <div key={m.id} style={{ display: 'flex', flexDirection: 'column',
              alignItems: mine ? 'flex-end' : 'flex-start', marginTop: groupedTop ? 0 : 8 }}>
              {showName && (
                <span style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--ink-faint)',
                  margin: '2px 0 3px 14px' }}>{person(m.from).name.split(' ')[0]}</span>
              )}
              {m.kind === 'image' ? (
                <div className="bubble" style={{ padding: 4, overflow: 'hidden',
                  background: mine ? 'var(--brand)' : 'var(--surface)' }}>
                  <div className="ph" style={{ width: 200, height: 150, borderRadius: 'calc(var(--bubble-radius) - 6px)' }}>
                    <span className="ph__label">{m.text}</span>
                  </div>
                </div>
              ) : (
                <div className={'bubble ' + (mine ? 'bubble--out' : 'bubble--in')}>{m.text}</div>
              )}
              {m.reactions && m.reactions.length > 0 && (
                <div style={{ display: 'flex', gap: 3, marginTop: -7, zIndex: 2,
                  marginRight: mine ? 6 : 0, marginLeft: mine ? 0 : 6 }}>
                  {m.reactions.map((r, ri) => (
                    <span key={ri} style={{ fontSize: 13, background: 'var(--surface)',
                      borderRadius: 99, padding: '2px 6px', boxShadow: '0 1px 4px oklch(0.2 0.05 270 / 0.12)',
                      border: '1px solid var(--line-soft)' }}>{r}</span>
                  ))}
                </div>
              )}
              {mine && !next && (
                <span style={{ fontSize: 10.5, color: 'var(--ink-faint)', fontWeight: 600,
                  marginTop: 4, marginRight: 4, display: 'flex', alignItems: 'center', gap: 3 }}>
                  {m.time || ''} <Icon name="checks" size={15} color="var(--brand)" />
                </span>
              )}
            </div>
          );
        })}
        {typing && (
          <div style={{ alignSelf: 'flex-start', marginTop: 8 }}>
            <div className="bubble bubble--in" style={{ display: 'flex', gap: 4, padding: '13px 16px' }}>
              {[0, 1, 2].map(d => (
                <span key={d} style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--ink-faint)',
                  animation: `typing 1.2s ${d * 0.15}s infinite var(--ease)` }} />
              ))}
            </div>
          </div>
        )}
        <div style={{ height: 4 }} />
      </div>

      <form onSubmit={submit} style={{ flexShrink: 0, display: 'flex', alignItems: 'flex-end', gap: 9,
        padding: '10px 14px calc(12px + env(safe-area-inset-bottom))', background: 'var(--bg)',
        boxShadow: '0 -1px 0 var(--line)' }}>
        <button type="button" className="iconbtn" style={{ background: 'var(--surface-2)', width: 44, height: 44 }}>
          <Icon name="plus" size={23} color="var(--brand)" />
        </button>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8, background: 'var(--surface)',
          border: '1px solid var(--line)', borderRadius: 24, padding: '4px 6px 4px 16px' }}>
          <input value={draft} onChange={e => setDraft(e.target.value)} placeholder="Message…"
            style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 15,
              fontWeight: 500, padding: '9px 0' }} />
          <button type="button" className="iconbtn" style={{ width: 36, height: 36 }}>
            <Icon name="smiley" size={22} color="var(--ink-faint)" />
          </button>
        </div>
        <button type="submit" className="iconbtn" disabled={!draft.trim()}
          style={{ width: 46, height: 46, background: 'var(--brand)', color: 'var(--on-brand)',
            boxShadow: draft.trim() ? '0 6px 16px -6px var(--brand)' : 'none',
            opacity: draft.trim() ? 1 : 0.5, transition: 'all 0.2s var(--ease)' }}>
          <Icon name={draft.trim() ? 'send' : 'mic'} size={22} />
        </button>
      </form>
    </div>
  );
}

// typing keyframes (injected once)
if (!document.getElementById('yap-typing-kf')) {
  const st = document.createElement('style');
  st.id = 'yap-typing-kf';
  st.textContent = '@keyframes typing{0%,60%,100%{opacity:.3;transform:translateY(0)}30%{opacity:1;transform:translateY(-3px)}}';
  document.head.appendChild(st);
}

Object.assign(window, { ChatListScreen, ChatDetailScreen, GroupAvatar });
