// src/features/messages/ui/conversation-list.jsx
//
// Left column of the messages page. List of conversations the viewer is in,
// sorted by last_message_at desc. Click selects.

const CL_initials = (name) => {
  if (!name) return '?';
  const parts = name.trim().split(/\s+/);
  return (parts[0][0] + (parts[1]?.[0] || '')).toUpperCase();
};

const CL_preview = (m, viewerUserId) => {
  if (!m) return 'No messages yet.';
  const prefix = m.sender_id === viewerUserId ? 'You: ' : '';
  const body = (m.body || '').replace(/\s+/g, ' ').trim();
  if (body) return prefix + (body.length > 60 ? body.slice(0, 60) + '…' : body);
  if (m.has_attachments) return prefix + '[Attachment]';
  return prefix + '—';
};

const CL_when = (iso) => {
  if (!iso) return '';
  const d = new Date(iso), now = new Date();
  const same = d.toDateString() === now.toDateString();
  if (same) return d.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
  const yd = new Date(now); yd.setDate(yd.getDate() - 1);
  if (d.toDateString() === yd.toDateString()) return 'Yesterday';
  if ((now - d) < 7 * 24 * 60 * 60 * 1000) return d.toLocaleDateString(undefined, { weekday: 'short' });
  return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
};

const ConversationList = ({ conversations, selectedId, onSelect, viewerUserId }) => {
  if (!conversations || conversations.length === 0) {
    return (
      <div style={{ padding:'28px 18px', fontSize:13, color:'oklch(56% 0.03 265)',
                     fontStyle:'italic', textAlign:'center', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        No conversations yet. They appear automatically once an admin assigns you.
      </div>
    );
  }
  return (
    <div style={{ overflowY:'auto', height:'100%', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
      {conversations.map(c => {
        const peer = c.peer === 'student' ? c.student : c.instructor;
        const peerName = peer?.full_name || (c.peer === 'student' ? 'Student' : 'Teacher');
        const isSel = c.id === selectedId;
        const hue = peer?.hue || 220;
        return (
          <button key={c.id} onClick={() => onSelect(c.id)}
            style={{
              display:'flex', gap:12, alignItems:'center',
              width:'100%', padding:'14px 16px',
              background: isSel ? 'oklch(94% 0.02 265)' : 'transparent',
              border:'none', borderBottom:'1px solid oklch(94% 0.008 265)',
              cursor:'pointer', textAlign:'left', fontFamily:'inherit',
            }}>
            <div style={{
              width:40, height:40, borderRadius:'50%', flexShrink:0,
              background:`oklch(72% 0.12 ${hue})`,
              color:'#fff', fontSize:14, fontWeight:700,
              display:'flex', alignItems:'center', justifyContent:'center',
            }}>{peer?.avatar_initials || CL_initials(peerName)}</div>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ display:'flex', alignItems:'baseline', gap:8, marginBottom:2 }}>
                <span style={{ fontSize:14, fontWeight:600, color:'oklch(22% 0.06 265)',
                                overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', flex:1 }}>
                  {peerName}
                </span>
                <span style={{ fontSize:10, color:'oklch(56% 0.03 265)', flexShrink:0 }}>
                  {CL_when(c.last_message_at)}
                </span>
              </div>
              <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                <span style={{ flex:1, fontSize:12, color:'oklch(48% 0.03 265)',
                                overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                  {CL_preview(c.last_message, viewerUserId)}
                </span>
                {c.unread_count > 0 && (
                  <span style={{ flexShrink:0, minWidth:18, height:18, padding:'0 6px',
                                  borderRadius:9, background:'oklch(56% 0.18 25)',
                                  color:'#fff', fontSize:10, fontWeight:700,
                                  display:'flex', alignItems:'center', justifyContent:'center' }}>
                    {c.unread_count}
                  </span>
                )}
              </div>
            </div>
          </button>
        );
      })}
    </div>
  );
};

window.Messages.ui.ConversationList = ConversationList;
window.ConversationList             = ConversationList;
