const { useState, useEffect, useRef } = React;

const GOOGLE_API_KEY = 'AIzaSyCn0gh86NbiOXApAbg8FSHs12RQ_YQqstc';
const SEARCH_ENGINE_ID = '83d609e3813b6449a';

// Temas disponíveis
const themes = {
    purple: { primary: '#d946ef', secondary: '#a855f7', gradient: 'from-purple-400 via-pink-500 to-purple-600', name: 'Roxo' },
    red: { primary: '#ef4444', secondary: '#dc2626', gradient: 'from-red-400 via-rose-500 to-red-600', name: 'Vermelho' },
    blue: { primary: '#3b82f6', secondary: '#2563eb', gradient: 'from-blue-400 via-cyan-500 to-blue-600', name: 'Azul' },
    yellow: { primary: '#eab308', secondary: '#ca8a04', gradient: 'from-yellow-400 via-amber-500 to-yellow-600', name: 'Amarelo' },
    green: { primary: '#22c55e', secondary: '#16a34a', gradient: 'from-green-400 via-emerald-500 to-green-600', name: 'Verde' },
    white: { primary: '#f5f5f5', secondary: '#e5e5e5', gradient: 'from-gray-100 via-gray-200 to-gray-300', name: 'Branco' }
};

// Personalidades
const personalities = [
    { id: 'professional', name: 'Profissional', icon: '💼', description: 'Formal e objetiva' },
    { id: 'pirate', name: 'Pirata', icon: '🏴‍☠️', description: 'Ahoy! Fala como um pirata' },
    { id: 'philosopher', name: 'Filósofa', icon: '🤔', description: 'Questiona a existência' },
    { id: 'poet', name: 'Poeta', icon: '📜', description: 'Responde em versos' },
    { id: 'gamer', name: 'Gamer', icon: '🎮', description: 'Cheio de gírias de games' },
    { id: 'chef', name: 'Chef', icon: '👨‍🍳', description: 'Tudo vira culinária' },
    { id: 'conspiracy', name: 'Conspiração', icon: '👽', description: 'Vê teorias em tudo' },
    { id: 'motivational', name: 'Motivador', icon: '💪', description: 'Super empolgado' }
];

// Salvar configurações no localStorage
const saveSettings = (theme, personality) => {
    localStorage.setItem('stellaTheme', theme);
    localStorage.setItem('stellaPersonality', personality);
};

const loadSettings = () => {
    return {
        theme: localStorage.getItem('stellaTheme') || 'purple',
        personality: localStorage.getItem('stellaPersonality') || 'professional'
    };
};

// Lucide Icons como componentes SVG
const Search = () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="11" cy="11" r="8"></circle>
        <path d="m21 21-4.35-4.35"></path>
    </svg>
);

const Settings = () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"></path>
        <circle cx="12" cy="12" r="3"></circle>
    </svg>
);

const Edit = () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
        <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
    </svg>
);

const Book = () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path>
        <path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path>
    </svg>
);

const FileText = () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path>
        <polyline points="14 2 14 8 20 8"></polyline>
        <line x1="16" y1="13" x2="8" y2="13"></line>
        <line x1="16" y1="17" x2="8" y2="17"></line>
        <line x1="10" y1="9" x2="8" y2="9"></line>
    </svg>
);

const MessageCircle = () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
    </svg>
);

const X = () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <line x1="18" y1="6" x2="6" y2="18"></line>
        <line x1="6" y1="6" x2="18" y2="18"></line>
    </svg>
);

