// Desktop Messages panel — right-side drawer like the screenshot reference.
// Mirrors the mobile chat list style but in the desktop chrome.

const CHAT_PANEL_W = 360;

const DESKTOP_CHATS = [
  { name: 'Aishwarya Iyer',  initials: 'AI', bg: '#EF4444', avatar: 'https://i.pravatar.cc/80?img=49', preview: 'Tap to chat',                  time: 'Apr 24', conn: 'internet', online: true,  badge: 'HTTP' },
  { name: 'Rohan Sharma',    initials: 'RS', bg: '#F472B6', avatar: 'https://i.pravatar.cc/80?img=12', preview: 'sent you the deck',           time: 'Mon',    conn: 'internet', online: true,  unread: 1 },
  { name: 'Priya Nair',      initials: 'PN', bg: '#22D3EE', avatar: 'https://i.pravatar.cc/80?img=47', preview: 'sounds good, let me check', time: 'Apr 18', conn: 'ble',      online: true,  unread: 2 },
  { name: 'Arjun Mehta',     initials: 'AM', bg: '#6EE7B7', avatar: 'https://i.pravatar.cc/80?img=14', preview: 'on it 👍',                     time: 'Apr 16', conn: 'internet', online: true },
  { name: 'Dimitri Volkov',  initials: 'DV', bg: '#FBBF24', avatar: 'https://i.pravatar.cc/80?img=33', preview: 'merged the PR',               time: 'Apr 14', conn: 'internet', online: false },
  { name: 'Dave Thompson',   initials: 'DT', bg: '#A78BFA', avatar: 'https://i.pravatar.cc/80?img=15', preview: 'shared a file · brief.pdf',   time: 'Apr 12', conn: 'internet', online: true },
  { name: 'Amara Okonkwo',   initials: 'AO', bg: '#60A5FA', avatar: 'https://i.pravatar.cc/80?img=44', preview: 'see you tomorrow',            time: 'Apr 09', conn: 'internet', online: false },
  { name: 'Mei Tanaka',      initials: 'MT', bg: '#F87171', avatar: 'https://i.pravatar.cc/80?img=20', preview: 'Thanks! Talk soon 👋',         time: 'Apr 04', conn: 'internet', online: false },
];

function ConnChip({ type }) {
  const meta = {
    internet: { label: 'Internet', color: '#60A5FA' },
    ble:      { label: 'BLE',      color: '#A78BFA' },
    mesh:     { label: 'Mesh',     color: '#6EE7B7' },
    mediator: { label: 'Mediator', color: '#FBBF24' },
  }[type] || null;
  if (!meta) return null;
  return (
    <span style={{
      fontSize: 9, fontWeight: 600, padding: '1px 5px', borderRadius: 3,
      color: meta.color, background: meta.color + '22',
      letterSpacing: '0.06em', textTransform: 'uppercase',
      fontFamily: 'JetBrains Mono, monospace',
    }}>{meta.label}</span>
  );
}

function ChatPanel({ open, onClose, onStartCall }) {
  const [active, setActive] = React.useState(null);
  if (!open) return null;

  return (
    <aside className="glass" style={{
      width: CHAT_PANEL_W, height: '100%', flexShrink: 0,
      borderRadius: 14, overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
      fontFamily: 'Inter, system-ui, sans-serif',
      animation: 'chatSlide 220ms cubic-bezier(0.2,0.8,0.2,1)',
    }}>
      <style>{`@keyframes chatSlide { from { transform: translateX(20px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }`}</style>

      {active ? (
        <ChatThread peer={active} onBack={() => setActive(null)} onClose={onClose} onStartCall={onStartCall}/>
      ) : (
        <ChatList onOpen={setActive} onClose={onClose}/>
      )}
    </aside>
  );
}

