import React, { useState, useEffect, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { createClient } from '@supabase/supabase-js'; 

const appId = typeof __app_id !== 'undefined' ? __app_id : 'provistahub-assistant-v12';
const supabaseUrl = 'https://xbphycmjfnznmhykkgpc.supabase.co'; 
const supabaseAnonKey = 'sb_publishable_dngYToeCF-HF3PshcFl9Og_funVC0ph';

let supabase = null;
try { supabase = createClient(supabaseUrl, supabaseAnonKey); } catch (e) {}

const TENANT = { name: "ProVista Hub", primary: "#00ff88", secondary: "#05150a", logoUrl: "https://provistahub.com/favicon.ico", phone: "+91 8084843501", email: "support@provistahub.com", whatsapp: "918084843501" };

const Icons = {
    Brand: ({ className }) => (<div className={`flex items-center justify-center overflow-hidden rounded bg-black shadow-[0_0_10px_rgba(0,255,136,0.3)] border border-[#00ff88] ${className || "w-10 h-10"}`}><img src={TENANT.logoUrl} alt="Logo" className="w-full h-full object-contain p-1 filter brightness-200" onError={(e) => { e.target.src = `https://ui-avatars.com/api/?name=PV&background=000&color=00ff88`; }} /></div>),
    Send: () => <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>,
    Back: () => <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>,
    Mic: () => <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>,
    Clip: () => <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>,
    Trash: () => <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M10 11v6M14 11v6"/></svg>
};

const Typewriter = ({ text, onComplete }) => {
    const [display, setDisplay] = useState('');
    useEffect(() => {
        let i = 0; const interval = setInterval(() => {
            if (i < text.length) { setDisplay(text.substring(0, i + 3)); i += 3; } 
            else { setDisplay(text); clearInterval(interval); if (onComplete) onComplete(); }
        }, 15); 
        return () => clearInterval(interval);
    }, [text]);
    return <div className="leading-relaxed whitespace-pre-wrap font-mono">{display}<span className="animate-pulse text-[#00ff88]">_</span></div>;
};

function App() {
    const [isOpen, setIsOpen] = useState(false);
    const [messages, setMessages] = useState([]);
    const [input, setInput] = useState('');
    const scrollRef = useRef(null);

    const quickSuggestions = ["SYSTEM_STATUS", "PROTOCOLS", "PRICING_MATRIX", "ACCESS_SERVICES"];

    useEffect(() => { if (isOpen && messages.length === 0) { resetChat(); } }, [isOpen]);
    useEffect(() => { scrollRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages]);

    const resetChat = () => { setMessages([{ role: 'ai', text: `> NEURAL LINK ESTABLISHED.\n> I am the Vista AI Core.\n> Ready to engineer your next success story. Input command...`, actions: ['EXPLORE_SERVICES', 'INITIATE_CONTACT'], typed: true }]); };

    const handleSend = (text = input) => {
        if (!text.trim()) return;
        setMessages(prev => [...prev, { role: 'user', text, typed: true }]);
        setInput('');
        setTimeout(() => { setMessages(prev => [...prev, { role: 'ai', text: "> COMMAND RECEIVED. Our human engineers will contact you shortly to execute the protocol.", typed: false }]); }, 1000);
    };

    return (
        <div className="fixed bottom-6 right-4 md:bottom-8 md:right-8 z-[99999] pointer-events-none flex flex-col items-end">
            {isOpen && (
                <div className="interactive mb-4 w-[calc(100vw-2rem)] md:w-[380px] h-[65svh] md:h-[500px] max-h-[85vh] flex flex-col glass-hub rounded animate-slide-up overflow-hidden origin-bottom-right transition-all border border-[#00ff88]/30">
                    <div className="p-4 bg-black/80 border-b border-[#00ff88]/30 flex items-center justify-between text-[#00ff88]">
                        <div className="flex items-center space-x-3">
                            <Icons.Brand className="w-8 h-8" />
                            <h3 className="font-bold text-xs uppercase tracking-[0.2em] font-mono">Vista_Core //</h3>
                        </div>
                        <button onClick={resetChat} className="text-gray-500 hover:text-[#00ff88] transition-colors"><Icons.Trash /></button>
                    </div>

                    <div className="flex-1 overflow-y-auto p-4 space-y-4 chat-scroll bg-[#020a05]">
                        {messages.map((msg, i) => (
                            <div key={i} className={`flex w-full ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
                                <div className={`max-w-[85%] px-4 py-3 rounded text-xs font-mono shadow-sm border ${msg.role === 'user' ? 'bg-[#00ff88]/10 text-[#00ff88] border-[#00ff88]/50' : 'bg-black text-gray-300 border-gray-800'}`}>
                                    {msg.role === 'ai' && !msg.typed ? <Typewriter text={msg.text} onComplete={() => setMessages(prev => prev.map((m, idx) => idx === i ? {...m, typed: true} : m))} /> : <div className="whitespace-pre-wrap">{msg.text}</div>}
                                    {msg.actions?.map((a, idx) => <button key={idx} onClick={() => handleSend(a)} className="block mt-3 text-[10px] font-bold uppercase tracking-widest border border-gray-700 bg-black text-[#00ff88] px-3 py-2 rounded w-full text-center hover:bg-[#00ff88]/10 hover:border-[#00ff88] transition-all mag-btn">{a}</button>)}
                                </div>
                            </div>
                        ))}
                        <div ref={scrollRef} className="h-1" />
                    </div>

                    <div className="w-full shrink-0 flex flex-col bg-black border-t border-gray-800">
                        <div className="px-3 py-2 flex gap-2 overflow-x-auto no-scrollbar">
                            {quickSuggestions.map((s, idx) => (
                                <button key={`q-${idx}`} onClick={() => handleSend(s)} className="shrink-0 px-3 py-1 bg-[#05100a] border border-gray-700 rounded text-[9px] font-mono text-gray-400 hover:bg-[#00ff88]/20 hover:text-[#00ff88] hover:border-[#00ff88] transition-colors uppercase">{s}</button>
                            ))}
                        </div>
                        <div className="p-3 border-t border-gray-800 flex items-center space-x-2">
                            <input value={input} onChange={(e) => setInput(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && handleSend()} placeholder="Input command..." className="w-full bg-[#05100a] border border-gray-700 rounded pl-3 pr-3 py-2.5 text-xs text-white font-mono outline-none focus:border-[#00ff88] transition-all" />
                            <button onClick={() => handleSend()} className="p-2.5 bg-[#00ff88] text-black rounded hover:bg-white transition-all mag-btn cursor-pointer"><Icons.Send /></button>
                        </div>
                    </div>
                </div>
            )}
            <div className="relative group interactive flex-shrink-0">
                <button onClick={() => setIsOpen(!isOpen)} className="chatbot-toggle-btn w-[50px] h-[50px] rounded bg-black text-[#00ff88] flex items-center justify-center border border-[#00ff88] shadow-[0_0_15px_rgba(0,255,136,0.3)] hover:shadow-[0_0_25px_rgba(0,255,136,0.6)] transition-all hover:scale-105 active:scale-95 z-10 cursor-pointer">
                    {isOpen ? <span className="text-2xl font-light font-mono">×</span> : <i className="fas fa-terminal text-xl"></i>}
                </button>
            </div>
        </div>
    );
}

const root = createRoot(document.getElementById('root'));
root.render(<App />);