// Componente do Modal de Configurações
function SettingsModal({ isOpen, onClose, currentTheme, currentPersonality, onThemeChange, onPersonalityChange, theme }) {
    if (!isOpen) return null;

    return (
        <>
            {/* Backdrop */}
            <div 
                className="fixed inset-0 bg-black/60 backdrop-blur-md z-40 transition-opacity duration-300"
                onClick={onClose}
                style={{ animation: 'fadeIn 0.3s ease-out' }}
            />

            {/* Modal */}
            <div 
                className="fixed inset-0 z-50 flex items-center justify-center pointer-events-none"
                style={{ animation: 'fadeIn 0.3s ease-out' }}
            >
                <div 
                    className="pointer-events-auto w-full max-w-2xl mx-4 relative"
                    style={{ animation: 'slideUp 0.3s ease-out' }}
                >
                    {/* Glow effect */}
                    <div 
                        className="absolute -inset-1 rounded-3xl blur opacity-25 group-hover:opacity-50 transition duration-300"
                        style={{
                            background: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})`
                        }}
                    />

                    {/* Content */}
                    <div className="relative bg-black/80 backdrop-blur-xl rounded-3xl border transition-all duration-300" style={{
                        borderColor: `${theme.primary}4d`
                    }}>
                        {/* Header */}
                        <div className="flex items-center justify-between p-8 border-b" style={{
                            borderColor: `${theme.primary}33`
                        }}>
                            <div>
                                <h2 className="text-2xl font-bold" style={{ color: theme.primary }}>
                                    Personalizar Stella
                                </h2>
                                <p className="text-gray-400 text-sm mt-1">Escolha seu tema e personalidade favoritos</p>
                            </div>
                            <button
                                onClick={onClose}
                                className="p-2 rounded-lg transition-all duration-300 hover:scale-110"
                                style={{
                                    color: theme.primary,
                                    backgroundColor: `${theme.primary}1a`
                                }}
                            >
                                <X />
                            </button>
                        </div>

                        {/* Content */}
                        <div className="p-8 space-y-8">
                            {/* Themes Section */}
                            <div>
                                <h3 className="text-lg font-semibold mb-4 flex items-center gap-2" style={{ color: theme.primary }}>
                                    <span className="text-2xl">🎨</span>
                                    Temas
                                </h3>
                                <div className="grid grid-cols-3 gap-3">
                                    {Object.entries(themes).map(([themeKey, themeValue]) => (
                                        <button
                                            key={themeKey}
                                            onClick={() => onThemeChange(themeKey)}
                                            className="relative group overflow-hidden rounded-2xl p-4 transition-all duration-300 hover:scale-105"
                                            style={{
                                                background: `linear-gradient(135deg, ${themeValue.primary}20, ${themeValue.secondary}10)`,
                                                border: currentTheme === themeKey 
                                                    ? `2px solid ${themeValue.primary}` 
                                                    : `2px solid ${themeValue.primary}33`,
                                                boxShadow: currentTheme === themeKey
                                                    ? `0 0 20px ${themeValue.primary}80`
                                                    : 'none'
                                            }}
                                        >
                                            <div className="flex items-center justify-between">
                                                <span 
                                                    className="font-semibold transition-colors duration-300"
                                                    style={{ color: themeValue.primary }}
                                                >
                                                    {themeValue.name}
                                                </span>
                                                <div 
                                                    className="w-6 h-6 rounded-full transition-all duration-300"
                                                    style={{
                                                        backgroundColor: themeValue.primary,
                                                        boxShadow: `0 0 12px ${themeValue.primary}80`
                                                    }}
                                                />
                                            </div>
                                        </button>
                                    ))}
                                </div>
                            </div>

                            {/* Personalities Section */}
                            <div>
                                <h3 className="text-lg font-semibold mb-4 flex items-center gap-2" style={{ color: theme.primary }}>
                                    <span className="text-2xl">✨</span>
                                    Personalidades
                                </h3>
                                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                                    {personalities.map((personality) => (
                                        <button
                                            key={personality.id}
                                            onClick={() => onPersonalityChange(personality.id)}
                                            className="relative group overflow-hidden rounded-2xl p-4 transition-all duration-300 hover:scale-105"
                                            style={{
                                                background: `linear-gradient(135deg, ${theme.primary}10, ${theme.secondary}05)`,
                                                border: currentPersonality === personality.id 
                                                    ? `2px solid ${theme.primary}` 
                                                    : `2px solid ${theme.primary}33`,
                                                boxShadow: currentPersonality === personality.id
                                                    ? `0 0 20px ${theme.primary}60`
                                                    : 'none'
                                            }}
                                        >
                                            <div className="flex flex-col items-center gap-2">
                                                <span className="text-3xl">{personality.icon}</span>
                                                <div className="text-center">
                                                    <p className="text-sm font-semibold text-white">
                                                        {personality.name}
                                                    </p>
                                                    <p className="text-xs text-gray-400 mt-1">
                                                        {personality.description}
                                                    </p>
                                                </div>
                                            </div>
                                        </button>
                                    ))}
                                </div>
                            </div>
                        </div>

                        {/* Footer */}
                        <div className="px-8 py-6 border-t flex gap-3" style={{ borderColor: `${theme.primary}33` }}>
                            <button
                                onClick={onClose}
                                className="flex-1 py-3 rounded-xl font-semibold transition-all duration-300 hover:scale-105"
                                style={{
                                    background: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})`,
                                    color: 'white'
                                }}
                            >
                                Feito!
                            </button>
                        </div>
                    </div>

                    <style>{`
                        @keyframes fadeIn {
                            from {
                                opacity: 0;
                            }
                            to {
                                opacity: 1;
                            }
                        }
                        
                        @keyframes slideUp {
                            from {
                                opacity: 0;
                                transform: translateY(20px);
                            }
                            to {
                                opacity: 1;
                                transform: translateY(0);
                            }
                        }
                    `}</style>
                </div>
            </div>
        </>
    );
}

