const { useState, useEffect, useRef, useCallback } = React;

function Hj93ChatBubbleApp() {
    const C = window.HJ93_CHATBOT || {};
    const i18n = C.i18n || {};
    const [open, setOpen] = useState(false);
    const [input, setInput] = useState('');
    const [messages, setMessages] = useState([]);
    const [typing, setTyping] = useState(false);
    const [started, setStarted] = useState(false);
    const streamRef = useRef(null);

    const cssVars = {
        '--hj93-primary-from': C.primaryFrom || '#0078D4',
        '--hj93-primary-to': C.primaryTo || '#00BCF2',
        '--hj93-chat-bg': C.chatBg || '#1e1e2e',
        '--hj93-bot-msg-bg': C.botMsgBg || '#2a2a3e',
        '--hj93-border': C.borderColor || '#3a3a4e',
        '--hj93-accent': C.accentColor || '#00BCF2',
    };

    useEffect(() => {
        if (open && streamRef.current) {
            streamRef.current.scrollTop = streamRef.current.scrollHeight;
        }
    }, [open, messages, typing, started]);

    const sendMessage = useCallback(async () => {
        const text = (input || '').trim();
        if (!text || typing) return;

        setStarted(true);
        setInput('');
        setMessages((m) => [...m, { role: 'user', text }]);
        setTyping(true);

        try {
            const hdr = {
                'Content-Type': 'application/json',
                'X-HJ93-Nonce': C.nonce || '',
                'X-WP-Nonce': C.nonceRest || C.nonce || '',
            };

            const res = await fetch(C.restUrl, {
                method: 'POST',
                credentials: 'same-origin',
                headers: hdr,
                body: JSON.stringify({ message: text, conversationId: null }),
            });

            const data = await res.json().catch(() => ({}));
            let replyText = '';
            if (data != null && typeof data.reply !== 'undefined' && data.reply !== null && data.reply !== '') {
                replyText = String(data.reply);
            } else if (data != null && data.data && typeof data.data.reply !== 'undefined' && data.data.reply !== '') {
                replyText = String(data.data.reply);
            }

            if (!res.ok) {
                const errMsg =
                    (data && data.message && String(data.message)) ||
                    (data && data.code && String(data.code)) ||
                    i18n.error ||
                    'Error';
                setMessages(function (m) {
                    return m.concat({ role: 'bot', text: errMsg });
                });
                return;
            }
            if (replyText !== '') {
                setMessages(function (m) {
                    return m.concat({ role: 'bot', text: replyText });
                });
            } else {
                setMessages(function (m) {
                    return m.concat({ role: 'bot', text: i18n.error || 'Error' });
                });
            }
        } catch (e) {
            setMessages((m) => [...m, { role: 'bot', text: i18n.error || 'Error' }]);
        } finally {
            setTyping(false);
        }
    }, [C.restUrl, C.nonce, input, typing, i18n.error]);

    const onKeyDown = (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    };

    const title = C.botTitle || 'Chat';

    return (
        <div className="hj93-chat-widget" style={cssVars}>
            {open && (
                <div className="hj93-chat-panel" role="dialog" aria-label={title}>
                    <div className="hj93-chat-panel-header">
                        <h2 className="hj93-chat-panel-title">{title}</h2>
                        <button
                            type="button"
                            className="hj93-chat-close"
                            onClick={() => setOpen(false)}
                            aria-label={i18n.close || 'Cerrar'}
                        >
                            ×
                        </button>
                    </div>

                    <div className="hj93-chat-stream" ref={streamRef}>
                        {!started && (
                            <div className="hj93-chat-welcome">
                                <div className="hj93-chat-welcome-icon" aria-hidden="true">💬</div>
                                <h3>{C.welcomeTitle || ''}</h3>
                                <p>{C.welcomeText || ''}</p>
                            </div>
                        )}

                        {messages.map((msg, idx) => (
                            <div
                                key={idx}
                                className={'hj93-chat-msg ' + (msg.role === 'user' ? 'user' : '')}
                            >
                                <div
                                    className={
                                        'hj93-chat-avatar' + (msg.role === 'user' ? ' user' : '')
                                    }
                                >
                                    {(msg.role === 'user' ? i18n.you : 'A').charAt(0)}
                                </div>
                                <div>
                                    <div className="hj93-chat-meta">
                                        {msg.role === 'user' ? i18n.you || 'Tú' : title}
                                    </div>
                                    <div className="hj93-chat-bubble-text">{msg.text}</div>
                                </div>
                            </div>
                        ))}

                        {typing && (
                            <div className="hj93-chat-msg">
                                <div className="hj93-chat-avatar">A</div>
                                <div>
                                    <div className="hj93-chat-meta">{i18n.typing || '…'}</div>
                                    <div className="hj93-chat-typing" aria-hidden="true">
                                        <span />
                                        <span />
                                        <span />
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>

                    <div className="hj93-chat-input-row">
                        <textarea
                            className="hj93-chat-input"
                            rows={1}
                            value={input}
                            onChange={(e) => setInput(e.target.value)}
                            onKeyDown={onKeyDown}
                            placeholder={i18n.placeholder || ''}
                            disabled={typing}
                            aria-label={i18n.placeholder || ''}
                        />
                        <button
                            type="button"
                            className="hj93-chat-send"
                            onClick={sendMessage}
                            disabled={typing || !String(input).trim()}
                            aria-label={i18n.send || 'Enviar'}
                        >
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                                <path
                                    d="M22 2L11 13M22 2L15 22L11 13M22 2L2 9L11 13"
                                    stroke="currentColor"
                                    strokeWidth="2"
                                />
                            </svg>
                        </button>
                    </div>
                </div>
            )}

            <button
                type="button"
                className="hj93-chat-launcher"
                onClick={() => setOpen(!open)}
                aria-expanded={open}
                aria-label={open ? i18n.close || 'Cerrar' : i18n.openChat || 'Abrir chat'}
            >
                {open ? '×' : '💬'}
            </button>
        </div>
    );
}

const hj93BubbleRoot = document.getElementById('hj93-chat-bubble-root');
if (hj93BubbleRoot) {
    const root = ReactDOM.createRoot(hj93BubbleRoot);
    root.render(<Hj93ChatBubbleApp />);
}
