import { useState, useEffect, useCallback, useRef } from 'react'
import {
  Bot, AlertTriangle, MessageSquare, Settings, HelpCircle,
  Send, RefreshCw, Inbox, ArrowLeft, ArrowRightCircle, X,
  Flag, CheckCircle, Brain, Users, Megaphone, Info,
} from 'lucide-react'
import { InboxInternaService, EscalationService, HumanApiService, ProtocolService, KnowledgeService, GroupChatService, BroadcastService, type GroupChat } from '../services/api'
import CollaboratorsPanel, { type Colleague } from './CollaboratorsPanel'
import DMConversationView from './DMConversationView'
import GroupChatView from './GroupChatView'
import BroadcastPanel from './BroadcastPanel'
import InboxHelpModal from '../components/InboxHelpModal'
import NotificationToast, { useNotifications } from '../components/NotificationToast'
import { useSSE } from '../hooks/useSSE'

// ─── tipos ───────────────────────────────────────────────────────────────────

interface Thread {
  thread_id: string
  type: string
  sector_id: number | null
  sector_name: string | null
  last_message: string
  last_at: string
  ref_id: string | null
  chat_id: string | null
  unread: number
}

interface Message {
  id: number
  thread_id: string
  from_account: number | null
  from_name: string | null
  from_avatar: string | null
  to_account: number | null
  sector_id: number | null
  type: string
  content: string
  ref_id: string | null
  read_at: string | null
  created_at: string
}

// ─── helpers ─────────────────────────────────────────────────────────────────

const TYPE_META: Record<string, { label: string; Icon: any; color: string }> = {
  human_api:     { label: 'Human API',    Icon: Bot,           color: 'text-cyan-500' },
  escalation:    { label: 'Escalação',    Icon: AlertTriangle, color: 'text-amber-500' },
  help_request:  { label: 'Ajuda',        Icon: HelpCircle,    color: 'text-orange-500' },
  collaboration: { label: 'Mensagem',     Icon: MessageSquare, color: 'text-[#54656f]' },
  system:        { label: 'Sistema',      Icon: Settings,      color: 'text-[#8696a0]' },
}

function formatTime(iso: string): string {
  const d = new Date(iso)
  const now = new Date()
  const diff = (now.getTime() - d.getTime()) / 1000
  if (diff < 60)    return 'agora'
  if (diff < 3600)  return `${Math.floor(diff/60)}m`
  if (diff < 86400) return d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })
  return d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' })
}

function Avatar({ name, url, size = 8 }: { name: string | null; url?: string | null; size?: number }) {
  const s = `w-${size} h-${size}`
  if (url) return <img src={url} className={`${s} rounded-full object-cover flex-shrink-0`} />
  const letter = name ? name.charAt(0).toUpperCase() : '?'
  return (
    <div className={`${s} rounded-full bg-[#dfe5e7] flex items-center justify-center text-[#54656f] text-xs font-semibold flex-shrink-0`}>
      {letter}
    </div>
  )
}

// ─── Painel de thread ─────────────────────────────────────────────────────────