function StellaSearch() {
    const [query, setQuery] = useState('');
    const [results, setResults] = useState([]);
    const [loading, setLoading] = useState(false);
    const [searched, setSearched] = useState(false);
    const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
    const [scrollY, setScrollY] = useState(0);
    const [showSettings, setShowSettings] = useState(false);
    const [currentTheme, setCurrentTheme] = useState('purple');
    const [currentPersonality, setCurrentPersonality] = useState('professional');
    const searchRef = useRef(null);

    useEffect(() => {
        const settings = loadSettings();
        setCurrentTheme(settings.theme);
        setCurrentPersonality(settings.personality);
    }, []);

    useEffect(() => {
        const handleMouseMove = (e) => {
            setMousePosition({ x: e.clientX, y: e.clientY });
        };

        const handleScroll = () => {
            setScrollY(window.scrollY);
        };

        window.addEventListener('mousemove', handleMouseMove);
        window.addEventListener('scroll', handleScroll);

        return () => {
            window.removeEventListener('mousemove', handleMouseMove);
            window.removeEventListener('scroll', handleScroll);
        };
    }, []);

    const handleThemeChange = (theme) => {
        setCurrentTheme(theme);
        saveSettings(theme, currentPersonality);
    };

    const handlePersonalityChange = (personality) => {
        setCurrentPersonality(personality);
        saveSettings(currentTheme, personality);
    };

    const theme = themes[currentTheme];

    const searchGoogle = async (searchQuery) => {
        setLoading(true);
        setSearched(true);
        
        try {
            const url = `https://www.googleapis.com/customsearch/v1?key=${GOOGLE_API_KEY}&cx=${SEARCH_ENGINE_ID}&q=${encodeURIComponent(searchQuery)}`;
            const response = await fetch(url);
            
            if (!response.ok) throw new Error('Erro na busca');
            
            const data = await response.json();
            setResults(data.items || []);
        } catch (error) {
            console.error('Erro:', error);
            setResults([]);
        } finally {
            setLoading(false);
        }
    };

    const handleSearch = () => {
        if (query.trim()) {
            searchGoogle(query);
        }
    };

    const handleKeyPress = (e) => {
        if (e.key === 'Enter') {
            handleSearch();
        }
    };

    const cards = [
        { icon: Edit, label: 'Dash', color: 'from-purple-500 to-pink-500', link: 'flowchart.html' },
        { icon: Book, label: 'Library', color: 'from-blue-500 to-cyan-500', link: 'library.html' },
        { icon: FileText, label: 'Notes', color: 'from-green-500 to-emerald-500', link: 'notes.html' },
        { icon: MessageCircle, label: 'Chat', color: 'from-orange-500 to-red-500', link: 'chat.html' }
    ];

    const handleCardClick = (card) => {
        if (card.link) {
            window.open(card.link, '_blank');
        }
    };

    const gradientStyle = {
        background: `radial-gradient(circle at ${mousePosition.x}px ${mousePosition.y}px, ${theme.primary}26, transparent 50%)`
    };

    return (
        <div className="min-h-screen bg-black text-white overflow-hidden relative">
            {/* Interactive background gradient */}
            <div 
                className="fixed inset-0 pointer-events-none transition-all duration-300"
                style={gradientStyle}
            />

            {/* Animated particles */}
            <div className="fixed inset-0 pointer-events-none">
                {[...Array(20)].map((_, i) => (
                    <div
                        key={i}
                        className="absolute w-1 h-1 rounded-full animate-pulse"
                        style={{
                            backgroundColor: `${theme.primary}4d`,
                            left: `${Math.random() * 100}%`,
                            top: `${Math.random() * 100}%`,
                            animationDelay: `${Math.random() * 3}s`,
                            animationDuration: `${2 + Math.random() * 3}s`
                        }}
                    />
                ))}
            </div>

            <div className="relative z-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                {/* Header */}
                <header className="flex justify-end items-center py-6">
                    <button 
                        onClick={() => setShowSettings(!showSettings)}
                        className="p-2 rounded-lg border transition-all duration-300 group"
                        style={{
                            borderColor: `${theme.primary}7f`,
                        }}
                    >
                        <div className="group-hover:rotate-90 transition-transform duration-300" style={{ color: theme.primary }}>
                            <Settings />
                        </div>
                    </button>
                </header>

                {/* Main Content */}
                <main 
                    className="flex flex-col items-center justify-center transition-all duration-500"
                    style={{
                        transform: searched ? `translateY(-${Math.min(scrollY * 0.5, 100)}px)` : 'translateY(0)',
                        paddingTop: searched ? '2rem' : '8rem'
                    }}
                >
                    {/* Title */}
                    <h1 
                        className="text-6xl sm:text-7xl md:text-8xl font-bold mb-12 transition-all duration-500"
                        style={{
                            transform: searched ? 'scale(0.7)' : 'scale(1)',
                            opacity: searched ? 0.9 : 1
                        }}
                    >
                        <span className="bg-clip-text text-transparent" style={{
                            backgroundImage: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})`
                        }}>
                            Stella IA
                        </span>
                    </h1>

                    {/* Search Box */}
                    <div className="w-full max-w-3xl mb-8" ref={searchRef}>
                        <div className="relative group">
                            <div className="absolute -inset-0.5 rounded-2xl blur opacity-30 group-hover:opacity-50 transition duration-300" style={{
                                background: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})`
                            }} />
                            <div className="relative flex items-center bg-black/50 backdrop-blur-xl rounded-2xl group-hover:bg-black/60 transition-all duration-300" style={{
                                border: `2px solid ${theme.primary}4d`,
                            }} onMouseEnter={(e) => e.currentTarget.style.borderColor = `${theme.primary}99`} onMouseLeave={(e) => e.currentTarget.style.borderColor = `${theme.primary}4d`}>
                                <div className="pl-6" style={{ color: theme.primary }}>
                                    <Search />
                                </div>
                                <input
                                    type="text"
                                    value={query}
                                    onChange={(e) => setQuery(e.target.value)}
                                    onKeyPress={handleKeyPress}
                                    placeholder="Pesquisar na web..."
                                    className="flex-1 bg-transparent border-none outline-none px-4 py-5 text-white placeholder-gray-400"
                                />
                                <button
                                    onClick={handleSearch}
                                    className="mr-2 px-6 py-2 rounded-xl transition-all duration-300 transform hover:scale-105"
                                    style={{
                                        background: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})`,
                                        color: 'white'
                                    }}
                                >
                                    Buscar
                                </button>
                            </div>
                        </div>
                    </div>

                    {/* Feature Cards */}
                    {!searched && (
                        <div className="w-full max-w-4xl grid grid-cols-2 md:grid-cols-4 gap-4 mb-12">
                            {cards.map((card, index) => (
                                <div
                                    key={index}
                                    onClick={() => handleCardClick(card)}
                                    className="group relative overflow-hidden rounded-2xl border hover:border-opacity-100 bg-black/30 backdrop-blur-sm p-6 cursor-pointer transition-all duration-300 hover:scale-105 hover:bg-black/50"
                                    style={{
                                        borderColor: `${theme.primary}4d`
                                    }}
                                >
                                    <div className="absolute inset-0 opacity-0 group-hover:opacity-10 transition-opacity duration-300" style={{
                                        background: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})`
                                    }} />
                                    <div className="relative flex flex-col items-center gap-3">
                                        <div className="p-3 rounded-xl transition-all duration-300" style={{
                                            background: `linear-gradient(135deg, ${theme.primary}20, ${theme.secondary}20)`,
                                        }}>
                                            <div className="transition-colors" style={{ color: theme.primary }}>
                                                <card.icon />
                                            </div>
                                        </div>
                                        <h2 className="font-semibold transition-colors" style={{ color: theme.primary }}>
                                            {card.label}
                                        </h2>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}

                    {/* Loading */}
                    {loading && (
                        <div className="flex flex-col items-center gap-4 py-12">
                            <div className="w-12 h-12 border-4 border-opacity-30 rounded-full animate-spin" style={{
                                borderColor: `${theme.primary}4d`,
                                borderTopColor: theme.primary
                            }} />
                            <p style={{ color: theme.primary }}>Buscando resultados...</p>
                        </div>
                    )}

                    {/* Results */}
                    {!loading && results.length > 0 && (
                        <div className="w-full max-w-4xl space-y-4">
                            {results.map((result, index) => (
                                <div
                                    key={index}
                                    className="group relative overflow-hidden rounded-2xl border bg-black/30 backdrop-blur-sm p-6 transition-all duration-300 hover:bg-black/50 hover:scale-[1.02]"
                                    style={{
                                        borderColor: `${theme.primary}33`
                                    }}
                                >
                                    <div className="absolute inset-0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700" style={{
                                        background: `linear-gradient(to right, transparent, ${theme.primary}05, transparent)`
                                    }} />
                                    
                                    <a href={result.link} target="_blank" rel="noopener noreferrer" className="block relative">
                                        <h3 className="text-xl font-semibold mb-2 transition-colors" style={{
                                            color: theme.primary
                                        }}>
                                            {result.title}
                                        </h3>
                                        <p className="text-sm text-green-400 mb-3 break-all">
                                            {result.displayLink}
                                        </p>
                                        <p className="text-gray-300 group-hover:text-white transition-colors">
                                            {result.snippet}
                                        </p>
                                    </a>
                                </div>
                            ))}
                        </div>
                    )}

                    {/* No Results */}
                    {!loading && searched && results.length === 0 && (
                        <div className="text-center py-12">
                            <p className="text-2xl mb-2" style={{ color: theme.primary }}>Nenhum resultado encontrado</p>
                            <p className="text-gray-400">Tente usar outras palavras-chave</p>
                        </div>
                    )}
                </main>
            </div>

            {/* Settings Modal */}
            <SettingsModal 
                isOpen={showSettings} 
                onClose={() => setShowSettings(false)}
                currentTheme={currentTheme}
                currentPersonality={currentPersonality}
                onThemeChange={handleThemeChange}
                onPersonalityChange={handlePersonalityChange}
                theme={theme}
            />
        </div>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<StellaSearch />);