import React, { useState, useMemo } from 'react';
import { MOCK_MESSAGES, MOCK_TEAM, MOCK_PROJECTS, MOCK_TASKS, MOCK_USER } from '../../services/mockData';
import { useProject } from '../../context/ProjectContext';

// ── Helpers ───────────────────────────────────────────────────────────────────
const fmtDate = s => {
  const d = new Date(s);
  const now = new Date();
  const diff = Math.floor((now - d) / 60000);
  if (diff < 60) return `hace ${diff}m`;
  if (diff < 1440) return `hace ${Math.floor(diff/60)}h`;
  return d.toLocaleDateString('es-MX', { day:'2-digit', month:'short' });
};
const fmtFull = s => new Date(s).toLocaleString('es-MX', { day:'2-digit', month:'short', year:'numeric', hour:'2-digit', minute:'2-digit' });

const TYPE_CONFIG = {
  RECORDATORIO: { label:'Recordatorio', color:'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300',   icon:'🔔' },
  ALERTA:       { label:'Alerta',        color:'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-300',       icon:'⚠' },
  GENERAL:      { label:'General',       color:'bg-slate-100 text-slate-600 dark:bg-gray-500/20 dark:text-gray-300', icon:'✉' },
  APROBACION:   { label:'Aprobación',    color:'bg-purple-100 text-purple-700 dark:bg-purple-500/20 dark:text-purple-300', icon:'✅' },
};
const PRIORITY_COLOR = {
  CRITICO:'text-red-500', ALTO:'text-orange-500', MEDIO:'text-amber-500', BAJO:'text-slate-400',
};

const ME_ID = MOCK_USER.id; // 'mock-1' → matches u1

// All tasks flat list for reminder selector
const ALL_TASKS = Object.entries(MOCK_TASKS).flatMap(([projId, tasks]) =>
  tasks.filter(t => !t.isMilestone).map(t => ({ ...t, projId }))
);

// ── Avatar ────────────────────────────────────────────────────────────────────
function Av({ person, size = 'sm' }) {
  const sz = size === 'lg' ? 'w-10 h-10 text-sm' : 'w-8 h-8 text-xs';
  return (
    <div className={`${sz} rounded-full flex items-center justify-center font-bold flex-shrink-0`}
      style={{ background: (person?.color || '#64748b') + '22', color: person?.color || '#64748b' }}>
      {person?.avatar || '?'}
    </div>
  );
}