function TransferModal({ thread, onClose, onDone }: { thread: Thread; onClose: () => void; onDone: () => void }) {
  const [accounts, setAccounts] = useState<{ id: number; name: string; email: string }[]>([])
  const [toId,    setToId]      = useState<number | ''>('')
  const [msg,     setMsg]       = useState('')
  const [sending, setSending]   = useState(false)

  useEffect(() => {
    fetch('/api/admin/accounts', { credentials: 'include' })
      .then(r => r.json()).then(d => setAccounts(Array.isArray(d) ? d : d.accounts || []))
      .catch(() => {})
  }, [])

  async function submit() {
    if (!toId) return
    setSending(true)
    try {
      await EscalationService.transfer({
        threadId:       thread.thread_id,
        toAccountId:    Number(toId),
        protocolNumber: thread.ref_id || undefined,
        message:        msg.trim() || undefined,
      })
      onDone()
      onClose()
    } catch { setSending(false) }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-white rounded-2xl shadow-2xl w-[340px] p-6 flex flex-col gap-4">
        <div className="flex items-center justify-between">
          <h3 className="text-[14px] font-bold text-[#111b21]">Transferir protocolo</h3>
          <button onClick={onClose} className="text-[#8696a0] hover:text-[#111b21] transition"><X size={16} /></button>
        </div>
        {thread.ref_id && <p className="text-[12px] text-[#667781]">Protocolo: <span className="font-mono font-bold">#{thread.ref_id}</span></p>}
        <select
          value={toId}
          onChange={e => setToId(Number(e.target.value))}
          className="w-full border border-[#d1d7db] rounded-xl px-3 py-2.5 text-[13px] text-[#111b21] outline-none focus:border-[#00a884]">
          <option value="">Selecione o atendente...</option>
          {accounts.map(a => <option key={a.id} value={a.id}>{a.name} — {a.email}</option>)}
        </select>
        <textarea
          value={msg}
          onChange={e => setMsg(e.target.value)}
          placeholder="Mensagem de contexto (opcional)"
          rows={3}
          className="w-full border border-[#d1d7db] rounded-xl px-3 py-2 text-[13px] text-[#111b21] placeholder-[#8696a0] outline-none focus:border-[#00a884] resize-none" />
        <button onClick={submit} disabled={!toId || sending}
          className="bg-[#00a884] hover:bg-[#008f72] disabled:opacity-40 text-white rounded-xl py-2.5 text-[13px] font-bold transition flex items-center justify-center gap-2">
          <ArrowRightCircle size={15} />
          {sending ? 'Transferindo...' : 'Transferir'}
        </button>
      </div>
    </div>
  )
}

function ThreadPanel({ thread, accountId, onBack, onRefresh }: {
  thread: Thread; accountId: number | null; onBack: () => void; onRefresh: () => void
}) {
  const [messages,      setMessages]      = useState<Message[]>([])
  const [loading,       setLoading]       = useState(true)
  const [reply,         setReply]         = useState('')
  const [sending,       setSending]       = useState(false)
  const [transferOpen,  setTransferOpen]  = useState(false)
  const [flagOpen,      setFlagOpen]      = useState(false)
  const [flagNote,      setFlagNote]      = useState('')
  const [flagSending,   setFlagSending]   = useState(false)
  const [closing,       setClosing]       = useState(false)
  const [savingBrain,   setSavingBrain]   = useState(false)
  const bottomRef = useRef<HTMLDivElement>(null)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const msgs = await InboxInternaService.getThread(thread.thread_id)
      setMessages(msgs)
      if (accountId) await InboxInternaService.markRead(thread.thread_id, accountId)
    } finally { setLoading(false) }
  }, [thread.thread_id, accountId])

  useEffect(() => { load() }, [load])
  useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [messages])

  async function send() {
    if (!reply.trim()) return
    setSending(true)
    try {
      // Para human_api, entrega a resposta à IA via endpoint dedicado
      if (thread.type === 'human_api' && thread.ref_id) {
        await HumanApiService.answer(Number(thread.ref_id), reply.trim())
      } else {
        await InboxInternaService.postMessage({
          thread_id:    thread.thread_id,
          from_account: accountId || undefined,
          sector_id:    thread.sector_id || undefined,
          type:         thread.type,
          content:      reply.trim(),
          ref_id:       thread.ref_id || undefined,
        })
      }
      setReply('')
      load()
      onRefresh()
    } finally { setSending(false) }
  }

  async function handleFlag(type: 'complaint' | 'suggestion' | 'compliment') {
    setFlagSending(true)
    try {
      await ProtocolService.flag({ threadId: thread.thread_id, type, note: flagNote.trim() || undefined })
      setFlagOpen(false); setFlagNote(''); load(); onRefresh()
    } finally { setFlagSending(false) }
  }

  async function handleClose(chatId: string) {
    if (!chatId) return
    setClosing(true)
    try {
      await ProtocolService.close({ threadId: thread.thread_id, chatId, protocolNumber: thread.ref_id || undefined })
      load(); onRefresh()
    } finally { setClosing(false) }
  }

  async function handleSaveBrain() {
    const lastQuestion = messages.find(m => !m.from_account)?.content
    const lastAnswer   = messages.filter(m => m.from_account).pop()?.content
    if (!lastAnswer) return
    setSavingBrain(true)
    try {
      const kl = await KnowledgeService.save({
        question: lastQuestion || thread.ref_id || 'Consulta',
        answer:   lastAnswer,
        sectorId: thread.sector_id || undefined,
      })
      if (window.confirm('Resposta salva! Promover para Base de Conhecimento do setor agora?')) {
        await KnowledgeService.promote(kl.id)
      }
    } finally { setSavingBrain(false) }
  }

  const meta = TYPE_META[thread.type] || TYPE_META.collaboration

  return (
    <div className="flex flex-col h-full bg-[#f0f2f5]">
      {/* cabeçalho */}
      <div className="flex-shrink-0 px-3 py-3 bg-[#f0f2f5] border-b border-[#e9edef] flex items-center gap-2">
        <button onClick={onBack} className="p-1 rounded-full hover:bg-[#e9edef] transition text-[#54656f]">
          <ArrowLeft size={18} />
        </button>
        <meta.Icon size={15} className={meta.color} />
        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium text-[#111b21] truncate">
            {meta.label}
            {thread.sector_name && <span className="text-[#8696a0]"> · {thread.sector_name}</span>}
          </p>
          {thread.ref_id && <p className="text-[10px] text-[#8696a0]">#{thread.ref_id}</p>}
        </div>
        {thread.type === 'human_api' && (
          <button onClick={handleSaveBrain} disabled={savingBrain} title="Salvar resposta no Brain"
            className="p-1.5 rounded-full hover:bg-[#e9edef] transition text-cyan-500 disabled:opacity-40">
            <Brain size={15} />
          </button>
        )}
        <button onClick={() => setFlagOpen(f => !f)} title="Registrar flag"
          className={`p-1.5 rounded-full hover:bg-[#e9edef] transition ${flagOpen ? 'text-amber-500' : 'text-[#8696a0]'}`}>
          <Flag size={15} />
        </button>
        <button onClick={() => setTransferOpen(true)} title="Transferir protocolo"
          className="p-1.5 rounded-full hover:bg-[#e9edef] transition text-[#8696a0]">
          <ArrowRightCircle size={15} />
        </button>
        <button onClick={load} className="p-1.5 rounded-full hover:bg-[#e9edef] transition text-[#8696a0]">
          <RefreshCw size={13} className={loading ? 'animate-spin' : ''} />
        </button>
      </div>

      {transferOpen && (
        <TransferModal
          thread={thread}
          onClose={() => setTransferOpen(false)}
          onDone={() => { load(); onRefresh() }}
        />
      )}

      {/* Painel de flag */}
      {flagOpen && (
        <div className="flex-shrink-0 px-3 py-2 bg-amber-50 border-b border-amber-200">
          <p className="text-[11px] font-semibold text-amber-700 mb-1.5 flex items-center gap-1">
            <Flag size={10} /> Registrar flag neste protocolo
          </p>
          <input value={flagNote} onChange={e => setFlagNote(e.target.value)}
            placeholder="Observação (opcional)"
            className="w-full border border-amber-200 rounded-lg px-2.5 py-1.5 text-[12px] mb-1.5 outline-none focus:border-amber-400 bg-white" />
          <div className="flex gap-1.5">
            {([
              ['complaint',  '🔴 Reclamação'],
              ['suggestion', '💡 Sugestão'],
              ['compliment', '⭐ Elogio'],
            ] as const).map(([t, l]) => (
              <button key={t} onClick={() => handleFlag(t)} disabled={flagSending}
                className="flex-1 text-[11px] font-medium py-1 rounded-lg border border-amber-200 bg-white hover:bg-amber-100 text-amber-800 disabled:opacity-40 transition">
                {l}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* mensagens */}
      <div className="flex-1 overflow-y-auto p-3 space-y-2">
        {loading && messages.length === 0
          ? <div className="text-center py-8 text-[#8696a0] text-sm">Carregando...</div>
          : messages.map(msg => {
              const isMe = accountId && msg.from_account === accountId
              const isSystem = !msg.from_account
              return (
                <div key={msg.id} className={`flex gap-2 ${isMe ? 'flex-row-reverse' : ''}`}>
                  {!isMe && <Avatar name={msg.from_name} url={msg.from_avatar} size={7} />}
                  <div className={`max-w-[82%] flex flex-col gap-0.5 ${isMe ? 'items-end' : 'items-start'}`}>
                    {!isMe && !isSystem && (
                      <p className="text-[10px] text-[#8696a0] px-1">{msg.from_name || 'Sistema'}</p>
                    )}
                    <div className={`px-3 py-2 rounded-2xl text-[13px] leading-relaxed whitespace-pre-wrap shadow-sm
                      ${isSystem
                        ? 'bg-[#fff3cd] border border-[#ffe69c] text-[#664d03] italic text-xs rounded-xl'
                        : isMe
                          ? 'bg-[#d9fdd3] text-[#111b21] rounded-tr-sm'
                          : 'bg-white text-[#111b21] rounded-tl-sm'}`}>
                      {msg.content}
                    </div>
                    <p className="text-[10px] text-[#8696a0] px-1">{formatTime(msg.created_at)}</p>
                  </div>
                </div>
              )
            })
        }
        <div ref={bottomRef} />
      </div>

      {/* input */}
      <div className="flex-shrink-0 px-3 py-2 bg-[#f0f2f5] border-t border-[#e9edef]">
        {thread.type === 'human_api' && (
          <p className="text-[11px] text-cyan-600 mb-1.5 flex items-center gap-1">
            <Bot size={11} /> Sua resposta será entregue à IA para continuar o atendimento
          </p>
        )}
        <div className="flex gap-2 items-end">
          <textarea
            value={reply}
            onChange={e => setReply(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send() } }}
            rows={1}
            placeholder="Digite uma mensagem"
            className="flex-1 bg-white border-0 rounded-xl px-3 py-2.5 text-[13px] text-[#111b21] placeholder-[#8696a0] focus:outline-none resize-none shadow-sm"
            style={{ minHeight: 40, maxHeight: 100 }}
          />
          <button onClick={send} disabled={sending || !reply.trim()}
            className="p-2.5 bg-[#00a884] hover:bg-[#008f72] disabled:opacity-40 text-white rounded-full transition flex-shrink-0">
            <Send size={15} />
          </button>
        </div>

        {/* Encerrar protocolo — só aparece em escalações com ref_id */}
        {thread.type === 'escalation' && thread.ref_id && thread.chat_id && (
          <div className="mt-1.5 flex justify-end">
            <button
              onClick={() => handleClose(thread.chat_id!)}
              disabled={closing}
              className="flex items-center gap-1.5 px-3 py-1 text-[11px] font-medium text-[#54656f] hover:text-red-600 hover:bg-red-50 rounded-lg transition disabled:opacity-40">
              <CheckCircle size={12} />
              {closing ? 'Encerrando...' : 'Encerrar protocolo'}
            </button>
          </div>
        )}
      </div>
    </div>
  )
}

// ─── InboxInternaTab ──────────────────────────────────────────────────────────

export default function InboxInternaTab({ accountId, role = 'agent' }: { accountId?: number | null; role?: string }) {
  const [threads, setThreads]           = useState<Thread[]>([])
  const [selected, setSelected]         = useState<Thread | null>(null)
  const [selectedColleague, setSelectedColleague] = useState<Colleague | null>(null)
  const [groups, setGroups]             = useState<GroupChat[]>([])
  const [selectedGroup, setSelectedGroup] = useState<GroupChat | null>(null)
  const [groupsLoading, setGroupsLoading] = useState(false)
  const [broadcastUnread, setBroadcastUnread] = useState(0)
  const [loading, setLoading]           = useState(true)
  const [filterType, setFilterType]     = useState<string>('')
  const [viewMode, setViewMode]         = useState<'inbox' | 'colleagues' | 'groups' | 'broadcast'>('inbox')
  const [showHelp, setShowHelp]         = useState(false)

  const { notifications, push: pushNotif, dismiss: dismissNotif } = useNotifications()
  const { addEventListener, removeEventListener } = useSSE()
  const selectedColleagueRef = useRef<Colleague | null>(null)
  const selectedGroupRef      = useRef<GroupChat | null>(null)
  const viewModeRef           = useRef(viewMode)
  useEffect(() => { selectedColleagueRef.current = selectedColleague }, [selectedColleague])
  useEffect(() => { selectedGroupRef.current = selectedGroup }, [selectedGroup])
  useEffect(() => { viewModeRef.current = viewMode }, [viewMode])

  const load = useCallback(async () => {
    if (!accountId) return
    setLoading(true)
    try {
      const t = await InboxInternaService.listThreads(accountId)
      setThreads(t)
    } finally { setLoading(false) }
  }, [accountId])

  const loadGroups = useCallback(async () => {
    if (!accountId) return
    setGroupsLoading(true)
    try {
      const g = await GroupChatService.list()
      setGroups(g)
    } finally { setGroupsLoading(false) }
  }, [accountId])

  const loadBroadcastUnread = useCallback(async () => {
    if (!accountId) return
    try {
      const { unread_count } = await BroadcastService.list()
      setBroadcastUnread(unread_count)
    } catch { /* silencioso */ }
  }, [accountId])

  useEffect(() => { load() }, [load])
  useEffect(() => { loadGroups() }, [loadGroups])
  useEffect(() => { loadBroadcastUnread() }, [loadBroadcastUnread])

  // ── SSE: notificações em tempo real ─────────────────────────────────────────
  useEffect(() => {
    const onDmNew = (data: unknown) => {
      const { from, content } = data as { from: number; content: string }
      // Só notifica se o chat com esse remetente não está aberto
      if (viewModeRef.current === 'colleagues' && selectedColleagueRef.current?.id === from) return
      pushNotif({ type: 'dm.new', title: 'Nova mensagem', body: content })
    }

    const onHumanApi = (data: unknown) => {
      const { question } = data as { question?: string }
      load()
      pushNotif({ type: 'human_api.new', title: 'IA precisa de ajuda', body: question || 'Clique para responder' })
    }

    const onHumanApiTimeout = () => {
      pushNotif({ type: 'human_api.timeout', title: 'Tempo esgotado', body: 'IA retomou sem resposta humana' })
    }

    const onSlaBreach = (data: unknown) => {
      const d = data as { protocol?: string }
      pushNotif({ type: 'sla.breach', title: 'SLA em risco!', body: d.protocol ? `Protocolo #${d.protocol}` : 'Protocolo urgente' })
    }

    const onHandoffExpired = () => {
      load()
      pushNotif({ type: 'handoff.expired', title: 'Handoff expirado', body: 'Atendimento retornou para a IA' })
    }

    const onBroadcastSent = (data: unknown) => {
      const d = data as { from: number; content: string }
      if (d.from === accountId) return
      if (viewModeRef.current !== 'broadcast') {
        setBroadcastUnread(n => n + 1)
        pushNotif({ type: 'dm.new', title: 'Aviso da equipe', body: d.content })
      }
    }

    const onGroupMsgNew = (data: unknown) => {
      const d = data as { group_chat_id: number; group_name: string; from: number; content: string }
      const groupOpen = viewModeRef.current === 'groups' && selectedGroupRef.current?.id === d.group_chat_id
      // Atualiza last_message e unread_count na lista
      setGroups(prev => prev.map(g =>
        g.id === d.group_chat_id
          ? {
              ...g,
              last_message:    d.content,
              last_message_at: new Date().toISOString(),
              unread_count:    groupOpen ? g.unread_count : (g.unread_count ?? 0) + 1,
            }
          : g
      ))
      if (!groupOpen) {
        pushNotif({ type: 'dm.new', title: `Grupo: ${d.group_name}`, body: d.content })
      }
    }

    addEventListener('dm.new', onDmNew)
    addEventListener('human_api.new', onHumanApi)
    addEventListener('human_api.timeout', onHumanApiTimeout)
    addEventListener('sla.breach', onSlaBreach)
    addEventListener('handoff.expired', onHandoffExpired)
    addEventListener('group_message.new', onGroupMsgNew)
    addEventListener('broadcast.sent', onBroadcastSent)

    return () => {
      removeEventListener('dm.new', onDmNew)
      removeEventListener('human_api.new', onHumanApi)
      removeEventListener('human_api.timeout', onHumanApiTimeout)
      removeEventListener('sla.breach', onSlaBreach)
      removeEventListener('handoff.expired', onHandoffExpired)
      removeEventListener('group_message.new', onGroupMsgNew)
      removeEventListener('broadcast.sent', onBroadcastSent)
    }
  }, [addEventListener, removeEventListener, load, pushNotif])

  const filtered         = filterType ? threads.filter(t => t.type === filterType) : threads
  const totalUnread      = threads.reduce((s, t) => s + t.unread, 0)
  const totalGroupUnread = groups.reduce((s, g) => s + (g.unread_count ?? 0), 0)

  // Sem conta de equipe → não tem inbox
  if (!accountId) {
    return (
      <div className="flex flex-col items-center justify-center h-full gap-3 text-[#8696a0] px-6 text-center">
        <Inbox size={32} className="opacity-30" />
        <p className="text-[13px]">Inbox Interna disponível apenas para membros da equipe.</p>
        <p className="text-[11px]">Faça login como colaborador para acessar.</p>
      </div>
    )
  }

  // Two-column layout: left = list (threads or colleagues), right = detail (thread or DM conversation)
  return (
    <div className="flex h-full bg-white">
      <NotificationToast notifications={notifications} onDismiss={dismissNotif} />
      {/* LEFT COLUMN: Threads or Colleagues list */}
      <div className={`flex flex-col h-full min-h-0 bg-white border-r border-[#d1d7db] ${selectedColleague || selected || selectedGroup ? 'w-80 flex-shrink-0' : 'flex-1'} ${viewMode === 'broadcast' ? 'flex-1' : ''}`}>

        {/* Tabs */}
        <div className="flex-shrink-0 px-3 pt-3 pb-0 bg-white border-b border-[#e9edef]">
          <div className="flex gap-0 mb-0 overflow-x-auto">
            {/* Tab: Inbox */}
            <button
              onClick={() => { setViewMode('inbox'); setSelectedColleague(null); setSelectedGroup(null) }}
              className={`relative flex items-center gap-1 px-3 py-2 text-[12px] font-medium border-b-2 transition flex-shrink-0 ${
                viewMode === 'inbox' ? 'border-[#00a884] text-[#00a884]' : 'border-transparent text-[#8696a0] hover:text-[#54656f]'
              }`}>
              <Inbox size={13} />
              Inbox
              {totalUnread > 0 && (
                <span className="bg-[#25d366] text-white text-[9px] font-bold min-w-[15px] h-[15px] px-0.5 rounded-full flex items-center justify-center">
                  {totalUnread > 9 ? '9+' : totalUnread}
                </span>
              )}
            </button>

            {/* Tab: Equipe */}
            <button
              onClick={() => { setViewMode('colleagues'); setSelected(null); setSelectedGroup(null) }}
              className={`relative flex items-center gap-1 px-3 py-2 text-[12px] font-medium border-b-2 transition flex-shrink-0 ${
                viewMode === 'colleagues' ? 'border-[#00a884] text-[#00a884]' : 'border-transparent text-[#8696a0] hover:text-[#54656f]'
              }`}>
              <Users size={13} />
              Equipe
            </button>

            {/* Tab: Grupos */}
            <button
              onClick={() => { setViewMode('groups'); setSelected(null); setSelectedColleague(null) }}
              className={`relative flex items-center gap-1 px-3 py-2 text-[12px] font-medium border-b-2 transition flex-shrink-0 ${
                viewMode === 'groups' ? 'border-[#00a884] text-[#00a884]' : 'border-transparent text-[#8696a0] hover:text-[#54656f]'
              }`}>
              <MessageSquare size={13} />
              Grupos
              {totalGroupUnread > 0 && (
                <span className="bg-[#25d366] text-white text-[9px] font-bold min-w-[15px] h-[15px] px-0.5 rounded-full flex items-center justify-center">
                  {totalGroupUnread > 9 ? '9+' : totalGroupUnread}
                </span>
              )}
            </button>

            {/* Tab: Avisos */}
            <button
              onClick={() => {
                setViewMode('broadcast')
                setSelected(null); setSelectedColleague(null); setSelectedGroup(null)
              }}
              className={`relative flex items-center gap-1 px-3 py-2 text-[12px] font-medium border-b-2 transition flex-shrink-0 ${
                viewMode === 'broadcast' ? 'border-amber-500 text-amber-600' : 'border-transparent text-[#8696a0] hover:text-[#54656f]'
              }`}>
              <Megaphone size={13} />
              Avisos
              {broadcastUnread > 0 && (
                <span className="bg-amber-500 text-white text-[9px] font-bold min-w-[15px] h-[15px] px-0.5 rounded-full flex items-center justify-center">
                  {broadcastUnread > 9 ? '9+' : broadcastUnread}
                </span>
              )}
            </button>

            {/* Botão info */}
            <button
              onClick={() => setShowHelp(true)}
              title="Ajuda sobre o Inbox Interna"
              className="ml-auto flex-shrink-0 self-center p-1.5 rounded-full text-[#8696a0] hover:text-[#00a884] hover:bg-[#e9edef] transition"
            >
              <Info size={14} />
            </button>
          </div>
        </div>

        {showHelp && <InboxHelpModal onClose={() => setShowHelp(false)} />}

        {/* INBOX VIEW */}
        {viewMode === 'inbox' && (
          <>
            <div className="flex-shrink-0 px-4 pt-3 pb-2 bg-[#f0f2f5] border-b border-[#e9edef]">
              <div className="flex items-center gap-2 mb-2">
                <h3 className="text-xs font-semibold text-[#667781] uppercase tracking-wide">Mensagens</h3>
                {totalUnread > 0 && (
                  <span className="ml-auto bg-[#25d366] text-white text-[10px] font-bold px-1.5 py-0.5 rounded-full">
                    {totalUnread}
                  </span>
                )}
                <button onClick={load} className={`${totalUnread > 0 ? '' : 'ml-auto'} p-1 rounded-full hover:bg-[#e9edef] transition text-[#8696a0]`}>
                  <RefreshCw size={13} className={loading ? 'animate-spin' : ''} />
                </button>
              </div>

              {/* filtros */}
              <div className="flex gap-1 overflow-x-auto pb-0.5 -mx-1 px-1">
                <button onClick={() => setFilterType('')}
                  className={`px-2.5 py-0.5 rounded-full text-[11px] font-medium transition whitespace-nowrap
                    ${!filterType ? 'bg-[#00a884] text-white' : 'text-[#54656f] hover:bg-[#e9edef]'}`}>
                  Todos
                </button>
                {Object.entries(TYPE_META).map(([k, v]) => (
                  <button key={k} onClick={() => setFilterType(k)}
                    className={`flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-medium transition whitespace-nowrap
                      ${filterType === k ? 'bg-[#00a884] text-white' : 'text-[#54656f] hover:bg-[#e9edef]'}`}>
                    <v.Icon size={9} />
                    {v.label}
                  </button>
                ))}
              </div>
            </div>

            {/* lista */}
            <div className="flex-1 overflow-y-auto">
              {loading
                ? <div className="text-center py-8 text-[#8696a0] text-sm">Carregando...</div>
                : filtered.length === 0
                  ? <div className="text-center py-12 text-[#8696a0] text-xs px-4">
                      <Inbox size={28} className="mx-auto mb-3 opacity-30 text-[#54656f]" />
                      Nenhuma mensagem ainda.<br />
                      Você receberá aqui consultas da IA e mensagens da equipe.
                    </div>
                  : filtered.map(t => {
                      const meta = TYPE_META[t.type] || TYPE_META.collaboration
                      return (
                        <button key={t.thread_id} onClick={() => setSelected(t)}
                          className={`w-full text-left flex items-start gap-3 px-4 py-3 border-b border-[#e9edef] hover:bg-[#f5f6f6] transition-colors
                            ${selected?.thread_id === t.thread_id ? 'bg-[#e7f5ff] border-l-4 border-l-[#00a884]' : ''}`}>
                          <div className={`mt-0.5 flex-shrink-0 ${meta.color}`}><meta.Icon size={16} /></div>
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center justify-between gap-1">
                              <span className="text-[13px] font-medium text-[#111b21]">
                                {meta.label}
                                {t.sector_name && <span className="text-[#8696a0] font-normal"> · {t.sector_name}</span>}
                              </span>
                              <span className={`text-[11px] flex-shrink-0 ${t.unread > 0 ? 'text-[#25d366] font-medium' : 'text-[#8696a0]'}`}>
                                {formatTime(t.last_at)}
                              </span>
                            </div>
                            <p className="text-[12px] text-[#667781] truncate mt-0.5">{t.last_message}</p>
                            {t.ref_id && <p className="text-[11px] text-[#8696a0]">#{t.ref_id}</p>}
                          </div>
                          {t.unread > 0 && (
                            <span className="mt-1 flex-shrink-0 bg-[#25d366] text-white text-[10px] font-bold min-w-[18px] h-[18px] px-1 rounded-full flex items-center justify-center">
                              {t.unread}
                            </span>
                          )}
                        </button>
                      )
                    })
              }
            </div>

            {/* pedir ajuda */}
            <div className="flex-shrink-0 p-3 border-t border-[#e9edef] bg-[#f0f2f5]">
              <button
                onClick={async () => {
                  const content = prompt('Descreva do que você precisa de ajuda:')
                  if (!content) return
                  const msg = await InboxInternaService.postMessage({
                    from_account: accountId,
                    type: 'help_request',
                    content,
                  })
                  await load()
                  const thread = threads.find(t => t.thread_id === msg.thread_id) || {
                    thread_id: msg.thread_id, type: 'help_request', sector_id: null,
                    sector_name: null, last_message: content, last_at: msg.created_at,
                    ref_id: null, chat_id: null, unread: 0,
                  }
                  setSelected(thread as Thread)
                }}
                className="w-full flex items-center justify-center gap-2 px-3 py-2 border border-dashed border-[#c8d0d4] rounded-xl text-[12px] text-[#54656f] hover:bg-[#e9edef] transition">
                <HelpCircle size={13} />
                Preciso de ajuda
              </button>
            </div>
          </>
        )}

        {/* COLLEAGUES VIEW */}
        {viewMode === 'colleagues' && (
          <CollaboratorsPanel
            selected={selectedColleague?.id ?? null}
            onSelect={(colleague) => setSelectedColleague(colleague)}
            onStartDM={(colleague) => setSelectedColleague(colleague)}
            onNewDM={(fromId) => {
              if (selectedColleague?.id !== fromId) {
                pushNotif({ type: 'dm.new', title: 'Nova mensagem', body: 'Clique em Equipe para ver' })
              }
            }}
          />
        )}

        {/* GROUPS VIEW */}
        {viewMode === 'groups' && (
          <div className="flex flex-col flex-1 min-h-0">
            <div className="flex-shrink-0 px-3 pt-3 pb-2 bg-[#f0f2f5] border-b border-[#e9edef] flex items-center justify-between">
              <h3 className="text-xs font-semibold text-[#667781] uppercase tracking-wide">Grupos por Setor</h3>
              <button onClick={loadGroups} className="p-1 rounded-full hover:bg-[#e9edef] transition text-[#8696a0]">
                <RefreshCw size={11} className={groupsLoading ? 'animate-spin' : ''} />
              </button>
            </div>
            <div className="flex-1 overflow-y-auto">
              {groupsLoading ? (
                <div className="text-center py-8 text-[#8696a0] text-[12px]">Carregando...</div>
              ) : groups.length === 0 ? (
                <div className="text-center py-8 text-[#8696a0] text-[12px]">Nenhum grupo encontrado</div>
              ) : (
                groups.map(g => {
                  const hasUnread = (g.unread_count ?? 0) > 0
                  return (
                    <button
                      key={g.id}
                      onClick={() => {
                        setSelectedGroup(g)
                        // Mark as read optimisticamente
                        setGroups(prev => prev.map(x => x.id === g.id ? { ...x, unread_count: 0 } : x))
                        GroupChatService.markRead(g.id).catch(() => {})
                      }}
                      className={`w-full text-left flex items-center gap-2.5 px-3 py-2.5 border-b border-[#f0f2f5] hover:bg-[#f5f6f6] transition-colors
                        ${selectedGroup?.id === g.id ? 'bg-[#e7f5ff] border-l-4 border-l-[#00a884]' : ''}
                        ${hasUnread ? 'bg-white' : ''}`}
                    >
                      <div
                        className="w-9 h-9 rounded-full flex items-center justify-center text-white text-sm font-bold flex-shrink-0"
                        style={{ backgroundColor: g.color }}
                      >
                        {g.name.charAt(0).toUpperCase()}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className={`text-[13px] truncate ${hasUnread ? 'font-semibold text-[#111b21]' : 'font-medium text-[#111b21]'}`}>
                          {g.name}
                        </p>
                        {g.last_message && (
                          <p className={`text-[11px] truncate ${hasUnread ? 'text-[#111b21] font-medium' : 'text-[#8696a0]'}`}>
                            {g.last_message}
                          </p>
                        )}
                      </div>
                      <div className="flex flex-col items-end gap-1 flex-shrink-0">
                        {g.last_message_at && (
                          <span className={`text-[10px] ${hasUnread ? 'text-[#25d366] font-medium' : 'text-[#8696a0]'}`}>
                            {formatTime(g.last_message_at)}
                          </span>
                        )}
                        {hasUnread && (
                          <span className="bg-[#25d366] text-white text-[9px] font-bold min-w-[18px] h-[18px] px-1 rounded-full flex items-center justify-center">
                            {g.unread_count > 9 ? '9+' : g.unread_count}
                          </span>
                        )}
                      </div>
                    </button>
                  )
                })
              )}
            </div>
          </div>
        )}

        {/* BROADCAST VIEW */}
        {viewMode === 'broadcast' && accountId && (
          <BroadcastPanel
            accountId={accountId}
            role={role}
            onNewBroadcast={(content) => pushNotif({ type: 'dm.new', title: 'Aviso da equipe', body: content })}
            onSeen={() => setBroadcastUnread(0)}
          />
        )}
      </div>

      {/* RIGHT COLUMN: Thread, DM or Group Chat */}
      {(selected || selectedColleague || selectedGroup) && (
        <div className="flex-1 flex flex-col">
          {selected && !selectedColleague && !selectedGroup ? (
            <ThreadPanel
              thread={selected}
              accountId={accountId ?? null}
              onBack={() => setSelected(null)}
              onRefresh={load}
            />
          ) : selectedColleague ? (
            <DMConversationView
              colleague={selectedColleague}
              accountId={accountId}
              onBack={() => setSelectedColleague(null)}
            />
          ) : selectedGroup ? (
            <GroupChatView
              group={selectedGroup}
              accountId={accountId!}
              onBack={() => setSelectedGroup(null)}
            />
          ) : null}
        </div>
      )}
    </div>
  )
}
