// src/features/messages/ui/admin-messages.jsx
//
// Admin read-only archive: list of every conversation across the platform
// with the latest preview; click → read-only thread view (no composer).

const AdminMessages = () => {
  const auth = window.useAuth ? window.useAuth() : { user: null };
  const [conversations, setConversations] = React.useState([]);
  const [selectedId,    setSelectedId]    = React.useState(null);
  const [loading,       setLoading]       = React.useState(true);
  const [err,           setErr]           = React.useState('');

  const refresh = React.useCallback(async () => {
    try {
      const rows = await window.Messages.db.loadConversations(auth.user?.id);
      setConversations(rows);
      setLoading(false);
    } catch (e) { setErr(e.message || String(e)); setLoading(false); }
  }, [auth.user?.id]);

  React.useEffect(() => {
    refresh();
    const sub = window.Messages.db.subscribeToInbox(() => refresh());
    return () => sub.unsubscribe();
  }, [refresh]);

  if (loading) return <div style={{ padding:24, color:'oklch(56% 0.03 265)' }}>Loading…</div>;
  if (err)     return <div style={{ padding:24, color:'oklch(40% 0.15 25)' }}>{err}</div>;

  const selected = conversations.find(c => c.id === selectedId);

  return (
    <div style={{ display:'flex', gap:0, minHeight:'60vh',
                   border:'1px solid oklch(92% 0.01 265)', borderRadius:10, overflow:'hidden',
                   fontFamily:"'Plus Jakarta Sans', sans-serif", background:'#fff' }}>
      {/* Left: list */}
      <div style={{ width:340, borderRight:'1px solid oklch(92% 0.01 265)',
                     maxHeight:'70vh', overflowY:'auto', background:'#fff' }}>
        {conversations.length === 0 ? (
          <div style={{ padding:20, color:'oklch(56% 0.03 265)', fontSize:13, fontStyle:'italic' }}>
            No conversations on the platform yet.
          </div>
        ) : conversations.map(c => {
          const isSel = c.id === selectedId;
          return (
            <button key={c.id} onClick={() => setSelectedId(c.id)}
              style={{ display:'block', width:'100%', textAlign:'left',
                       padding:'12px 14px', border:'none',
                       borderBottom:'1px solid oklch(94% 0.008 265)',
                       background: isSel ? 'oklch(94% 0.02 265)' : 'transparent',
                       cursor:'pointer', fontFamily:'inherit' }}>
              <div style={{ fontSize:13, fontWeight:600, color:'oklch(22% 0.06 265)' }}>
                {c.student?.full_name || 'Student'} <span style={{ color:'oklch(56% 0.03 265)', fontWeight:400 }}>↔</span> {c.instructor?.full_name || 'Teacher'}
              </div>
              <div style={{ fontSize:11, color:'oklch(50% 0.03 265)', marginTop:3,
                             overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                {c.last_message?.body || (c.last_message ? '[Attachment]' : 'No messages yet')}
              </div>
              <div style={{ fontSize:10, color:'oklch(58% 0.03 265)', marginTop:3 }}>
                {c.last_message_at ? new Date(c.last_message_at).toLocaleString() : ''}
              </div>
            </button>
          );
        })}
      </div>

      {/* Right: read-only thread */}
      <div style={{ flex:1, display:'flex', flexDirection:'column', minWidth:0 }}>
        {!selected ? (
          <div style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center',
                         color:'oklch(56% 0.03 265)', fontSize:13, padding:24, textAlign:'center' }}>
            Pick a conversation to read it.
          </div>
        ) : (
          <React.Fragment>
            <div style={{ padding:'12px 16px', borderBottom:'1px solid oklch(92% 0.01 265)',
                           fontSize:13, color:'oklch(22% 0.06 265)' }}>
              <span style={{ fontWeight:600 }}>
                {selected.student?.full_name} ↔ {selected.instructor?.full_name}
              </span>
              <span style={{ marginLeft:10, fontSize:11, color:'oklch(56% 0.03 265)' }}>
                (read-only)
              </span>
            </div>
            <window.ThreadView
              conversationId={selected.id}
              viewerUserId={auth.user?.id}
              peerLabel={selected.student?.full_name}
              readOnly
            />
          </React.Fragment>
        )}
      </div>
    </div>
  );
};

window.Messages.ui.AdminMessages = AdminMessages;
window.AdminMessages             = AdminMessages;
