function ChannelBadge({ channel }) {
  const colors = {
    WhatsApp: '#2bb741',
    Email: '#e5a22a',
    SMS: '#00a4b7',
  };

  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        borderRadius: 999,
        padding: '0.22rem 0.6rem',
        background: `${colors[channel] || '#003150'}16`,
        color: colors[channel] || '#003150',
        fontSize: '0.8rem',
        fontWeight: 700,
      }}
    >
      {channel}
    </span>
  );
}

function LastMessageDot({ fromMe }) {
  const color = fromMe ? '#e5a22a' : '#00a4b7';
  const label = fromMe ? 'Última mensagem enviada pelo atendimento' : 'Última mensagem enviada pelo cliente';

  return (
    <span
      title={label}
      aria-label={label}
      style={{
        width: 10,
        height: 10,
        borderRadius: 999,
        background: color,
        boxShadow: `0 0 0 3px ${color}22`,
        flex: '0 0 auto',
      }}
    />
  );
}

function UnreadBadge({ count }) {
  if (!count) return null;

  return (
    <span
      style={{
        width: 26,
        height: 26,
        borderRadius: '50%',
        background: 'var(--color-secondary)',
        color: '#fff',
        fontSize: '0.78rem',
        fontWeight: 800,
        display: 'inline-grid',
        placeItems: 'center',
        lineHeight: 1,
        flex: '0 0 auto',
      }}
    >
      {count > 99 ? '99+' : count}
    </span>
  );
}

function SavedContactLabel({ contact }) {
  const profile = contact.contactProfile;
  const hasSavedContact = Boolean(profile?.created_at || profile?.name || profile?.company || profile?.note);
  if (!hasSavedContact) return null;

  return (
    <span
      title="Contato salvo na agenda"
      style={{
        color: '#b7791f',
        flex: '0 0 auto',
        fontSize: '0.72rem',
        fontWeight: 800,
        lineHeight: 1,
      }}
    >
       •Salvo•
    </span>
  );
}

const CHAT_LIST_HEIGHT = 'min(760px, calc(100vh - 160px))';

export function ChatConversationList({
  contacts,
  activeContactId,
  onSelectContact,
  onOpenContact,
  isMobile = false,
}) {
  return (
    <aside
      style={{
        background: '#fff',
        border: '1px solid var(--color-border)',
        borderRadius: '28px',
        padding: '1rem',
        display: 'grid',
        gridTemplateRows: 'auto minmax(0, 1fr)',
        gap: '0.85rem',
        height: isMobile ? 'auto' : CHAT_LIST_HEIGHT,
        maxHeight: isMobile ? 'none' : CHAT_LIST_HEIGHT,
        alignSelf: 'start',
        minHeight: 0,
      }}
    >
      <div>
        <strong style={{ display: 'block', fontSize: '1.08rem' }}>Conversas ativas</strong>
        <span style={{ color: 'var(--color-text-soft)' }}>
          WhatsApp, SMS e e-mail em uma fila visual.
        </span>
      </div>

      <div
        style={{
          display: 'grid',
          gap: '0.75rem',
          gridTemplateColumns: isMobile ? '1fr' : '1fr',
          gridAutoRows: 'max-content',
          alignContent: 'start',
          overflowY: 'auto',
          minHeight: 0,
          paddingRight: '0.15rem',
        }}
      >
        {contacts.map((contact) => {
          const isActive = contact.id === activeContactId;

          return (
            <button
              key={contact.id}
              type="button"
              onClick={() => onSelectContact(contact.id)}
              onContextMenu={(event) => {
                event.preventDefault();
                onSelectContact(contact.id);
                onOpenContact?.(contact);
              }}
              style={{
                border: '1px solid',
                borderColor: isActive ? 'rgba(0, 164, 183, 0.26)' : 'var(--color-border)',
                background: isActive ? 'rgba(0, 164, 183, 0.08)' : '#fff',
                borderRadius: '20px',
                padding: '1rem',
                textAlign: 'left',
                display: 'grid',
                gap: '0.6rem',
              }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', gap: '1rem' }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.5rem', minWidth: 0 }}>
                  <LastMessageDot fromMe={contact.lastMessageFromMe} />
                  <strong style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {contact.name}
                  </strong>
                </span>
                <span style={{ fontSize: '0.82rem', color: 'var(--color-text-soft)' }}>
                  {contact.time}
                </span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', gap: '0.75rem' }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.45rem', minWidth: 0 }}>
                  <ChannelBadge channel={contact.channel} />
                  <SavedContactLabel contact={contact} />
                </span>
                <UnreadBadge count={contact.unread} />
              </div>
              <span style={{ color: 'var(--color-text-soft)' }}>{contact.preview}</span>
            </button>
          );
        })}

        {contacts.length === 0 ? (
          <div
            style={{
              border: '1px solid var(--color-border)',
              borderRadius: '18px',
              padding: '1rem',
              background: 'rgba(0, 49, 80, 0.04)',
              color: 'var(--color-text-soft)',
              fontWeight: 700,
              lineHeight: 1.45,
            }}
          >
            Nenhuma conversa ativa na sua fila. Conversas em triagem do Omnino aparecem aqui depois de classificadas.
          </div>
        ) : null}
      </div>
    </aside>
  );
}
