/* global React, Icon, Badge, Button */

// ─── Mensagens Module — Widgets & Utilities ─────────────────────────────────
// Shared constants, status helpers, and small reusable components.
// ─────────────────────────────────────────────────────────────────────────────

// ─── Constants ──────────────────────────────────────────────────────────────

const MSG_CANAIS_INFO = {
  whatsapp:  { nome: 'WhatsApp',           icon: 'message-circle', color: '#25D366' },
  instagram: { nome: 'Instagram Direct',   icon: 'instagram',      color: '#E4405F' },
  facebook:  { nome: 'Facebook Messenger', icon: 'facebook',       color: '#1877F2' },
  email:     { nome: 'E-mail',             icon: 'mail',           color: '#C9A36B' },
  mercadolivre: { nome: 'Mercado Livre',   icon: 'shopping-bag',   color: '#FFE600' },
};

const AGENTE_TIPOS = [
  { value: 'sac',       label: 'SAC (Atendimento)', icon: 'headphones', color: '#4EA8DE' },
  { value: 'vendas',    label: 'Vendas',            icon: 'shopping-cart', color: '#5BB17A' },
  { value: 'pos_venda', label: 'Pós-venda',         icon: 'package',    color: '#C9A36B' },
  { value: 'custom',    label: 'Personalizado',     icon: 'bot',        color: '#A78BFA' },
];

const MODELOS_IA = [
  { value: 'claude-sonnet-4-20250514', label: 'Claude Sonnet 4 (Recomendado)' },
  { value: 'claude-haiku-4-20250514',  label: 'Claude Haiku 4 (Mais rápido)' },
];

const MSG_STATUS_TONE = {
  'Aberta':    'info',
  'Fechada':   'neutral',
  'Aguardando':'warning',
  'Resolvida': 'success',
  'Escalada':  'danger',
};

const PRIORIDADE_TONE = {
  'baixa':   'neutral',
  'normal':  'info',
  'alta':    'warning',
  'urgente': 'danger',
};

const TEMPLATE_CATEGORIAS = ['geral', 'sac', 'vendas', 'pos_venda', 'cobranca', 'promocao'];

// ─── Utility Functions ──────────────────────────────────────────────────────

function timeAgo(isoDate) {
  if (!isoDate) return '';
  const now = new Date();
  const date = new Date(isoDate);
  const diffMs = now - date;
  const diffMin = Math.floor(diffMs / 60000);
  const diffH = Math.floor(diffMin / 60);
  const diffD = Math.floor(diffH / 24);

  if (diffMin < 1) return 'agora';
  if (diffMin < 60) return `${diffMin}min`;
  if (diffH < 24) return `${diffH}h`;
  if (diffD < 7) return `${diffD}d`;
  return date.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' });
}

function formatPhone(phone) {
  if (!phone) return '';
  const clean = phone.replace(/\D/g, '');
  if (clean.length === 13) { // 55 11 99999-9999
    return `+${clean.slice(0,2)} (${clean.slice(2,4)}) ${clean.slice(4,9)}-${clean.slice(9)}`;
  }
  if (clean.length === 12) { // 55 11 9999-9999
    return `+${clean.slice(0,2)} (${clean.slice(2,4)}) ${clean.slice(4,8)}-${clean.slice(8)}`;
  }
  if (clean.length === 11) { // 11 99999-9999
    return `(${clean.slice(0,2)}) ${clean.slice(2,7)}-${clean.slice(7)}`;
  }
  return phone;
}

// ─── Small Components ───────────────────────────────────────────────────────

function CanalBadge({ canal }) {
  const info = MSG_CANAIS_INFO[(canal || 'whatsapp').toLowerCase()] || MSG_CANAIS_INFO.whatsapp;
  return (
    <span className="ch-chip" style={{ fontSize: 10.5, padding: '2px 8px', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: info.color }} />
      {info.nome}
    </span>
  );
}

function AgenteIndicator({ ativo, tipo }) {
  if (!ativo) return null;
  const info = AGENTE_TIPOS.find(a => a.value === tipo) || AGENTE_TIPOS[0];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      fontSize: 10, fontWeight: 600, padding: '2px 6px',
      borderRadius: 4, background: info.color + '18', color: info.color,
    }}>
      <Icon name="bot" size={10} />IA {info.label}
    </span>
  );
}

