import { useState, useEffect, useRef, type FormEvent } from 'react'; import { Loader2, Send } from 'lucide-react'; type MessageType = 'text' | 'audio' | 'image' | 'video' | 'embed'; interface MessageConfig { text: string; delay?: number; type?: MessageType; } interface OptionConfig { text: string; nextId?: string; actionLink?: string; } interface FunnelNode { id: string; messages: MessageConfig[]; options?: OptionConfig[]; requireEmail?: boolean; } interface RenderedMessage { id: string; sender: 'bot' | 'user'; type: MessageType; content: string; } const funnelData: FunnelNode[] = [ { id: "start", messages: [ { text: "Oi! 👋 Aqui Ă© a Festa MĂĄgica IA. VocĂȘ cria o personagem 3D do seu filho e monta o kit de festa (convite, topper, painel e mais) direto pelo celular.", delay: 900, type: "text" } ], options: [ { text: "Quero ver como funciona", nextId: "proof" }, { text: "JĂĄ conheço, quero comprar", nextId: "offer" } ] }, { id: "proof", messages: [ { text: "Assiste esse vĂ­deo rapidinho mostrando a plataforma funcionando 👇", delay: 900, type: "text" }, { text: "https://s3.seureview.com.br/festamagica/0510(2).mp4", delay: 1200, type: "video" }, { text: "Aqui um exemplo real: a foto original do Miguel e o personagem 3D que a IA criou com o rostinho dele.", delay: 1200, type: "text" }, { text: "/images/antes-depois/miguel-real.webp", delay: 1000, type: "image" }, { text: "/images/antes-depois/miguel-avatar.webp", delay: 1200, type: "image" } ], options: [ { text: "Quanto custa?", nextId: "offer" } ] }, { id: "offer", messages: [ { text: "O Kit Festa sai de R$29,99 por R$19,99 (pagamento Ășnico).", delay: 900, type: "text" }, { text: "VocĂȘ recebe 30 crĂ©ditos pra criar as artes que quiser — cada crĂ©dito gera uma arte, e a primeira Ă© por nossa conta. 🎁", delay: 1200, type: "text" }, { text: "Quer garantir o seu?", delay: 800, type: "text" } ], options: [ { text: "Quero criar meu kit!", nextId: "checkout_step" } ] }, { id: "checkout_step", messages: [ { text: "Perfeito! Qual Ă© o e-mail pra gente liberar seu acesso Ă  plataforma?", delay: 800, type: "text" } ], requireEmail: true } ]; let sharedAudioCtx: AudioContext | null = null; function getAudioContext() { if (!sharedAudioCtx) { const AudioContextClass = window.AudioContext || (window as any).webkitAudioContext; if (AudioContextClass) { sharedAudioCtx = new AudioContextClass(); } } return sharedAudioCtx; } function playMessageSound() { try { const ctx = getAudioContext(); if (!ctx) return; if (ctx.state === 'suspended') ctx.resume(); const osc = ctx.createOscillator(); const gain = ctx.createGain(); osc.connect(gain); gain.connect(ctx.destination); osc.type = 'sine'; osc.frequency.setValueAtTime(800, ctx.currentTime); osc.frequency.exponentialRampToValueAtTime(300, ctx.currentTime + 0.1); gain.gain.setValueAtTime(0.2, ctx.currentTime); gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.1); osc.start(ctx.currentTime); osc.stop(ctx.currentTime + 0.1); } catch (e) {} } function playTypingSound() { try { const ctx = getAudioContext(); if (!ctx) return; if (ctx.state === 'suspended') ctx.resume(); const osc = ctx.createOscillator(); const gain = ctx.createGain(); osc.connect(gain); gain.connect(ctx.destination); osc.type = 'triangle'; osc.frequency.setValueAtTime(200, ctx.currentTime); gain.gain.setValueAtTime(0.01, ctx.currentTime); gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.05); osc.start(ctx.currentTime); osc.stop(ctx.currentTime + 0.05); } catch (e) {} } export default function WhatsAppFunnel() { const [messages, setMessages] = useState([]); const [isTyping, setIsTyping] = useState(false); const [currentOptions, setCurrentOptions] = useState([]); const [currentRequireEmail, setCurrentRequireEmail] = useState(false); const [emailInput, setEmailInput] = useState(''); const [isLoadingCheckout, setIsLoadingCheckout] = useState(false); const chatEndRef = useRef(null); const scrollToBottom = () => { setTimeout(() => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, 100); }; const playNode = async (nodeId: string) => { setCurrentOptions([]); setCurrentRequireEmail(false); const node = funnelData.find((n) => n.id === nodeId); if (!node) return; for (let i = 0; i < node.messages.length; i++) { const msg = node.messages[i]; const delayBefore = msg.delay ? msg.delay : ((msg.type && msg.type !== 'text') ? 1500 : Math.min(400 + (msg.text.length * 30), 3000)); setIsTyping(true); scrollToBottom(); const typingInterval = setInterval(() => { if (Math.random() > 0.3) playTypingSound(); }, 150); await new Promise((r) => setTimeout(r, delayBefore)); clearInterval(typingInterval); setIsTyping(false); playMessageSound(); setMessages((prev) => [ ...prev, { id: Math.random().toString(), sender: 'bot', type: msg.type || 'text', content: msg.text, }, ]); scrollToBottom(); await new Promise((r) => setTimeout(r, 400)); } if (node.options && node.options.length > 0) { setCurrentOptions(node.options); scrollToBottom(); } if (node.requireEmail) { setCurrentRequireEmail(true); scrollToBottom(); } }; const initialized = useRef(false); useEffect(() => { if (!initialized.current) { initialized.current = true; getAudioContext(); playNode('start'); } }, []); const handleOptionClick = (opt: OptionConfig) => { const ctx = getAudioContext(); if (ctx && ctx.state === 'suspended') { ctx.resume(); } setMessages((prev) => [ ...prev, { id: Math.random().toString(), sender: 'user', type: 'text', content: opt.text, }, ]); setCurrentOptions([]); scrollToBottom(); if (opt.actionLink) { setTimeout(() => { window.location.href = opt.actionLink!; }, 800); } else if (opt.nextId) { setTimeout(() => { playNode(opt.nextId!); }, 600); } }; const handleEmailSubmit = async (e: FormEvent) => { e.preventDefault(); if (!emailInput) return; // Add user email message and a bot "loading" message setMessages((prev) => [ ...prev, { id: Math.random().toString(), sender: 'user', type: 'text', content: emailInput, }, { id: 'loading-checkout', sender: 'bot', type: 'text', content: 'Perfeito! Abrindo o checkout seguro pra vocĂȘ 🎉', } ]); setCurrentRequireEmail(false); setIsLoadingCheckout(true); scrollToBottom(); if (typeof window !== 'undefined' && 'fbq' in window) { (window as any).fbq('track', 'InitiateCheckout'); } setTimeout(() => { window.location.href = `https://festamagicaia.com.br/checkout?plan=popular&source=funil-30&email=${encodeURIComponent(emailInput)}`; }, 800); }; const renderMessageContent = (m: RenderedMessage) => { if (m.type === 'image') { return ( Media ); } else if (m.type === 'video') { return (