function ChatList({ onOpen, onClose }) {
  return (
    <>
      {/* header */}
      <div style={{
        padding: '14px 16px', borderBottom: '1px solid var(--border-soft)',
        display: 'flex', alignItems: 'center', gap: 10, background: 'var(--bg-elev)',
      }}>
        <span style={{ fontSize: 13.5, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.01em' }}>Messages</span>
        <span style={{ fontSize: 10, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace' }}>· {DESKTOP_CHATS.length}</span>
        <div style={{ flex: 1 }}/>
        <button title="Settings" style={iconBtnSm()}><Ic.settings s={13}/></button>
        <button title="Search" style={iconBtnSm()}><Ic.search s={13}/></button>
        <button title="Refresh" style={iconBtnSm()}><Ic.reload s={13}/></button>
        <button title="New chat" style={iconBtnSm()}><Ic.plus s={13}/></button>
        <button onClick={onClose} title="Close" style={iconBtnSm()}><Ic.x s={13}/></button>
      </div>

      {/* search */}
      <div style={{ padding: '10px 14px 8px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '7px 10px', background: 'var(--bg-elev)',
          border: '1px solid var(--border-soft)', borderRadius: 8,
          color: 'var(--fg-dim)', fontSize: 12,
        }}>
          <Ic.search s={12}/>
          <span style={{ flex: 1 }}>Search messages…</span>
        </div>
      </div>

      {/* list */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '0 6px 14px' }}>
        {DESKTOP_CHATS.map((c, i) => (
          <button key={i} onClick={() => onOpen(c)} style={{
            width: '100%', display: 'flex', alignItems: 'center', gap: 11,
            padding: '11px 10px', borderRadius: 10,
            background: 'transparent', border: 0, cursor: 'pointer',
            color: 'var(--fg)', textAlign: 'left',
          }}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--hover)'}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
          >
            <div style={{ position: 'relative', flexShrink: 0 }}>
              <div style={{
                width: 38, height: 38, borderRadius: 19, background: c.bg,
                display: 'grid', placeItems: 'center', color: '#fff',
                fontSize: 13, fontWeight: 700, fontFamily: 'Geist, Inter, sans-serif',
                boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.06)',
                overflow: 'hidden', position: 'relative',
              }}>
                <span style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>{c.initials}</span>
                {c.avatar && (
                  <img src={c.avatar} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} onError={e => { e.currentTarget.style.display = 'none'; }}/>
                )}
              </div>
              {c.online && <div style={{ position: 'absolute', bottom: 0, right: 0, width: 10, height: 10, borderRadius: 5, background: '#22D27A', border: '2px solid var(--bg)' }}/>}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flex: 1 }}>{c.name}</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3 }}>
                <span style={{ fontSize: 11.5, color: c.unread ? 'var(--fg)' : 'var(--fg-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontWeight: c.unread ? 500 : 400, flex: 1, minWidth: 0 }}>{c.preview}</span>
                {c.badge && <ConnChip type="internet"/>}
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4, flexShrink: 0 }}>
              {c.badge && (
                <span style={{
                  fontSize: 9, fontWeight: 600, padding: '1px 5px', borderRadius: 3,
                  color: '#60A5FA', background: '#60A5FA22',
                  letterSpacing: '0.06em', textTransform: 'uppercase',
                  fontFamily: 'JetBrains Mono, monospace',
                }}>{c.badge}</span>
              )}
              <span style={{ fontSize: 10, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace' }}>{c.time}</span>
              {c.unread > 0 && <span style={{ minWidth: 16, height: 16, padding: '0 4px', borderRadius: 8, background: 'var(--accent-b)', color: '#0B0C0F', fontSize: 9.5, fontWeight: 700, display: 'grid', placeItems: 'center' }}>{c.unread}</span>}
            </div>
          </button>
        ))}
      </div>

      {/* footer status */}
      <div style={{
        padding: '10px 16px', borderTop: '1px solid var(--border-soft)',
        display: 'flex', alignItems: 'center', gap: 8,
        fontSize: 10.5, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace',
        background: 'var(--bg-elev)',
      }}>
        <span style={{ width: 6, height: 6, borderRadius: 3, background: '#22D27A', boxShadow: '0 0 6px #22D27A' }}/>
        <span>Mediator online · 1 route</span>
        <span style={{ flex: 1 }}/>
        <span>BLE · 3 peers</span>
      </div>
    </>
  );
}