// ── Compose modal ─────────────────────────────────────────────────────────────
function ComposeModal({ onSend, onClose, prefill }) {
  const [form, setForm] = useState({
    toId:      prefill?.toId     || '',
    type:      prefill?.type     || 'GENERAL',
    priority:  prefill?.priority || 'MEDIO',
    subject:   prefill?.subject  || '',
    body:      prefill?.body     || '',
    projectId: prefill?.projectId|| '',
    taskId:    prefill?.taskId   || '',
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const projTasks = form.projectId
    ? ALL_TASKS.filter(t => {
        const proj = MOCK_PROJECTS.find(p => p.id === form.projectId);
        return proj && t.projId === form.projectId;
      })
    : [];

  const canSend = form.toId && form.subject.trim() && form.body.trim();

  const handleSend = () => {
    if (!canSend) return;
    const to   = MOCK_TEAM.find(m => m.id === form.toId);
    const proj = MOCK_PROJECTS.find(p => p.id === form.projectId);
    const task = ALL_TASKS.find(t => t.id === form.taskId);
    onSend({
      id: `msg${Date.now()}`,
      type: form.type,
      priority: form.priority,
      from: { id: ME_ID, name: `${MOCK_USER.firstName} ${MOCK_USER.lastName}`, avatar: 'AS', color: '#2563EB' },
      to:   { id: to.id, name: `${to.firstName} ${to.lastName}`, avatar: to.avatar, color: to.color },
      subject: form.subject,
      body: form.body,
      projectId:   form.projectId   || null,
      projectCode: proj?.code        || null,
      taskId:      form.taskId       || null,
      taskWbs:     task?.wbsCode     || null,
      taskTitle:   task?.title       || null,
      date: new Date().toISOString(),
      read: true,
    });
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={onClose}/>
      <div className="relative w-full max-w-xl bg-white dark:bg-surface-800 rounded-2xl shadow-2xl border border-slate-200 dark:border-surface-700 overflow-hidden max-h-[90vh] flex flex-col">

        <div className="px-6 py-4 border-b border-slate-100 dark:border-surface-700 flex items-center justify-between flex-shrink-0">
          <h2 className="text-base font-bold text-slate-900 dark:text-white">Nuevo mensaje</h2>
          <button onClick={onClose} className="p-1.5 rounded-lg text-slate-400 hover:text-slate-700 dark:hover:text-white hover:bg-black/5 transition cursor-pointer">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>

        <div className="overflow-y-auto flex-1 p-6 space-y-4">
          {/* To */}
          <div>
            <label className="field-label">Para <span className="text-red-500">*</span></label>
            <select value={form.toId} onChange={e => set('toId', e.target.value)} className="field-input">
              <option value="">Seleccionar destinatario...</option>
              {MOCK_TEAM.map(m => (
                <option key={m.id} value={m.id}>{m.firstName} {m.lastName} — {m.title}</option>
              ))}
            </select>
          </div>

          {/* Type + Priority */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="field-label">Tipo</label>
              <select value={form.type} onChange={e => set('type', e.target.value)} className="field-input">
                {Object.entries(TYPE_CONFIG).map(([k, v]) => (
                  <option key={k} value={k}>{v.icon} {v.label}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="field-label">Prioridad</label>
              <select value={form.priority} onChange={e => set('priority', e.target.value)} className="field-input">
                <option value="CRITICO">Crítico</option>
                <option value="ALTO">Alto</option>
                <option value="MEDIO">Medio</option>
                <option value="BAJO">Bajo</option>
              </select>
            </div>
          </div>

          {/* Project + Task (optional) */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="field-label">Proyecto (opcional)</label>
              <select value={form.projectId} onChange={e => { set('projectId', e.target.value); set('taskId', ''); }} className="field-input">
                <option value="">Sin proyecto</option>
                {MOCK_PROJECTS.map(p => <option key={p.id} value={p.id}>{p.code}</option>)}
              </select>
            </div>
            <div>
              <label className="field-label">Tarea (opcional)</label>
              <select value={form.taskId} onChange={e => set('taskId', e.target.value)} className="field-input" disabled={!form.projectId}>
                <option value="">Sin tarea específica</option>
                {projTasks.map(t => <option key={t.id} value={t.id}>{t.wbsCode} — {t.title}</option>)}
              </select>
            </div>
          </div>

          {/* Subject */}
          <div>
            <label className="field-label">Asunto <span className="text-red-500">*</span></label>
            <input value={form.subject} onChange={e => set('subject', e.target.value)} className="field-input" placeholder="Asunto del mensaje..."/>
          </div>

          {/* Body */}
          <div>
            <label className="field-label">Mensaje <span className="text-red-500">*</span></label>
            <textarea rows={5} value={form.body} onChange={e => set('body', e.target.value)}
              className="field-input resize-none" placeholder="Escribe tu mensaje aquí..."/>
          </div>
        </div>

        <div className="px-6 py-4 border-t border-slate-100 dark:border-surface-700 flex gap-3 justify-end flex-shrink-0">
          <button onClick={onClose}
            className="px-4 py-2 text-sm font-medium rounded-xl border border-slate-200 dark:border-surface-600 text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-surface-700 transition cursor-pointer">
            Cancelar
          </button>
          <button onClick={handleSend} disabled={!canSend}
            className="px-4 py-2 text-sm font-semibold rounded-xl bg-blue-600 hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed text-white transition cursor-pointer flex items-center gap-2">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
            Enviar
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Message detail panel ──────────────────────────────────────────────────────
function MessageDetail({ msg, onReply, onClose }) {
  if (!msg) return (
    <div className="flex-1 flex items-center justify-center text-slate-300 dark:text-gray-600">
      <div className="text-center">
        <svg className="w-12 h-12 mx-auto mb-3 opacity-30" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
        <p className="text-sm">Selecciona un mensaje</p>
      </div>
    </div>
  );

  const tc = TYPE_CONFIG[msg.type] || TYPE_CONFIG.GENERAL;

  return (
    <div className="flex-1 flex flex-col min-w-0">
      {/* Header */}
      <div className="px-6 py-5 border-b border-slate-100 dark:border-surface-700 flex-shrink-0">
        <div className="flex items-start justify-between gap-3 mb-3">
          <h2 className="text-base font-bold text-slate-900 dark:text-white leading-snug flex-1">{msg.subject}</h2>
          <button onClick={onClose} className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 dark:hover:text-gray-300 hover:bg-slate-100 dark:hover:bg-surface-700 transition cursor-pointer flex-shrink-0 xl:hidden">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${tc.color}`}>{tc.icon} {tc.label}</span>
          <span className={`text-xs font-semibold ${PRIORITY_COLOR[msg.priority]}`}>{msg.priority}</span>
        </div>

        {/* Referencias prominentes */}
        {(msg.projectCode || msg.taskId) && (
          <div className="mt-3 flex items-center gap-2 flex-wrap bg-slate-50 dark:bg-surface-700/50 rounded-xl px-3 py-2.5 border border-slate-100 dark:border-surface-600">
            <svg className="w-3.5 h-3.5 text-slate-400 dark:text-gray-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/></svg>
            <span className="text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">Ref:</span>
            {msg.projectCode && (
              <span className="text-xs font-mono font-bold px-2 py-0.5 rounded-md bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-300">
                {msg.projectCode}
              </span>
            )}
            {msg.taskId && (
              <span className="flex items-center gap-1 text-xs">
                {msg.taskWbs && (
                  <span className="font-mono font-bold px-2 py-0.5 rounded-md bg-violet-100 dark:bg-violet-500/20 text-violet-700 dark:text-violet-300">
                    WBS {msg.taskWbs}
                  </span>
                )}
                {msg.taskTitle && (
                  <span className="text-slate-600 dark:text-gray-300 truncate max-w-[220px]">{msg.taskTitle}</span>
                )}
              </span>
            )}
          </div>
        )}
      </div>

      {/* From / To */}
      <div className="px-6 py-4 border-b border-slate-50 dark:border-surface-700/50 bg-slate-50/50 dark:bg-surface-700/20 flex-shrink-0">
        <div className="flex items-center gap-3 text-sm">
          <Av person={msg.from} size="lg"/>
          <div className="flex-1 min-w-0">
            <p className="font-semibold text-slate-800 dark:text-gray-200">{msg.from.name}</p>
            <p className="text-xs text-slate-400 dark:text-gray-500">Para: {msg.to.name} · {fmtFull(msg.date)}</p>
          </div>
        </div>
      </div>

      {/* Body */}
      <div className="flex-1 overflow-y-auto px-6 py-5">
        <p className="text-sm text-slate-700 dark:text-gray-300 leading-relaxed whitespace-pre-wrap">{msg.body}</p>
      </div>

      {/* Actions */}
      <div className="px-6 py-4 border-t border-slate-100 dark:border-surface-700 flex gap-3 flex-shrink-0">
        <button onClick={() => onReply(msg)}
          className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 text-white transition cursor-pointer">
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"/></svg>
          Responder
        </button>
        {msg.taskId && (
          <button onClick={() => onReply({ ...msg, type:'RECORDATORIO', subject:`Re: ${msg.subject}` })}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl border border-slate-200 dark:border-surface-600 text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-surface-700 transition cursor-pointer">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6 6 0 10-12 0v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/></svg>
            Reenviar recordatorio
          </button>
        )}
      </div>
    </div>
  );
}

// ── Page ──────────────────────────────────────────────────────────────────────
const VIEWS = ['Recibidos','Enviados'];

export default function MessagesPage() {
  const { selectedProjectId } = useProject();
  const [messages, setMessages] = useState(MOCK_MESSAGES);
  const [view,     setView]     = useState(0);   // 0=inbox 1=sent
  const [selected, setSelected] = useState(null);
  const [compose,  setCompose]  = useState(false);
  const [prefill,  setPrefill]  = useState(null);
  const [search,   setSearch]   = useState('');
  const [typeF,    setTypeF]    = useState('all');

  // Inbox = messages TO me; Sent = FROM me
  // For demo, u1 = admin = ME. Incoming = to.id === 'u1' or mock-1, outgoing = from admin
  const inbox = useMemo(() => messages.filter(m => m.to.id === 'u1' || m.to.id === ME_ID), [messages]);
  const sent  = useMemo(() => messages.filter(m => m.from.id === 'u1' || m.from.id === ME_ID), [messages]);
  const list  = view === 0 ? inbox : sent;

  const filtered = useMemo(() => list.filter(m => {
    const matchSearch = !search || `${m.subject} ${m.from.name} ${m.to.name} ${m.body}`.toLowerCase().includes(search.toLowerCase());
    const matchType   = typeF === 'all' || m.type === typeF;
    const matchProj   = !selectedProjectId || !m.projectId || m.projectId === selectedProjectId;
    return matchSearch && matchType && matchProj;
  }), [list, search, typeF, selectedProjectId]);

  const unreadCount = inbox.filter(m => !m.read).length;

  const openMsg = (msg) => {
    setSelected(msg);
    if (!msg.read) {
      setMessages(prev => prev.map(m => m.id === msg.id ? { ...m, read: true } : m));
    }
  };

  const handleSend = (newMsg) => {
    setMessages(prev => [newMsg, ...prev]);
    setView(1);
    setSelected(newMsg);
  };

  const handleReply = (msg) => {
    const replyTo = view === 0 ? msg.from : msg.to;
    setPrefill({
      toId: replyTo.id,
      type: msg.type,
      priority: msg.priority,
      subject: msg.subject.startsWith('Re:') ? msg.subject : `Re: ${msg.subject}`,
      body: `\n\n--- Mensaje original ---\n${msg.body}`,
      projectId: msg.projectId || '',
      taskId: msg.taskId || '',
    });
    setCompose(true);
  };

  const openReminder = () => {
    setPrefill({ type: 'RECORDATORIO', priority: 'ALTO' });
    setCompose(true);
  };

  return (
    <div className="flex flex-col h-[calc(100vh-112px)] gap-3">

      {/* Toolbar */}
      <div className="flex items-center justify-between flex-wrap gap-3 flex-shrink-0">
        <div>
          <h1 className="text-lg font-bold text-slate-900 dark:text-white">Mensajes internos</h1>
          <p className="text-sm text-slate-400 dark:text-gray-500 mt-0.5">
            {unreadCount > 0 && <span className="text-blue-600 dark:text-blue-400 font-semibold">{unreadCount} sin leer · </span>}
            Comunicación entre miembros del equipo
          </p>
        </div>
        <div className="flex gap-2">
          <button onClick={openReminder}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl border border-blue-300 dark:border-blue-500/40 text-blue-700 dark:text-blue-400 bg-blue-50 dark:bg-blue-500/10 hover:bg-blue-100 dark:hover:bg-blue-500/20 transition cursor-pointer">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6 6 0 10-12 0v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/></svg>
            Recordatorio de tarea
          </button>
          <button onClick={() => { setPrefill(null); setCompose(true); }}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 text-white transition cursor-pointer shadow-sm">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4"/></svg>
            Nuevo mensaje
          </button>
        </div>
      </div>

      {/* Main panel */}
      <div className="flex-1 min-h-0 bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden flex">

        {/* Left: list */}
        <div className={`flex-shrink-0 flex flex-col border-r border-slate-100 dark:border-surface-700 ${selected ? 'hidden xl:flex' : 'flex'}`}
          style={{ width: 340 }}>

          {/* Tabs */}
          <div className="flex gap-1 p-2 border-b border-slate-100 dark:border-surface-700 bg-slate-50 dark:bg-surface-700/30">
            {VIEWS.map((v, i) => {
              const count = i === 0 ? unreadCount : 0;
              return (
                <button key={v} onClick={() => { setView(i); setSelected(null); }}
                  className={`flex-1 py-1.5 text-sm font-medium rounded-lg transition cursor-pointer relative ${view === i ? 'bg-white dark:bg-surface-700 text-slate-900 dark:text-white shadow-sm' : 'text-slate-500 dark:text-gray-400 hover:text-slate-700 dark:hover:text-gray-200'}`}>
                  {v}
                  {count > 0 && <span className="absolute top-1 right-2 w-4 h-4 bg-blue-600 text-white rounded-full text-xs flex items-center justify-center font-bold">{count}</span>}
                </button>
              );
            })}
          </div>

          {/* Search + filter */}
          <div className="p-3 space-y-2 border-b border-slate-50 dark:border-surface-700">
            <div className="relative">
              <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="11" cy="11" r="8"/><path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-4.35-4.35"/></svg>
              <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar mensajes..."
                className="w-full pl-8 pr-3 py-1.5 text-xs rounded-lg border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-gray-200 placeholder-slate-300 dark:placeholder-gray-600 focus:outline-none focus:ring-1 focus:ring-blue-500"/>
            </div>
            <div className="flex gap-1 flex-wrap">
              {['all','RECORDATORIO','ALERTA','GENERAL','APROBACION'].map(t => (
                <button key={t} onClick={() => setTypeF(t)}
                  className={`text-xs px-2 py-0.5 rounded-full transition cursor-pointer ${typeF === t ? 'bg-blue-600 text-white' : 'bg-slate-100 dark:bg-surface-700 text-slate-500 dark:text-gray-400 hover:bg-slate-200 dark:hover:bg-surface-600'}`}>
                  {t === 'all' ? 'Todos' : TYPE_CONFIG[t]?.label}
                </button>
              ))}
            </div>
          </div>

          {/* Message list */}
          <div className="flex-1 overflow-y-auto">
            {filtered.length === 0 ? (
              <div className="flex items-center justify-center h-32 text-slate-300 dark:text-gray-600 text-sm">Sin mensajes</div>
            ) : (
              filtered.map(msg => {
                const tc = TYPE_CONFIG[msg.type] || TYPE_CONFIG.GENERAL;
                const isMe = view === 1;
                const person = isMe ? msg.to : msg.from;
                const isSelected = selected?.id === msg.id;
                const isUnread   = !msg.read && view === 0;
                return (
                  <button key={msg.id} onClick={() => openMsg(msg)} style={{ width:'100%', textAlign:'left' }}
                    className={`px-4 py-3 border-b border-slate-50 dark:border-surface-700/50 hover:bg-slate-50 dark:hover:bg-surface-700/30 transition-colors cursor-pointer ${isSelected ? 'bg-blue-50 dark:bg-blue-500/10 border-l-2 border-l-blue-500' : ''}`}>
                    <div className="flex items-start gap-3">
                      <Av person={person}/>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between gap-2 mb-0.5">
                          <p className={`text-xs truncate ${isUnread ? 'font-bold text-slate-900 dark:text-white' : 'font-medium text-slate-700 dark:text-gray-300'}`}>
                            {person.name}
                          </p>
                          <span className="text-xs text-slate-300 dark:text-gray-600 flex-shrink-0">{fmtDate(msg.date)}</span>
                        </div>
                        <p className={`text-xs truncate mb-1 ${isUnread ? 'text-slate-800 dark:text-gray-200 font-semibold' : 'text-slate-600 dark:text-gray-400'}`}>
                          {msg.subject}
                        </p>
                        <div className="flex items-center gap-1.5 flex-wrap">
                          <span className={`text-xs px-1.5 py-0.5 rounded-full ${tc.color}`}>{tc.label}</span>
                          {msg.projectCode && (
                            <span className="text-xs font-mono font-semibold px-1.5 py-0.5 rounded-md bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-300">
                              {msg.projectCode}
                            </span>
                          )}
                          {msg.taskWbs && (
                            <span className="text-xs font-mono px-1.5 py-0.5 rounded-md bg-violet-100 dark:bg-violet-500/20 text-violet-700 dark:text-violet-300">
                              WBS {msg.taskWbs}
                            </span>
                          )}
                          {isUnread && <span className="w-1.5 h-1.5 bg-blue-500 rounded-full ml-auto flex-shrink-0"/>}
                        </div>
                      </div>
                    </div>
                  </button>
                );
              })
            )}
          </div>
        </div>

        {/* Right: detail */}
        <MessageDetail
          msg={selected}
          onReply={handleReply}
          onClose={() => setSelected(null)}
        />
      </div>

      {compose && (
        <ComposeModal
          prefill={prefill}
          onSend={handleSend}
          onClose={() => { setCompose(false); setPrefill(null); }}
        />
      )}
    </div>
  );
}
