/* global React */
// Mensajería interna — versión ligera (HU.3.3)
// Canal simple de comunicación CGR ↔ Institución, sin adjuntos.

const { useState: useStateMs, useMemo: useMemoMs } = React;

function MensajeriaScreen({ roleId, user, onOpenDetalle }) {
  const I = window.Icons;
  const conversaciones = window.getConversaciones(roleId);

  const [tab, setTab] = useStateMs('inbox');
  const [q, setQ] = useStateMs('');
  const [activeId, setActiveId] = useStateMs(conversaciones[0]?.id || null);
  const [composing, setComposing] = useStateMs(false);

  const filtered = useMemoMs(() => {
    let list = conversaciones;
    if (tab === 'inbox')  list = list.filter(c => c.folder === 'inbox');
    if (tab === 'unread') list = list.filter(c => c.unread > 0);
    if (tab === 'sent')   list = list.filter(c => c.folder === 'sent');
    if (q) {
      list = list.filter(c =>
        `${c.with.name} ${c.subject} ${c.preview} ${c.compromisoText || ''}`
          .toLowerCase().includes(q.toLowerCase())
      );
    }
    return list;
  }, [conversaciones, tab, q]);

  const active = conversaciones.find(c => c.id === activeId) || filtered[0];

  const counts = useMemoMs(() => {
    const c = { inbox: 0, sent: 0, unread: 0 };
    conversaciones.forEach(x => {
      c[x.folder] = (c[x.folder] || 0) + 1;
      c.unread += x.unread;
    });
    return c;
  }, [conversaciones]);

  return (
    <div data-screen-label="04 Mensajería">
      <div className="page-head">
        <div>
          <div className="page-head__eyebrow">{user.org}</div>
          <h1 className="page-head__title">Mensajería</h1>
          <p className="page-head__sub">
            Canal de comunicación interno con
            {roleId === 'institucion' ? ' la CGR' : ' las instituciones reportantes'}.
            Cada conversación queda registrada para trazabilidad.
          </p>
        </div>
        <div className="page-head__actions">
          <button type="button" className="btn btn--primary" onClick={() => setComposing(true)}>
            <I.Send size={14} /> Nuevo mensaje
          </button>
        </div>
      </div>

      {/* Tabs simples */}
      <div className="msg-tabs">
        <button type="button" className={`msg-tab${tab === 'inbox' ? ' is-active' : ''}`} onClick={() => setTab('inbox')}>
          <I.Inbox size={13} /> Recibidos <span className="msg-tab__count">{counts.inbox}</span>
        </button>
        <button type="button" className={`msg-tab${tab === 'unread' ? ' is-active' : ''}`} onClick={() => setTab('unread')}>
          ● No leídos {counts.unread > 0 && <span className="msg-tab__count is-danger">{counts.unread}</span>}
        </button>
        <button type="button" className={`msg-tab${tab === 'sent' ? ' is-active' : ''}`} onClick={() => setTab('sent')}>
          <I.Send size={13} /> Enviados <span className="msg-tab__count">{counts.sent}</span>
        </button>
        <div className="msg-tabs__spacer"></div>
        <div className="msg-tabs__search">
          <I.Search size={13} />
          <input type="text" placeholder="Buscar…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
      </div>

      {/* 2-pane mailbox */}
      <div className="mailbox mailbox--simple">
        {/* List */}
        <div className="mailbox__list">
          <ul className="conv-list">
            {filtered.map(c => (
              <li
                key={c.id}
                className={`conv${activeId === c.id ? ' is-active' : ''}${c.unread > 0 ? ' is-unread' : ''}`}
                onClick={() => { setActiveId(c.id); setComposing(false); }}
              >
                <div className={`conv__avatar conv__avatar--${c.with.tone}`}>{c.with.initials}</div>
                <div className="conv__body">
                  <div className="conv__head">
                    <strong>{c.with.name}</strong>
                    <span className="conv__date">{c.lastDate}</span>
                  </div>
                  <div className="conv__subject">{c.subject}</div>
                  {c.compromisoId && (
                    <div className="conv__ref">
                      <span className="mono">{c.compromisoId}</span>
                    </div>
                  )}
                  <div className="conv__preview">{c.preview}</div>
                </div>
                {c.unread > 0 && <div className="conv__unread">{c.unread}</div>}
              </li>
            ))}
            {filtered.length === 0 && (
              <li className="conv-empty">
                <I.Inbox size={28} />
                <h4>Sin conversaciones</h4>
                <p>No hay mensajes con esos criterios.</p>
              </li>
            )}
          </ul>
        </div>

        {/* Thread */}
        <div className="mailbox__thread">
          {composing ? (
            <SimpleComposer onCancel={() => setComposing(false)} roleId={roleId} />
          ) : active ? (
            <SimpleThread c={active} onOpenDetalle={onOpenDetalle} />
          ) : (
            <div className="thread-empty">
              <I.MessageSquare size={32} />
              <h3>Selecciona una conversación</h3>
              <p>El hilo aparecerá aquí.</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ---------------- Thread simple ----------------
function SimpleThread({ c, onOpenDetalle }) {
  const I = window.Icons;
  return (
    <>
      <header className="thread-head thread-head--slim">
        <div className="thread-head__top">
          <div className={`conv__avatar conv__avatar--lg conv__avatar--${c.with.tone}`}>{c.with.initials}</div>
          <div className="thread-head__who">
            <h3>{c.with.name}</h3>
            <small>{c.with.sub}</small>
          </div>
        </div>
        <h2 className="thread-head__subject">{c.subject}</h2>
        {c.compromisoId && (
          <button type="button" className="thread-head__ref" onClick={() => onOpenDetalle(c.compromisoId)}>
            <I.Link2 size={12} />
            <span className="mono">{c.compromisoId}</span>
            <span>{c.compromisoText}</span>
          </button>
        )}
      </header>

      <div className="thread-body">
        {c.mensajes.map((m, i) => (
          <article key={i} className={`msg msg--${m.from === 'out' ? 'out' : 'in'} msg--thread`}>
            {m.from === 'in' && <div className={`conv__avatar conv__avatar--${c.with.tone}`}>{c.with.initials}</div>}
            <div className="msg__body">
              <div className="msg__head">
                <strong>{m.author}</strong>
                <span className="msg__date">{m.date}</span>
              </div>
              <p>{m.text}</p>
            </div>
            {m.from === 'out' && <div className="conv__avatar conv__avatar--cgr">CB</div>}
          </article>
        ))}
      </div>

      <div className="thread-composer thread-composer--slim">
        <textarea placeholder="Escribir respuesta…" rows={2}></textarea>
        <button type="button" className="btn btn--primary btn--sm">
          <I.Send size={13} /> Enviar
        </button>
      </div>
    </>
  );
}

// ---------------- Composer simple ----------------
function SimpleComposer({ onCancel, roleId }) {
  const I = window.Icons;
  return (
    <>
      <header className="thread-head thread-head--slim">
        <div className="thread-head__top">
          <div className="conv__avatar conv__avatar--lg conv__avatar--default">
            <I.Send size={16} />
          </div>
          <div className="thread-head__who">
            <h3>Nuevo mensaje</h3>
            <small>Quedará registrado en la bandeja del destinatario</small>
          </div>
          <button type="button" className="btn btn--ghost btn--sm" style={{ marginLeft: 'auto' }} onClick={onCancel}>
            <I.XCircle size={14} /> Cancelar
          </button>
        </div>
      </header>

      <div className="thread-body" style={{ padding: '20px 24px', gap: 14 }}>
        <label className="field">
          <span className="field__label">Para</span>
          <select>
            {roleId === 'institucion' ? (
              <>
                <option>CGR · Dirección de Análisis de Datos</option>
                <option>CGR · Dirección General</option>
              </>
            ) : (
              <>
                <option>Seleccionar institución…</option>
                <option>SENAC</option>
                <option>Ministerio de Hacienda</option>
                <option>Ministerio de Justicia</option>
                <option>Ministerio Público</option>
                <option>SEPRELAD</option>
                <option>Ministerio del Interior</option>
              </>
            )}
          </select>
        </label>
        <label className="field">
          <span className="field__label">Asunto</span>
          <input type="text" placeholder="Resumen breve del tema" />
        </label>
        <label className="field">
          <span className="field__label">Mensaje</span>
          <textarea rows={6} placeholder="Escribe tu mensaje…"></textarea>
        </label>
      </div>

      <div className="thread-composer thread-composer--slim">
        <span style={{ fontSize: 11, color: 'var(--cgr-text-muted)' }}>
          <I.AlertCircle size={11} /> Quedará registro permanente del envío.
        </span>
        <button type="button" className="btn btn--primary btn--sm" style={{ marginLeft: 'auto' }}>
          <I.Send size={13} /> Enviar mensaje
        </button>
      </div>
    </>
  );
}

Object.assign(window, { MensajeriaScreen });