function PrioridadeBadge({ prioridade }) {
  const p = prioridade || 'normal';
  const tone = PRIORIDADE_TONE[p] || 'info';
  if (p === 'normal') return null;
  return <Badge tone={tone} style={{ fontSize: 10 }}>{p.charAt(0).toUpperCase() + p.slice(1)}</Badge>;
}

function MsgStatusBadge({ status }) {
  const tone = MSG_STATUS_TONE[status] || 'neutral';
  return <Badge tone={tone}>{status || 'Aberta'}</Badge>;
}

function ConvAvatar({ nome, canal, size }) {
  const s = size || 40;
  const info = MSG_CANAIS_INFO[(canal || 'whatsapp').toLowerCase()] || MSG_CANAIS_INFO.whatsapp;
  const initial = (nome || '?')[0].toUpperCase();
  return (
    <div style={{ position: 'relative', width: s, height: s, flex: 'none' }}>
      <div className="avatar" style={{ width: s, height: s, fontSize: s * 0.4 }}>{initial}</div>
      <span style={{
        position: 'absolute', bottom: -1, right: -1,
        width: 14, height: 14, borderRadius: '50%',
        background: info.color, border: '2px solid var(--tm-bg-1)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={info.icon} size={8} style={{ color: '#fff' }} />
      </span>
    </div>
  );
}

function MsgBubble({ msg }) {
  const isCliente = msg.autor_tipo === 'cliente';
  const isAgente = msg.autor_tipo === 'agente';

  return (
    <div className={`msg ${isCliente ? 'in' : 'out'} ${isAgente ? 'ia' : ''}`}>
      {isAgente && (
        <span className="badge-ia"><Icon name="bot" size={10} />IA</span>
      )}
      {msg.tipo_conteudo === 'image' && msg.media_url && (
        <div style={{ marginBottom: 6 }}>
          <img src={msg.media_url} alt="" style={{ maxWidth: 220, borderRadius: 8 }} />
        </div>
      )}
      {msg.tipo_conteudo === 'audio' && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
          <Icon name="mic" size={14} />
          <span style={{ fontSize: 12, color: 'var(--tm-fg-3)' }}>Áudio</span>
        </div>
      )}
      {msg.tipo_conteudo === 'document' && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
          <Icon name="file" size={14} />
          <span style={{ fontSize: 12 }}>{msg.conteudo}</span>
        </div>
      )}
      {(msg.tipo_conteudo === 'text' || !msg.tipo_conteudo) && <div>{msg.conteudo}</div>}
      <span className="time">
        {new Date(msg.enviada_em || msg.created_at).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })}
        {!isCliente && msg.status_envio === 'lida' && ' ✓✓'}
        {!isCliente && msg.status_envio === 'entregue' && ' ✓✓'}
        {!isCliente && msg.status_envio === 'enviada' && ' ✓'}
      </span>
    </div>
  );
}

function MsgKpiCards({ conversas }) {
  const abertas = conversas.filter(c => c.status === 'Aberta').length;
  const naoLidas = conversas.reduce((a, c) => a + (c.nao_lidas || 0), 0);
  const iaAtivas = conversas.filter(c => c.agente_ativo).length;
  const hoje = new Date().toISOString().slice(0, 10);
  const msgsHoje = conversas.filter(c => (c.ultima_msg_em || '').slice(0, 10) === hoje).length;

  return (
    <div className="kpi-row">
      <div className="kpi-mini"><div className="kv">{abertas}</div><div className="kl">Abertas</div></div>
      <div className="kpi-mini"><div className="kv">{naoLidas}</div><div className="kl">Não lidas</div></div>
      <div className="kpi-mini"><div className="kv">{iaAtivas}</div><div className="kl">IA ativas</div></div>
      <div className="kpi-mini"><div className="kv">{msgsHoje}</div><div className="kl">Hoje</div></div>
    </div>
  );
}

// ─── Exports ────────────────────────────────────────────────────────────────

Object.assign(window, {
  MSG_CANAIS_INFO, AGENTE_TIPOS, MODELOS_IA, MSG_STATUS_TONE, PRIORIDADE_TONE, TEMPLATE_CATEGORIAS,
  timeAgo, formatPhone,
  CanalBadge, AgenteIndicator, PrioridadeBadge, MsgStatusBadge, ConvAvatar, MsgBubble, MsgKpiCards,
});
