'use client'; import React, { useState, useEffect, useRef } from 'react'; import { X, Phone, Send, ChevronDown, Check } from 'lucide-react'; import { motion, AnimatePresence } from 'framer-motion'; interface Instance { id: string; nome: string; avatar: string | null; phone: string | null; } interface NewConversationModalProps { isOpen: boolean; onClose: () => void; onSent?: (phone: string, instanceId: string) => void; activeInstance: Instance | null; connectedInstances: Instance[]; sendMessage: (instanceId: string, phone: string, text: string) => Promise<{ ok: boolean; messageId?: string }>; } function normalizePhoneForSend(input: string): string { const digits = input.replace(/\D/g, ''); // Already has Brazil country code: 55 + DDD (2) + number (8-9) = 12-13 digits if (digits.startsWith('55') && (digits.length === 12 || digits.length === 13)) return digits; // Local Brazilian number: DDD (2) + number (8-9) = 10-11 digits if (digits.length === 10 || digits.length === 11) return '55' + digits; // Return as-is (international or unusual) return digits; } export default function NewConversationModal({ isOpen, onClose, onSent, activeInstance, connectedInstances, sendMessage, }: NewConversationModalProps) { const [phone, setPhone] = useState(''); const [message, setMessage] = useState(''); const [selectedInstanceId, setSelectedInstanceId] = useState(''); const [sending, setSending] = useState(false); const [sent, setSent] = useState(false); const [error, setError] = useState(''); const phoneInputRef = useRef(null); const textareaRef = useRef(null); // Reset state when modal opens useEffect(() => { if (isOpen) { setPhone(''); setMessage(''); setError(''); setSent(false); setSending(false); setSelectedInstanceId(activeInstance?.id || connectedInstances[0]?.id || ''); setTimeout(() => phoneInputRef.current?.focus(), 120); } }, [isOpen, activeInstance?.id, connectedInstances]); const handlePhoneChange = (e: React.ChangeEvent) => { setPhone(e.target.value.replace(/[^\d\s\-()+]/g, '')); setError(''); }; const handleSubmit = async () => { const normalized = normalizePhoneForSend(phone); const digits = normalized.replace(/\D/g, ''); if (digits.length < 10) { setError('Número inválido. Informe DDD + número (ex: 67 99922-2377)'); phoneInputRef.current?.focus(); return; } if (!message.trim()) { setError('Escreva uma mensagem para iniciar a conversa'); textareaRef.current?.focus(); return; } if (!selectedInstanceId) { setError('Nenhuma instância conectada'); return; } setSending(true); setError(''); try { const result = await sendMessage(selectedInstanceId, normalized, message.trim()); if (!result.ok) throw new Error('Envio falhou'); setSent(true); // Brief success state, then close and notify parent setTimeout(() => { onSent?.(normalized, selectedInstanceId); onClose(); }, 1300); } catch (err: any) { setError(err?.message || 'Erro ao enviar. Verifique o número e tente novamente.'); setSending(false); } }; const handleTextareaKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); handleSubmit(); } }; const handlePhoneKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') textareaRef.current?.focus(); }; const canSend = !!phone.trim() && !!message.trim() && !!selectedInstanceId && !sending && !sent; return ( {isOpen && (
{/* Backdrop */} {/* Modal */} {/* Header */}

Nova Conversa

Enviar primeira mensagem

{/* Instance selector — only if multiple instances connected */} {connectedInstances.length > 1 && (
)} {/* Phone input */}
🇧🇷 +55
{/* Message textarea */}