import React, { useState, useEffect, useRef, use } from 'react'; import { __ } from '@wordpress/i18n'; import '../styles/widget-position.scss'; const ChatBubbleRollingMessage = ({ onClick, settings }) => { const [currentMessageIndex, setCurrentMessageIndex] = useState(0); const [showMessage, setShowMessage] = useState(false); const [playSound, setPlaySound] = useState(false); const [messagePosition, setMessagePosition] = useState({ right: 80 }); const messageRef = useRef(null); const [widgetPosition, setWidgetPosition] = useState('bottom-right'); const messages = settings.messages || [ __( '👋 Need help?', 'aisk-ai-chat' ), __( '💬 Chat with us!', 'aisk-ai-chat' ), __( '🛍️ Find products', 'aisk-ai-chat' ) ]; // Calculate message position based on its width useEffect(() => { const updatePosition = () => { if (messageRef.current) { const messageWidth = messageRef.current.offsetWidth; const bubbleWidth = 80; // Width of the chat bubble container const spacing = 16; // Spacing between bubble and message const newRight = bubbleWidth + spacing; if('bottom-left' == widgetPosition || 'top-left' == widgetPosition) { setMessagePosition({ left: newRight }); } else { setMessagePosition({ right: newRight }); } } }; // Update position when message changes or becomes visible if (showMessage) { updatePosition(); } // Handle window resize window.addEventListener('resize', updatePosition); return () => window.removeEventListener('resize', updatePosition); }, [showMessage, messages[currentMessageIndex], widgetPosition]); useEffect(() => { const initialTimer = setTimeout(() => { setShowMessage(true); if (settings.soundEnabled) { setPlaySound(true); } }, 1000); const rotationTimer = setInterval(() => { setShowMessage(false); setCurrentMessageIndex((prev) => (prev + 1) % messages.length); setTimeout(() => { setShowMessage(true); }, 100); }, 4000); return () => { clearTimeout(initialTimer); clearInterval(rotationTimer); }; }, [settings.soundEnabled, messages.length]); useEffect(() => { if (playSound && settings.soundEnabled) { const audio = new Audio(settings.soundUrl || '/notification.mp3'); audio.volume = 0.5; audio.play().catch(e => console.log('Audio play failed:', e)); setPlaySound(false); } }, [playSound, settings.soundEnabled, settings.soundUrl]); useEffect(() => { setWidgetPosition(settings.widgetPosition); }, [settings.widgetPosition]); return (
{/* Single message display */}
{messages[currentMessageIndex]}
{/* Main chat bubble */}
Chat
); }; export default ChatBubbleRollingMessage;