function ChatThread({ peer, onBack, onClose, onStartCall }) {
  const [input, setInput] = React.useState('');
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [profileOpen, setProfileOpen] = React.useState(false);
  const [muted, setMuted] = React.useState(false);
  const [disappearing, setDisappearing] = React.useState(false);
  const [messages, setMessages] = React.useState([
    { from: 'them', text: 'Tap to chat', time: '11:13 PM' },
  ]);
  const send = () => {
    const t = input.trim();
    if (!t) return;
    setInput('');
    setMessages(m => [...m, { from: 'me', text: t, time: 'now' }]);
    setTimeout(() => {
      setMessages(m => [...m, { from: 'them', text: 'Got it — routing through HTTP mediator.', time: 'now' }]);
    }, 500);
  };
  if (profileOpen) return <DContactProfile peer={peer} muted={muted} setMuted={setMuted} disappearing={disappearing} setDisappearing={setDisappearing} onClose={() => setProfileOpen(false)} onStartCall={onStartCall}/>;
  return (
    <>
      <div style={{
        padding: '11px 14px', borderBottom: '1px solid var(--border-soft)',
        display: 'flex', alignItems: 'center', gap: 10, background: 'var(--bg-elev)', position: 'relative',
      }}>
        <button onClick={onBack} style={iconBtnSm()}><Ic.back s={14}/></button>
        <div style={{
          width: 30, height: 30, borderRadius: 15, background: peer.bg,
          display: 'grid', placeItems: 'center', color: '#fff',
          fontSize: 11, fontWeight: 700, fontFamily: 'Geist, Inter, sans-serif',
          overflow: 'hidden', position: 'relative', flexShrink: 0,
        }}>
          <span style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>{peer.initials}</span>
          {peer.avatar && (
            <img src={peer.avatar} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} onError={e => { e.currentTarget.style.display = 'none'; }}/>
          )}
        </div>
        <div onClick={() => setProfileOpen(true)} style={{ flex: 1, minWidth: 0, cursor: 'pointer' }}>
          <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{peer.name}</div>
          <div style={{ fontSize: 10, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', marginTop: 1, display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: peer.online ? '#22D27A' : 'var(--fg-dim)' }}/>
            {peer.online ? 'online' : 'offline'} · via {peer.conn}
          </div>
        </div>
        <button onClick={() => { onStartCall && onStartCall(peer, 'audio'); }} title="Audio call" style={iconBtnSm()}><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg></button>
        <button onClick={() => { onStartCall && onStartCall(peer, 'video'); }} title="Video call" style={iconBtnSm()}><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="m23 7-7 5 7 5z"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg></button>
        <div style={{ position: 'relative' }}>
          <button onClick={() => setMenuOpen(m => !m)} title="More" style={iconBtnSm()}><Ic.more s={14}/></button>
          {menuOpen && <DChatOptionsMenu peer={peer} muted={muted} setMuted={setMuted} disappearing={disappearing} setDisappearing={setDisappearing} onClose={() => setMenuOpen(false)} onViewProfile={() => { setMenuOpen(false); setProfileOpen(true); }} onStartCall={onStartCall}/>}
        </div>
        <button onClick={onClose} style={iconBtnSm()}><Ic.x s={13}/></button>
      </div>

      <div style={{ flex: 1, padding: '14px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {messages.map((m, i) => (
          <div key={i} style={{
            alignSelf: m.from === 'me' ? 'flex-end' : 'flex-start',
            maxWidth: '80%', padding: '8px 11px', borderRadius: 12,
            background: m.from === 'me' ? 'linear-gradient(135deg, var(--accent-a), var(--accent-b))' : 'var(--bg-elev)',
            color: m.from === 'me' ? '#0B0C0F' : 'var(--fg)',
            fontSize: 12.5, lineHeight: 1.4, fontWeight: m.from === 'me' ? 500 : 400,
            border: m.from === 'me' ? 0 : '1px solid var(--border-soft)',
          }}>
            {m.text}
            <div style={{ fontSize: 9.5, opacity: 0.7, marginTop: 3, fontFamily: 'JetBrains Mono, monospace' }}>{m.time}</div>
          </div>
        ))}
      </div>

      <div style={{ padding: '10px 14px 14px', borderTop: '1px solid var(--border-soft)', background: 'var(--bg-elev)' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '8px 12px', background: 'var(--bg)',
          border: '1px solid var(--border-soft)', borderRadius: 12,
        }}>
          <input
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && send()}
            placeholder="Message…"
            style={{ flex: 1, background: 'transparent', border: 0, outline: 0, color: 'var(--fg)', fontSize: 12.5, fontFamily: 'inherit' }}
          />
          <button onClick={send} disabled={!input.trim()} style={{
            width: 26, height: 26, borderRadius: 8,
            background: input.trim() ? 'var(--accent-b)' : 'var(--bg-elev-2)',
            color: input.trim() ? '#0B0C0F' : 'var(--fg-dim)',
            border: 0, cursor: input.trim() ? 'pointer' : 'default',
            display: 'grid', placeItems: 'center', flexShrink: 0,
          }}><Ic.arrowRight s={12}/></button>
        </div>
      </div>
    </>
  );
}

