// COMMUNICATIONS PLATFORM — Unified Inbox (email threads with matter linking)
const { useState: useCmInboxState, useMemo: useCmInboxMemo } = React;

function CommsInbox() {
  const cm = window.__cm;
  const Tc = window.ArbiterTokens;
  const data = window.COMMS_DATA;

  const [folder, setFolder] = useCmInboxState('inbox');
  const [selected, setSelected] = useCmInboxState(data.emailThreads[0].id);
  const [query, setQuery] = useCmInboxState('');

  const folders = [
    { id: 'inbox',      label: 'Inbox',           count: data.emailThreads.filter(e => e.unread).length },
    { id: 'starred',    label: 'Starred',         count: data.emailThreads.filter(e => e.starred).length },
    { id: 'privileged', label: 'Privileged',      count: data.emailThreads.filter(e => e.sensitivity === 'privileged').length },
    { id: 'encrypted',  label: 'Encrypted (E2EE)', count: data.emailThreads.filter(e => e.encrypted).length },
    { id: 'attachments', label: 'With attachments', count: data.emailThreads.filter(e => e.hasAttachments).length },
    { id: 'client',     label: 'Client',          count: data.emailThreads.filter(e => e.labels.includes('client')).length },
    { id: 'court',      label: 'Court',           count: data.emailThreads.filter(e => e.labels.includes('court')).length },
    { id: 'opposing',   label: 'Opposing counsel', count: data.emailThreads.filter(e => e.labels.includes('opposing-counsel')).length },
    { id: 'all',        label: 'All mail',        count: data.emailThreads.length },
  ];

  const filtered = useCmInboxMemo(() => {
    let list = data.emailThreads;
    if (folder === 'starred')      list = list.filter(e => e.starred);
    else if (folder === 'privileged') list = list.filter(e => e.sensitivity === 'privileged');
    else if (folder === 'encrypted') list = list.filter(e => e.encrypted);
    else if (folder === 'attachments') list = list.filter(e => e.hasAttachments);
    else if (folder === 'client')   list = list.filter(e => e.labels.includes('client'));
    else if (folder === 'court')    list = list.filter(e => e.labels.includes('court'));
    else if (folder === 'opposing') list = list.filter(e => e.labels.includes('opposing-counsel'));
    else if (folder === 'inbox')    list = list; // all
    if (query) {
      const q = query.toLowerCase();
      list = list.filter(e =>
        e.subject.toLowerCase().includes(q) ||
        e.from.toLowerCase().includes(q) ||
        e.snippet.toLowerCase().includes(q)
      );
    }
    return list;
  }, [folder, query]);

  const current = data.emailThreads.find(e => e.id === selected) || filtered[0];

  const sensitivityPill = (s) => {
    const map = {
      privileged:  { label: ' Privileged',  kind: 'e2ee' },
      confidential:{ label: ' Confidential',kind: 'warn' },
      internal:    { label: 'Internal',       kind: 'info' },
      public:      { label: 'Public',         kind: 'pending' },
    };
    return map[s] || map.internal;
  };

  // Render a single thread message (synthesized from snippet)
  const renderThreadMessages = (thread) => {
    const count = Math.min(thread.count, 3);
    const msgs = [];
    for (let i = 0; i < count; i++) {
      msgs.push({
        id: `${thread.id}-m${i}`,
        from: i === 0 ? thread.from : (i % 2 === 0 ? thread.to[0] : thread.from),
        ts: new Date(new Date(thread.ts).getTime() - (count - i - 1) * 3600 * 1000).toISOString(),
        body: i === count - 1
          ? thread.snippet + '\n\nBest regards,\n' + thread.from.split('@')[0].replace(/\./g, ' ')
          : '…earlier message in thread (content omitted for preview)',
        isLatest: i === count - 1,
      });
    }
    return msgs;
  };

  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '200px 340px 1fr',
      gap: '0',
      height: 'calc(100vh - 280px)', minHeight: '560px',
      border: `1px solid ${Tc.color.border.light}`,
      borderRadius: Tc.radius.lg, overflow: 'hidden',
      background: Tc.color.bg.card,
    }}>
      {/* FOLDER LIST */}
      <div style={{ borderRight: `1px solid ${Tc.color.border.light}`, background: Tc.color.bg.secondary, display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '12px', borderBottom: `1px solid ${Tc.color.border.light}`, background: Tc.color.bg.card }}>
          <button style={{ ...cm.btnPrimary, width: '100%' }}>+ Compose</button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 0' }}>
          {folders.map(f => (
            <button key={f.id} onClick={() => setFolder(f.id)} style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              width: '100%', padding: '7px 14px', border: 'none',
              background: folder === f.id ? 'rgba(13,148,136,0.12)' : 'transparent',
              borderLeft: folder === f.id ? `3px solid #0F766E` : '3px solid transparent',
              cursor: 'pointer', fontFamily: Tc.font.family,
            }}>
              <span style={{ fontSize: '12px', fontWeight: folder === f.id ? 700 : 500, color: Tc.color.text.primary }}>{f.label}</span>
              <span style={{ fontSize: '10px', color: Tc.color.text.tertiary, fontFamily: Tc.font.mono }}>{f.count}</span>
            </button>
          ))}
        </div>
      </div>

      {/* THREAD LIST */}
      <div style={{ borderRight: `1px solid ${Tc.color.border.light}`, display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '10px 12px', borderBottom: `1px solid ${Tc.color.border.light}`, background: Tc.color.bg.card }}>
          <input
            style={{ ...cm.input, fontSize: '11px' }}
            placeholder="Search mail…"
            value={query}
            onChange={e => setQuery(e.target.value)}
          />
        </div>
        <div style={{ flex: 1, overflowY: 'auto' }}>
          {filtered.length === 0 ? (
            <div style={{ padding: '40px 20px', textAlign: 'center', color: Tc.color.text.tertiary, fontSize: '12px' }}>No messages.</div>
          ) : filtered.map(e => {
            const active = current && current.id === e.id;
            const sens = sensitivityPill(e.sensitivity);
            return (
              <button key={e.id} onClick={() => setSelected(e.id)} style={{
                width: '100%', textAlign: 'left', border: 'none', cursor: 'pointer',
                background: active ? 'rgba(13,148,136,0.08)' : 'transparent',
                borderLeft: active ? `3px solid #0F766E` : '3px solid transparent',
                borderBottom: `1px solid ${Tc.color.border.light}`,
                padding: '10px 14px', fontFamily: Tc.font.family,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '3px' }}>
                  <span style={{ fontSize: '11px', fontWeight: e.unread ? 700 : 500, color: Tc.color.text.primary, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {e.from.split('@')[0].replace(/\./g, ' ')}
                  </span>
                  {e.starred && <span style={{ color: '#D97706', fontSize: '11px' }}><Icons.Star size={11}/></span>}
                  <span style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>{cm.formatTime(e.ts)}</span>
                </div>
                <div style={{ fontSize: '12px', fontWeight: e.unread ? 700 : 500, color: Tc.color.text.primary, marginBottom: '3px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {e.subject}
                  {e.count > 1 && <span style={{ color: Tc.color.text.tertiary, fontWeight: 500, marginLeft: '4px' }}>({e.count})</span>}
                </div>
                <div style={{ fontSize: '11px', color: Tc.color.text.tertiary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginBottom: '4px' }}>
                  {e.snippet}
                </div>
                <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>
                  <span style={{ ...cm.tag, ...cm.statusPill(sens.kind), fontSize: '9px' }}>{sens.label}</span>
                  {e.encrypted && <span style={{ ...cm.tag, ...cm.statusPill('e2ee'), fontSize: '9px' }}> E2EE</span>}
                  {e.hasAttachments && <span style={{ ...cm.tag, background: Tc.color.bg.secondary, color: Tc.color.text.tertiary, fontSize: '9px' }}> {e.attachments}</span>}
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* THREAD DETAIL */}
      <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        {current ? (
          <>
            <div style={{ padding: '14px 20px', borderBottom: `1px solid ${Tc.color.border.light}`, flexShrink: 0, background: Tc.color.bg.card }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '12px' }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: '16px', fontWeight: 700, color: Tc.color.text.primary, marginBottom: '4px' }}>
                    {current.subject}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap' }}>
                    <span style={{ ...cm.tag, ...cm.statusPill(sensitivityPill(current.sensitivity).kind) }}>
                      {sensitivityPill(current.sensitivity).label}
                    </span>
                    {current.encrypted && <CmLockChip text="End-to-end encrypted" size="sm" />}
                    {current.labels.map(l => (
                      <span key={l} style={{ ...cm.tag, background: Tc.color.bg.secondary, color: Tc.color.text.secondary }}>{l}</span>
                    ))}
                  </div>
                </div>
                <div style={{ display: 'flex', gap: '4px', flexShrink: 0 }}>
                  <button style={cm.btnSecondary}>Reply</button>
                  <button style={cm.btnSecondary}>Reply all</button>
                  <button style={cm.btnSecondary}>Forward</button>
                  <button style={cm.btnGhost} title="Star"><Icons.Star size={11}/></button>
                  <button style={cm.btnGhost} title="Archive"></button>
                </div>
              </div>
            </div>

            <div style={{ flex: 1, overflowY: 'auto', padding: '16px 20px', background: Tc.color.bg.primary }}>
              {renderThreadMessages(current).map((m, idx) => (
                <div key={m.id} style={{
                  padding: '14px 16px', marginBottom: '10px',
                  background: Tc.color.bg.card, border: `1px solid ${Tc.color.border.light}`,
                  borderRadius: Tc.radius.md,
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
                    <div>
                      <div style={{ fontSize: '12px', fontWeight: 700, color: Tc.color.text.primary }}>
                        {m.from.split('@')[0].replace(/\./g, ' ')}
                        <span style={{ fontWeight: 400, color: Tc.color.text.tertiary, marginLeft: '6px' }}>&lt;{m.from}&gt;</span>
                      </div>
                      <div style={{ fontSize: '10px', color: Tc.color.text.tertiary, marginTop: '2px' }}>
                        to {current.to.join(', ')}
                        {current.cc.length > 0 && ` · cc ${current.cc.join(', ')}`}
                      </div>
                    </div>
                    <div style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>{new Date(m.ts).toLocaleString()}</div>
                  </div>
                  <div style={{ fontSize: '12px', color: Tc.color.text.primary, lineHeight: 1.65, whiteSpace: 'pre-wrap' }}>
                    {m.body}
                  </div>
                  {m.isLatest && current.hasAttachments && (
                    <div style={{ marginTop: '12px', paddingTop: '12px', borderTop: `1px solid ${Tc.color.border.light}` }}>
                      <div style={{ ...cm.sectionLabel, marginBottom: '6px' }}>Attachments ({current.attachments})</div>
                      <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                        {Array.from({ length: current.attachments }).map((_, i) => (
                          <div key={i} style={{
                            display: 'inline-flex', alignItems: 'center', gap: '8px',
                            padding: '8px 10px', border: `1px solid ${Tc.color.border.light}`,
                            borderRadius: '6px', background: Tc.color.bg.secondary,
                          }}>
                            <span style={{ fontSize: '16px' }}></span>
                            <div>
                              <div style={{ fontSize: '11px', fontWeight: 600, color: Tc.color.text.primary }}>attachment-{i+1}.pdf</div>
                              <div style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>{(Math.random() * 2 + 0.1).toFixed(1)} MB {current.encrypted && '· '}</div>
                            </div>
                            <button style={cm.btnGhost}>↓</button>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              ))}
              {/* Matter-link bar */}
              {current.labels.find(l => l.startsWith('matter:')) && (
                <div style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '10px',
                  padding: '10px 14px', background: cm.cipherBg,
                  border: `1px solid ${cm.cipherBorder}`, borderRadius: Tc.radius.md,
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <span></span>
                    <span style={{ fontSize: '11px', color: Tc.color.text.secondary }}>
                      Linked to matter <strong style={{ color: '#0F766E' }}>{current.labels.find(l => l.startsWith('matter:')).split(':')[1]}</strong>
                    </span>
                  </div>
                  <button style={cm.btnGhost}>Open matter →</button>
                </div>
              )}
            </div>

            {/* Inline reply bar */}
            <div style={{ padding: '10px 20px 14px', borderTop: `1px solid ${Tc.color.border.light}`, flexShrink: 0, background: Tc.color.bg.card }}>
              <div style={{
                padding: '10px 14px', border: `1px solid ${Tc.color.border.medium}`,
                borderRadius: Tc.radius.md, background: Tc.color.bg.card,
                display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '10px',
              }}>
                <span style={{ fontSize: '12px', color: Tc.color.text.tertiary }}>Click to reply…</span>
                <div style={{ display: 'flex', gap: '6px' }}>
                  <button style={cm.btnSecondary}>Reply</button>
                  <button style={cm.btnSecondary}>Reply with E2EE</button>
                </div>
              </div>
            </div>
          </>
        ) : (
          <div style={{ padding: '60px 20px', textAlign: 'center', color: Tc.color.text.tertiary, fontSize: '12px' }}>
            Select a message to read.
          </div>
        )}
      </div>
    </div>
  );
}

window.CommsInbox = CommsInbox;