function iconBtnSm() {
  return {
    width: 24, height: 24, borderRadius: 6,
    background: 'transparent', border: 0, cursor: 'pointer',
    color: 'var(--fg-muted)', display: 'grid', placeItems: 'center', padding: 0,
  };
}

// ── Desktop chat ⋯ menu (dropdown from header) ─────────────────
function DTog({ on, onChange }) {
  return (
    <button onClick={e => { e.stopPropagation(); onChange(); }} style={{ width: 36, height: 20, borderRadius: 10, padding: 0, flexShrink: 0, position: 'relative', background: on ? 'var(--accent-grad)' : 'var(--bg-elev-2)', border: '1px solid ' + (on ? 'transparent' : 'var(--border)'), cursor: 'pointer' }}>
      <span style={{ position: 'absolute', top: 2, left: on ? 17 : 2, width: 15, height: 15, borderRadius: 8, background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,0.3)', transition: 'left 160ms' }}/>
    </button>
  );
}

function DChatRow({ icon, label, sub, right, onClick, danger, accent }) {
  const sw = (d) => <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">{d}</svg>;
  return (
    <button onClick={onClick} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 11, padding: '9px 10px', borderRadius: 8, background: 'transparent', border: 0, color: danger ? '#F87171' : 'var(--fg)', textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit' }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--hover)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
      <span style={{ width: 18, display: 'grid', placeItems: 'center', color: danger ? '#F87171' : accent ? 'var(--accent-a)' : 'var(--fg-muted)', flexShrink: 0 }}>{typeof icon === 'string' ? sw(icon) : icon}</span>
      <span style={{ flex: 1 }}><span style={{ display: 'block', fontSize: 13, fontWeight: 500, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.01em' }}>{label}</span>{sub && <span style={{ display: 'block', fontSize: 10.5, color: 'var(--fg-dim)', marginTop: 1 }}>{sub}</span>}</span>
      {right}
    </button>
  );
}

function DChatOptionsMenu({ peer, muted, setMuted, disappearing, setDisappearing, onClose, onViewProfile, onStartCall }) {
  const sw = (d) => <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">{d}</svg>;
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 80 }}/>
      <div className="glass" style={{ position: 'absolute', top: 30, right: 0, zIndex: 81, width: 252, borderRadius: 12, padding: 6, animation: 'dcmIn 160ms ease-out' }}>
        <style>{`@keyframes dcmIn{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:none}}`}</style>
        <DChatRow icon={sw(<><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-6 8-6s8 2 8 6"/></>)} label="View profile" onClick={onViewProfile}/>
        <DChatRow icon={sw(<><circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/></>)} label="Search in chat" onClick={onClose}/>
        <div style={{ height: 1, background: 'var(--border-soft)', margin: '6px 8px' }}/>
        <DChatRow icon={sw(<><path d="M6 8a6 6 0 1 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 21a2 2 0 0 0 4 0"/></>)} label="Mute notifications" right={<DTog on={muted} onChange={() => setMuted(m => !m)}/>}/>
        <DChatRow icon={sw(<><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>)} label="Disappearing messages" sub={disappearing ? 'After 24 hours' : 'Off'} right={<DTog on={disappearing} onChange={() => setDisappearing(d => !d)}/>}/>
        <DChatRow icon={sw(<><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></>)} label="Media, links & files" sub="48 photos · 12 files" onClick={onClose}/>
        <div style={{ height: 1, background: 'var(--border-soft)', margin: '6px 8px' }}/>
        <DChatRow icon={sw(<><path d="M12 2 4 5v7c0 5 3.5 8.5 8 10 4.5-1.5 8-5 8-10V5z"/><path d="m9 12 2 2 4-4"/></>)} accent label="Verify security code" onClick={onViewProfile}/>
        <DChatRow icon={sw(<><circle cx="12" cy="12" r="9"/><path d="M9 12h6"/></>)} danger label="Block contact" onClick={onClose}/>
        <DChatRow icon={sw(<><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/></>)} danger label="Clear chat" onClick={onClose}/>
      </div>
    </>
  );
}

// ── Desktop contact profile (fills the chat panel) ─────────────
function DContactProfile({ peer, muted, setMuted, disappearing, setDisappearing, onClose, onStartCall }) {
  const sw = (d, s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">{d}</svg>;
  const conn = peer.conn === 'ble' ? 'Bluetooth mesh' : peer.conn === 'mesh' ? 'Ajna mesh' : 'DIDComm · Internet';
  const init = (peer.initials || (peer.name || 'XX').split(' ').map(x => x[0]).join('')).toUpperCase();
  const code = ['48201', '93517', '20846', '11759', '63092', '88410', '57231', '40198', '27514', '63820', '99471', '50384'];
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <div style={{ padding: '11px 14px', borderBottom: '1px solid var(--border-soft)', display: 'flex', alignItems: 'center', gap: 10, background: 'var(--bg-elev)' }}>
        <button onClick={onClose} style={iconBtnSm()}><Ic.back s={14}/></button>
        <div style={{ flex: 1, fontSize: 12.5, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.01em' }}>Contact</div>
        <button onClick={onClose} style={iconBtnSm()}><Ic.x s={13}/></button>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 16px 30px' }}>
        <div style={{ textAlign: 'center', marginBottom: 20 }}>
          <div style={{ width: 76, height: 76, borderRadius: 38, margin: '0 auto', background: peer.bg, position: 'relative', overflow: 'hidden', display: 'grid', placeItems: 'center', color: '#fff', fontWeight: 700, fontSize: 28, fontFamily: 'Geist, Inter, sans-serif' }}>
            <span style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>{init}</span>
            {peer.avatar && <img src={peer.avatar} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} onError={e => { e.currentTarget.style.display = 'none'; }}/>}
          </div>
          <div style={{ fontSize: 19, fontWeight: 700, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.025em', marginTop: 12 }}>{peer.name}</div>
          <div style={{ fontSize: 10.5, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', marginTop: 4 }}>did:peer:2.{init.toLowerCase()}…7Mq</div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 12, padding: '5px 12px', borderRadius: 999, background: 'color-mix(in oklch,#6EE7B7 12%,transparent)', color: '#6EE7B7', fontSize: 10, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>{sw(<path d="M12 2 4 5v7c0 5 3.5 8.5 8 10 4.5-1.5 8-5 8-10V5z"/>, 12)} Verified · {conn}</div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 8, marginBottom: 20 }}>
          {[['Message', sw(<path d="M3 6a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3h-5l-5 4v-4H6a3 3 0 0 1-3-3z"/>), onClose], ['Call', sw(<path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/>), () => onStartCall && onStartCall(peer, 'audio')], ['Video', sw(<><path d="m23 7-7 5 7 5z"/><rect x="1" y="5" width="15" height="14" rx="2"/></>), () => onStartCall && onStartCall(peer, 'video')], [muted ? 'Unmute' : 'Mute', sw(<><path d="M6 8a6 6 0 1 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 21a2 2 0 0 0 4 0"/></>), () => setMuted(m => !m)]].map(([l, ic, fn]) => (
            <button key={l} onClick={fn} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, padding: '12px 4px', background: 'var(--bg-elev)', border: '1px solid var(--border-soft)', borderRadius: 12, color: 'var(--fg)', cursor: 'pointer', fontFamily: 'inherit' }}><span style={{ color: 'var(--accent-b)' }}>{ic}</span><span style={{ fontSize: 10.5, fontWeight: 500 }}>{l}</span></button>
          ))}
        </div>
        <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--fg-dim)', letterSpacing: '0.12em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace', padding: '0 2px 6px', display: 'flex', justifyContent: 'space-between' }}><span>Safety number</span><span style={{ color: '#6EE7B7' }}>✓ Matches</span></div>
        <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border-soft)', borderRadius: 12, padding: 14, marginBottom: 18 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '8px 6px', marginBottom: 12 }}>{code.map((g, i) => <div key={i} style={{ fontSize: 12, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.04em', textAlign: 'center' }}>{g}</div>)}</div>
          <div style={{ display: 'flex', gap: 8 }}><button style={{ flex: 1, padding: '8px 0', borderRadius: 9, background: 'var(--bg-elev-2)', border: '1px solid var(--border-soft)', color: 'var(--fg)', fontSize: 12, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer' }}>Scan QR</button><button style={{ flex: 1, padding: '8px 0', borderRadius: 9, background: 'color-mix(in oklch,#6EE7B7 12%,transparent)', border: '1px solid color-mix(in oklch,#6EE7B7 28%,transparent)', color: '#6EE7B7', fontSize: 12, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer' }}>Mark verified</button></div>
        </div>
        <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border-soft)', borderRadius: 12, overflow: 'hidden', marginBottom: 18 }}>
          <DChatRow icon={sw(<><path d="M6 8a6 6 0 1 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 21a2 2 0 0 0 4 0"/></>)} label="Mute notifications" right={<DTog on={muted} onChange={() => setMuted(m => !m)}/>}/>
          <DChatRow icon={sw(<><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>)} label="Disappearing messages" sub={disappearing ? 'After 24 hours' : 'Off'} right={<DTog on={disappearing} onChange={() => setDisappearing(d => !d)}/>}/>
        </div>
        <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border-soft)', borderRadius: 12, overflow: 'hidden' }}>
          <DChatRow icon={sw(<><circle cx="12" cy="12" r="9"/><path d="M9 12h6"/></>)} danger label="Block contact"/>
          <DChatRow icon={sw(<path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/>)} danger label="Delete contact"/>
        </div>
      </div>
    </div>
  );
}

// Full-page Messages — list + thread, same data as the panel.
function MessagesPage({ onStartCall }) {
  const [peer, setPeer] = React.useState(null);
  return (
    <div style={{ height: '100%', display: 'flex', fontFamily: 'Inter, system-ui, sans-serif', color: 'var(--fg)' }}>
      <div style={{ width: 340, flexShrink: 0, borderRight: '1px solid var(--border-soft)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <ChatList onOpen={setPeer} onClose={() => {}}/>
      </div>
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        {peer ? (
          <ChatThread key={peer.name} peer={peer} onBack={() => setPeer(null)} onClose={() => setPeer(null)} onStartCall={onStartCall}/>
        ) : (
          <div style={{ flex: 1, display: 'grid', placeItems: 'center', textAlign: 'center', padding: 24 }}>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif' }}>Pick a conversation</div>
              <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 6, maxWidth: 300, lineHeight: 1.5 }}>
                Messages route peer-to-peer. Ajna AI can draft, summarize, or translate inside any thread.
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ChatPanel, ChatList, ChatThread, MessagesPage, DESKTOP_CHATS, CHAT_PANEL_W, DChatOptionsMenu, DContactProfile });
