const { useState, useEffect, useContext, createContext, useRef } = React;

// Check if React Router loaded properly
const ReactRouter = window.ReactRouterDOM || window.ReactRouter;
const { BrowserRouter, Routes, Route, Navigate, Link, useNavigate, useLocation } = ReactRouter || {};

// Auth Context
const AuthContext = createContext(null);

const AuthProvider = ({ children }) => {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const stored = localStorage.getItem('faith_user');
        if (stored) {
            setUser(JSON.parse(stored));
        }
        setLoading(false);
    }, []);

    const login = async (email, password) => {
        // Mock Supabase auth - replace with actual Supabase implementation
        const mockUser = { 
            id: Date.now(), 
            email, 
            name: email.split('@')[0],
            created_at: new Date().toISOString()
        };
        setUser(mockUser);
        localStorage.setItem('faith_user', JSON.stringify(mockUser));
        return { error: null };
    };

    const register = async (email, password, name) => {
        // Mock Supabase registration
        const mockUser = { 
            id: Date.now(), 
            email, 
            name: name || email.split('@')[0],
            created_at: new Date().toISOString()
        };
        setUser(mockUser);
        localStorage.setItem('faith_user', JSON.stringify(mockUser));
        return { error: null };
    };

    const logout = () => {
        setUser(null);
        localStorage.removeItem('faith_user');
    };

    const updateProfile = (updates) => {
        const updated = { ...user, ...updates };
        setUser(updated);
        localStorage.setItem('faith_user', JSON.stringify(updated));
    };

    return (
        <AuthContext.Provider value={{ user, login, register, logout, updateProfile, loading }}>
            {children}
        </AuthContext.Provider>
    );
};

const useAuth = () => useContext(AuthContext);

// Protected Route Component
const ProtectedRoute = ({ children }) => {
    const { user, loading } = useAuth();
    const location = useLocation();

    if (loading) {
        return (
            <div className="min-h-screen flex items-center justify-center">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-faith-600"></div>
            </div>
        );
    }

    if (!user) {
        return <Navigate to="/login" state={{ from: location }} replace />;
    }

    return children;
};

// Navigation Component
const Navbar = () => {
    const { user, logout } = useAuth();
    const navigate = useNavigate();
    const [isOpen, setIsOpen] = useState(false);

    const handleLogout = () => {
        logout();
        navigate('/');
    };

    return (
        <nav className="bg-white shadow-sm border-b border-warm-200 sticky top-0 z-50">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div className="flex justify-between h-16">
                    <div className="flex items-center">
                        <Link to="/dashboard" className="flex items-center space-x-2">
                            <div className="w-8 h-8 bg-gradient-to-br from-faith-500 to-faith-700 rounded-lg flex items-center justify-center text-white font-bold">
                                F
                            </div>
                            <span className="text-xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-faith-600 to-faith-800">
                                FaithAI
                            </span>
                        </Link>
                    </div>

                    {/* Desktop Navigation */}
                    <div className="hidden md:flex items-center space-x-8">
                        {user ? (
                            <>
                                <Link to="/dashboard" className="nav-item text-warm-600 hover:text-faith-600 font-medium">Dashboard</Link>
                                <Link to="/bible" className="nav-item text-warm-600 hover:text-faith-600 font-medium">Bible</Link>
                                <Link to="/study" className="nav-item text-warm-600 hover:text-faith-600 font-medium">Study</Link>
                                <Link to="/chat" className="nav-item text-warm-600 hover:text-faith-600 font-medium">AI Chat</Link>
                                <Link to="/devotion" className="nav-item text-warm-600 hover:text-faith-600 font-medium">Devotion</Link>
                                <Link to="/support" className="nav-item text-warm-600 hover:text-faith-600 font-medium">Support</Link>
                                <div className="relative group">
                                    <button className="flex items-center space-x-2 text-warm-700 hover:text-faith-600">
                                        <div className="w-8 h-8 rounded-full bg-faith-100 flex items-center justify-center text-faith-700 font-semibold">
                                            {user.name?.[0]?.toUpperCase()}
                                        </div>
                                    </button>
                                    <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-warm-200 py-1 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all">
                                        <Link to="/profile" className="block px-4 py-2 text-sm text-warm-700 hover:bg-faith-50">Profile</Link>
                                        <button onClick={handleLogout} className="w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50">Sign Out</button>
                                    </div>
                                </div>
                            </>
                        ) : (
                            <>
                                <Link to="/login" className="text-warm-600 hover:text-faith-600 font-medium">Sign In</Link>
                                <Link to="/register" className="bg-faith-600 text-white px-4 py-2 rounded-lg hover:bg-faith-700 transition">Get Started</Link>
                            </>
                        )}
                    </div>

                    {/* Mobile menu button */}
                    <div className="md:hidden flex items-center">
                        <button onClick={() => setIsOpen(!isOpen)} className="text-warm-600 hover:text-warm-900">
                            <i data-lucide={isOpen ? "x" : "menu"} className="w-6 h-6"></i>
                        </button>
                    </div>
                </div>
            </div>

            {/* Mobile Navigation */}
            {isOpen && (
                <div className="md:hidden bg-white border-t border-warm-200">
                    <div className="px-2 pt-2 pb-3 space-y-1">
                        {user ? (
                            <>
                                <Link to="/dashboard" className="block px-3 py-2 rounded-md text-base font-medium text-warm-700 hover:text-faith-600 hover:bg-faith-50">Dashboard</Link>
                                <Link to="/bible" className="block px-3 py-2 rounded-md text-base font-medium text-warm-700 hover:text-faith-600 hover:bg-faith-50">Bible</Link>
                                <Link to="/study" className="block px-3 py-2 rounded-md text-base font-medium text-warm-700 hover:text-faith-600 hover:bg-faith-50">Study</Link>
                                <Link to="/chat" className="block px-3 py-2 rounded-md text-base font-medium text-warm-700 hover:text-faith-600 hover:bg-faith-50">AI Chat</Link>
                                <Link to="/devotion" className="block px-3 py-2 rounded-md text-base font-medium text-warm-700 hover:text-faith-600 hover:bg-faith-50">Devotion</Link>
                                <Link to="/support" className="block px-3 py-2 rounded-md text-base font-medium text-warm-700 hover:text-faith-600 hover:bg-faith-50">Support</Link>
                                <Link to="/profile" className="block px-3 py-2 rounded-md text-base font-medium text-warm-700 hover:text-faith-600 hover:bg-faith-50">Profile</Link>
                                <button onClick={handleLogout} className="w-full text-left px-3 py-2 rounded-md text-base font-medium text-red-600 hover:bg-red-50">Sign Out</button>
                            </>
                        ) : (
                            <>
                                <Link to="/login" className="block px-3 py-2 rounded-md text-base font-medium text-warm-700 hover:text-faith-600 hover:bg-faith-50">Sign In</Link>
                                <Link to="/register" className="block px-3 py-2 rounded-md text-base font-medium text-faith-600 hover:bg-faith-50">Get Started</Link>
                            </>
                        )}
                    </div>
                </div>
            )}
        </nav>
    );
};

// Layout Component
const Layout = ({ children }) => (
    <div className="min-h-screen bg-warm-50">
        <Navbar />
        <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            {children}
        </main>
    </div>
);

// Landing Page
const LandingPage = () => {
    useEffect(() => {
        lucide.createIcons();
    }, []);

    return (
        <div className="min-h-screen bg-white">
            {/* Hero Section */}
            <div className="relative overflow-hidden">
                <div className="absolute inset-0 bg-gradient-to-br from-faith-50 via-white to-warm-100"></div>
                <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-20 pb-16 text-center">
                    <h1 className="text-5xl md:text-6xl font-bold text-warm-900 mb-6 serif">
                        Deepen Your <span className="text-faith-600">Faith</span> with AI
                    </h1>
                    <p className="mt-4 text-xl text-warm-600 max-w-2xl mx-auto mb-8">
                        Experience spiritual growth through AI-powered Bible study, personalized devotions, and compassionate spiritual guidance available 24/7.
                    </p>
                    <div className="flex justify-center gap-4">
                        <Link to="/register" className="bg-faith-600 text-white px-8 py-4 rounded-full font-semibold hover:bg-faith-700 transition shadow-lg hover:shadow-xl transform hover:-translate-y-1">
                            Start Your Journey
                        </Link>
                        <Link to="/login" className="bg-white text-faith-600 border-2 border-faith-600 px-8 py-4 rounded-full font-semibold hover:bg-faith-50 transition">
                            Sign In
                        </Link>
                    </div>
                </div>
            </div>

            {/* Features Grid */}
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
                <div className="text-center mb-12">
                    <h2 className="text-3xl font-bold text-warm-900 mb-4">Features for Your Spiritual Journey</h2>
                    <p className="text-warm-600">Everything you need to grow in faith and understanding</p>
                </div>
                
                <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
                    {[
                        { icon: "book-open", title: "Bible Study", desc: "AI-powered explanations with historical and theological context", color: "blue" },
                        { icon: "message-circle", title: "Spiritual Chat", desc: "Real-time conversations for guidance and support", color: "purple" },
                        { icon: "heart", title: "Emotional Support", desc: "Comfort and scripture-based encouragement", color: "rose" },
                        { icon: "sun", title: "Daily Devotion", desc: "Personalized prayers and scripture readings", color: "amber" },
                        { icon: "search", title: "Bible Search", desc: "Browse and search scripture with ease", color: "emerald" },
                        { icon: "shield", title: "Safe Space", desc: "Private, secure, and judgment-free environment", color: "indigo" }
                    ].map((feature, idx) => (
                        <div key={idx} className="bg-white p-6 rounded-2xl shadow-sm border border-warm-200 hover:shadow-md transition verse-card">
                            <div className={`w-12 h-12 rounded-lg bg-${feature.color}-100 flex items-center justify-center mb-4`}>
                                <i data-lucide={feature.icon} className={`w-6 h-6 text-${feature.color}-600`}></i>
                            </div>
                            <h3 className="text-xl font-semibold text-warm-900 mb-2">{feature.title}</h3>
                            <p className="text-warm-600">{feature.desc}</p>
                        </div>
                    ))}
                </div>
            </div>

            {/* Scripture Section */}
            <div className="bg-faith-900 text-white py-16">
                <div className="max-w-4xl mx-auto px-4 text-center">
                    <i data-lucide="quote" className="w-12 h-12 mx-auto mb-6 text-faith-400"></i>
                    <blockquote className="text-2xl md:text-3xl serif italic mb-4">
                        "Your word is a lamp to my feet and a light to my path."
                    </blockquote>
                    <cite className="text-faith-300">Psalm 119:105</cite>
                </div>
            </div>
        </div>
    );
};

// Login Page
const LoginPage = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);
    const { login } = useAuth();
    const navigate = useNavigate();

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');
        setLoading(true);
        
        const { error } = await login(email, password);
        
        if (error) {
            setError(error.message);
        } else {
            navigate('/dashboard');
        }
        
        setLoading(false);
    };

    return (
        <div className="min-h-screen bg-gradient-to-br from-faith-50 to-warm-100 flex items-center justify-center px-4">
            <div className="max-w-md w-full bg-white rounded-2xl shadow-xl p-8">
                <div className="text-center mb-8">
                    <div className="w-16 h-16 bg-faith-600 rounded-2xl flex items-center justify-center mx-auto mb-4 text-white text-2xl font-bold">
                        F
                    </div>
                    <h2 className="text-2xl font-bold text-warm-900">Welcome Back</h2>
                    <p className="text-warm-600">Continue your spiritual journey</p>
                </div>

                {error && (
                    <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">
                        {error}
                    </div>
                )}

                <form onSubmit={handleSubmit} className="space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-warm-700 mb-1">Email</label>
                        <input 
                            type="email" 
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            className="w-full px-4 py-2 border border-warm-300 rounded-lg focus:ring-2 focus:ring-faith-500 focus:border-transparent outline-none"
                            placeholder="you@example.com"
                            required
                        />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-warm-700 mb-1">Password</label>
                        <input 
                            type="password" 
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            className="w-full px-4 py-2 border border-warm-300 rounded-lg focus:ring-2 focus:ring-faith-500 focus:border-transparent outline-none"
                            placeholder="••••••••"
                            required
                        />
                    </div>
                    <button 
                        type="submit" 
                        disabled={loading}
                        className="w-full bg-faith-600 text-white py-2 rounded-lg hover:bg-faith-700 transition disabled:opacity-50 font-semibold"
                    >
                        {loading ? 'Signing in...' : 'Sign In'}
                    </button>
                </form>

                <p className="mt-6 text-center text-sm text-warm-600">
                    Don't have an account?{' '}
                    <Link to="/register" className="text-faith-600 hover:underline font-medium">
                        Create one
                    </Link>
                </p>
            </div>
        </div>
    );
};

// Register Page
const RegisterPage = () => {
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);
    const { register } = useAuth();
    const navigate = useNavigate();

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');
        setLoading(true);
        
        const { error } = await register(email, password, name);
        
        if (error) {
            setError(error.message);
        } else {
            navigate('/dashboard');
        }
        
        setLoading(false);
    };

    return (
        <div className="min-h-screen bg-gradient-to-br from-faith-50 to-warm-100 flex items-center justify-center px-4">
            <div className="max-w-md w-full bg-white rounded-2xl shadow-xl p-8">
                <div className="text-center mb-8">
                    <div className="w-16 h-16 bg-faith-600 rounded-2xl flex items-center justify-center mx-auto mb-4 text-white text-2xl font-bold">
                        F
                    </div>
                    <h2 className="text-2xl font-bold text-warm-900">Begin Your Journey</h2>
                    <p className="text-warm-600">Join our community of faith</p>
                </div>

                {error && (
                    <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">
                        {error}
                    </div>
                )}

                <form onSubmit={handleSubmit} className="space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-warm-700 mb-1">Full Name</label>
                        <input 
                            type="text" 
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                            className="w-full px-4 py-2 border border-warm-300 rounded-lg focus:ring-2 focus:ring-faith-500 focus:border-transparent outline-none"
                            placeholder="John Doe"
                            required
                        />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-warm-700 mb-1">Email</label>
                        <input 
                            type="email" 
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            className="w-full px-4 py-2 border border-warm-300 rounded-lg focus:ring-2 focus:ring-faith-500 focus:border-transparent outline-none"
                            placeholder="you@example.com"
                            required
                        />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-warm-700 mb-1">Password</label>
                        <input 
                            type="password" 
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            className="w-full px-4 py-2 border border-warm-300 rounded-lg focus:ring-2 focus:ring-faith-500 focus:border-transparent outline-none"
                            placeholder="••••••••"
                            required
                        />
                    </div>
                    <button 
                        type="submit" 
                        disabled={loading}
                        className="w-full bg-faith-600 text-white py-2 rounded-lg hover:bg-faith-700 transition disabled:opacity-50 font-semibold"
                    >
                        {loading ? 'Creating account...' : 'Create Account'}
                    </button>
                </form>

                <p className="mt-6 text-center text-sm text-warm-600">
                    Already have an account?{' '}
                    <Link to="/login" className="text-faith-600 hover:underline font-medium">
                        Sign in
                    </Link>
                </p>
            </div>
        </div>
    );
};

// Dashboard Page
const Dashboard = () => {
    const { user } = useAuth();
    const navigate = useNavigate();
    
    useEffect(() => {
        lucide.createIcons();
    }, []);

    const features = [
        { 
            title: "AI Chat", 
            desc: "Talk with your spiritual companion", 
            icon: "message-circle", 
            color: "bg-blue-500", 
            path: "/chat",
            verse: "Call to me and I will answer you"
        },
        { 
            title: "Bible Study", 
            desc: "Deep dive with AI explanations", 
            icon: "book-open", 
            color: "bg-purple-500", 
            path: "/study",
            verse: "Study to show yourself approved"
        },
        { 
            title: "Daily Devotion", 
            desc: "Start your day with scripture", 
            icon: "sun", 
            color: "bg-amber-500", 
            path: "/devotion",
            verse: "His mercies are new every morning"
        },
        { 
            title: "Emotional Support", 
            desc: "Find comfort in God's word", 
            icon: "heart", 
            color: "bg-rose-500", 
            path: "/support",
            verse: "The Lord is close to the brokenhearted"
        },
        { 
            title: "Read Bible", 
            desc: "Browse and search scripture", 
            icon: "search", 
            color: "bg-emerald-500", 
            path: "/bible",
            verse: "Your word is a lamp to my feet"
        },
        { 
            title: "Profile", 
            desc: "Manage your account", 
            icon: "user", 
            color: "bg-gray-500", 
            path: "/profile",
            verse: "I am fearfully and wonderfully made"
        }
    ];

    return (
        <div className="space-y-8">
            <div className="bg-gradient-to-r from-faith-600 to-faith-800 rounded-3xl p-8 text-white shadow-lg">
                <h1 className="text-3xl font-bold mb-2">Welcome back, {user?.name} ✨</h1>
                <p className="text-faith-100">How can we support your walk with God today?</p>
            </div>

            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                {features.map((feature, idx) => (
                    <button 
                        key={idx}
                        onClick={() => navigate(feature.path)}
                        className="text-left bg-white p-6 rounded-2xl shadow-sm border border-warm-200 hover:shadow-lg transition verse-card group"
                    >
                        <div className={`w-12 h-12 ${feature.color} rounded-xl flex items-center justify-center text-white mb-4 group-hover:scale-110 transition`}>
                            <i data-lucide={feature.icon} className="w-6 h-6"></i>
                        </div>
                        <h3 className="text-lg font-semibold text-warm-900 mb-1">{feature.title}</h3>
                        <p className="text-sm text-warm-600 mb-3">{feature.desc}</p>
                        <p className="text-xs text-faith-600 italic serif">"{feature.verse}"</p>
                    </button>
                ))}
            </div>

            <div className="bg-warm-100 rounded-2xl p-6">
                <h3 className="text-lg font-semibold text-warm-900 mb-4 flex items-center gap-2">
                    <i data-lucide="sparkles" className="w-5 h-5 text-faith-600"></i>
                    Today's Inspiration
                </h3>
                <blockquote className="serif text-xl text-warm-800 italic">
                    "For I know the plans I have for you, declares the Lord, plans to prosper you and not to harm you, plans to give you hope and a future."
                </blockquote>
                <cite className="block mt-2 text-warm-600 not-italic">Jeremiah 29:11</cite>
            </div>
        </div>
    );
};

// AI Chat Page with WebSocket Simulation
const AIChat = () => {
    const [messages, setMessages] = useState([
        { type: 'ai', text: "Hello! I'm here to walk alongside you in your spiritual journey. How can I support you today?", timestamp: new Date() }
    ]);
    const [input, setInput] = useState('');
    const [isConnected, setIsConnected] = useState(true);
    const [isTyping, setIsTyping] = useState(false);
    const messagesEndRef = useRef(null);

    // Simulate WebSocket connection
    useEffect(() => {
        console.log('WebSocket Connected (Simulated)');
        return () => console.log('WebSocket Disconnected');
    }, []);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    };

    useEffect(() => {
        scrollToBottom();
        lucide.createIcons();
    }, [messages]);

    const generateAIResponse = (userText) => {
        const lower = userText.toLowerCase();
        let responses = [];
        
        if (lower.includes('pray') || lower.includes('prayer')) {
            responses = [
                "Prayer is our direct line to God. Would you like me to help you structure a prayer, or would you prefer a moment of guided meditation?",
                "Remember, prayer doesn't need to be perfect - God hears your heart. Philippians 4:6 tells us 'Do not be anxious about anything, but in every situation, by prayer and petition, with thanksgiving, present your requests to God.'"
            ];
        } else if (lower.includes('sad') || lower.includes('depressed') || lower.includes('hurt')) {
            responses = [
                "I'm sorry you're feeling this way. Psalm 34:18 reminds us that 'The Lord is close to the brokenhearted and saves those who are crushed in spirit.' You're not alone in this.",
                "It's okay to feel pain. Even Jesus wept. Would you like me to suggest some Psalms of comfort, or would you prefer to talk about what you're experiencing?"
            ];
        } else if (lower.includes('bible') || lower.includes('scripture')) {
            responses = [
                "The Bible is living and active! Are you looking for a specific verse, or would you like guidance on where to start reading?",
                "2 Timothy 3:16 tells us 'All Scripture is God-breathed and is useful for teaching, rebuking, correcting and training in righteousness.' What topic are you interested in exploring?"
            ];
        } else if (lower.includes('faith') || lower.includes('doubt')) {
            responses = [
                "Doubt is not the opposite of faith; it's part of the journey. Mark 9:24 shows us a father crying out 'I believe; help my unbelief!' God meets us where we are.",
                "Faith is built through relationship, not just knowledge. Would you like to explore ways to strengthen your faith walk?"
            ];
        } else if (lower.includes('help') || lower.includes('guidance')) {
            responses = [
                "I'm here to help. Proverbs 3:5-6 encourages us to 'Trust in the Lord with all your heart and lean not on your own understanding; in all your ways submit to him, and he will make your paths straight.' What guidance do you seek?"
            ];
        } else {
            responses = [
                "That's a thoughtful question. Let me reflect on that with you from a biblical perspective...",
                "I appreciate you sharing that. The Bible has wisdom for every situation. Could you tell me more so I can better support you?",
                "Every conversation with you is meaningful. As Colossians 3:16 says, 'Let the message of Christ dwell among you richly...' How else can I assist you today?"
            ];
        }
        
        return responses[Math.floor(Math.random() * responses.length)];
    };

    const handleSend = async (e) => {
        e.preventDefault();
        if (!input.trim()) return;

        const userMsg = { type: 'user', text: input, timestamp: new Date() };
        setMessages(prev => [...prev, userMsg]);
        setInput('');
        setIsTyping(true);

        // Simulate network delay and AI processing
        setTimeout(() => {
            const aiResponse = generateAIResponse(userMsg.text);
            const aiMsg = { type: 'ai', text: aiResponse, timestamp: new Date() };
            setMessages(prev => [...prev, aiMsg]);
            setIsTyping(false);
        }, 1500 + Math.random() * 1000);
    };

    return (
        <div className="max-w-4xl mx-auto h-[calc(100vh-8rem)] flex flex-col bg-white rounded-2xl shadow-sm border border-warm-200 overflow-hidden">
            <div className="bg-faith-600 text-white p-4 flex items-center justify-between">
                <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center">
                        <i data-lucide="sparkles" className="w-5 h-5"></i>
                    </div>
                    <div>
                        <h3 className="font-semibold">Faith Assistant</h3>
                        <p className="text-xs text-faith-200 flex items-center gap-1">
                            <span className={`w-2 h-2 rounded-full ${isConnected ? 'bg-green-400' : 'bg-red-400'}`}></span>
                            {isConnected ? 'Online' : 'Reconnecting...'}
                        </p>
                    </div>
                </div>
                <button className="p-2 hover:bg-white/10 rounded-lg transition">
                    <i data-lucide="more-vertical" className="w-5 h-5"></i>
                </button>
            </div>

            <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-warm-50">
                {messages.map((msg, idx) => (
                    <div key={idx} className={`flex ${msg.type === 'user' ? 'justify-end' : 'justify-start'} chat-bubble`}>
                        <div className={`max-w-[80%] p-4 rounded-2xl ${
                            msg.type === 'user' 
                                ? 'bg-faith-600 text-white rounded-br-none' 
                                : 'bg-white border border-warm-200 text-warm-800 rounded-bl-none shadow-sm'
                        }`}>
                            <p className="leading-relaxed">{msg.text}</p>
                            <span className={`text-xs mt-2 block ${msg.type === 'user' ? 'text-faith-200' : 'text-warm-400'}`}>
                                {msg.timestamp.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
                            </span>
                        </div>
                    </div>
                ))}
                {isTyping && (
                    <div className="flex justify-start chat-bubble">
                        <div className="bg-white border border-warm-200 p-4 rounded-2xl rounded-bl-none shadow-sm">
                            <div className="flex gap-1">
                                <span className="w-2 h-2 bg-warm-400 rounded-full animate-bounce"></span>
                                <span className="w-2 h-2 bg-warm-400 rounded-full animate-bounce" style={{animationDelay: '0.1s'}}></span>
                                <span className="w-2 h-2 bg-warm-400 rounded-full animate-bounce" style={{animationDelay: '0.2s'}}></span>
                            </div>
                        </div>
                    </div>
                )}
                <div ref={messagesEndRef} />
            </div>

            <form onSubmit={handleSend} className="p-4 bg-white border-t border-warm-200 flex gap-2">
                <button type="button" className="p-2 text-warm-400 hover:text-faith-600 transition">
                    <i data-lucide="paperclip" className="w-5 h-5"></i>
                </button>
                <input
                    type="text"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    placeholder="Share your thoughts, questions, or prayers..."
                    className="flex-1 px-4 py-2 border border-warm-300 rounded-full focus:ring-2 focus:ring-faith-500 focus:border-transparent outline-none"
                />
                <button 
                    type="submit" 
                    disabled={!input.trim()}
                    className="p-2 bg-faith-600 text-white rounded-full hover:bg-faith-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    <i data-lucide="send" className="w-5 h-5"></i>
                </button>
            </form>
        </div>
    );
};

// Bible Page
const BiblePage = () => {
    const [books, setBooks] = useState([]);
    const [selectedBook, setSelectedBook] = useState('');
    const [chapter, setChapter] = useState(1);
    const [verses, setVerses] = useState([]);
    const [loading, setLoading] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');

    useEffect(() => {
        // Common Bible books
        setBooks([
            'Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteronomy',
            'Joshua', 'Judges', 'Ruth', '1 Samuel', '2 Samuel',
            'Psalms', 'Proverbs', 'Ecclesiastes', 'Isaiah', 'Jeremiah',
            'Matthew', 'Mark', 'Luke', 'John', 'Acts',
            'Romans', '1 Corinthians', '2 Corinthians', 'Galatians', 'Ephesians',
            'Philippians', 'Colossians', 'Hebrews', 'James', '1 Peter',
            'Revelation'
        ]);
    }, []);

    const fetchChapter = async () => {
        if (!selectedBook) return;
        setLoading(true);
        try {
            const query = searchQuery ? `${selectedBook} ${searchQuery}` : `${selectedBook} ${chapter}`;
            const response = await axios.get(`https://bible-api.com/${encodeURIComponent(query)}`);
            if (response.data && response.data.verses) {
                setVerses(response.data.verses);
            } else if (response.data && response.data.text) {
                // Handle single verse or range response
                setVerses([{
                    verse: response.data.verses ? response.data.verses[0].verse : 1,
                    text: response.data.text
                }]);
            }
        } catch (error) {
            console.error('Error fetching Bible:', error);
        }
        setLoading(false);
    };

    return (
        <div className="space-y-6">
            <div className="bg-white p-6 rounded-2xl shadow-sm border border-warm-200">
                <h2 className="text-2xl font-bold text-warm-900 mb-4 flex items-center gap-2">
                    <i data-lucide="book" className="w-6 h-6 text-faith-600"></i>
                    Scripture Browser
                </h2>
                
                <div className="grid md:grid-cols-3 gap-4 mb-6">
                    <div>
                        <label className="block text-sm font-medium text-warm-700 mb-2">Book</label>
                        <select 
                            value={selectedBook}
                            onChange={(e) => setSelectedBook(e.target.value)}
                            className="w-full px-3 py-2 border border-warm-300 rounded-lg focus:ring-2 focus:ring-faith-500 outline-none"
                        >
                            <option value="">Select a book...</option>
                            {books.map(book => (
                                <option key={book} value={book}>{book}</option>
                            ))}
                        </select>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-warm-700 mb-2">Chapter/Verse</label>
                        <input
                            type="text"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            placeholder="e.g., 3:16 or 1-5"
                            className="w-full px-3 py-2 border border-warm-300 rounded-lg focus:ring-2 focus:ring-faith-500 outline-none"
                        />
                    </div>
                    <div className="flex items-end">
                        <button 
                            onClick={fetchChapter}
                            disabled={!selectedBook || loading}
                            className="w-full bg-faith-600 text-white py-2 rounded-lg hover:bg-faith-700 transition disabled:opacity-50 font-medium"
                        >
                            {loading ? 'Loading...' : 'Read Scripture'}
                        </button>
                    </div>
                </div>

                {verses.length > 0 && (
                    <div className="bg-warm-50 p-6 rounded-xl border border-warm-200">
                        <h3 className="text-lg font-semibold text-faith-800 mb-4 serif">
                            {selectedBook} {searchQuery || chapter}
                        </h3>
                        <div className="space-y-3">
                            {verses.map((v) => (
                                <div key={v.verse} className="flex gap-3">
                                    <span className="text-faith-600 font-bold text-sm mt-1">{v.verse}</span>
                                    <p className="text-warm-800 leading-relaxed">{v.text}</p>
                                </div>
                            ))}
                        </div>
                        <div className="mt-6 flex gap-3">
                            <button className="flex items-center gap-2 px-4 py-2 bg-white border border-warm-300 rounded-lg text-sm hover:bg-faith-50 transition">
                                <i data-lucide="bookmark" className="w-4 h-4"></i>
                                Save
                            </button>
                            <button className="flex items-center gap-2 px-4 py-2 bg-white border border-warm-300 rounded-lg text-sm hover:bg-faith-50 transition">
                                <i data-lucide="share-2" className="w-4 h-4"></i>
                                Share
                            </button>
                            <button className="flex items-center gap-2 px-4 py-2 bg-faith-100 text-faith-700 rounded-lg text-sm hover:bg-faith-200 transition">
                                <i data-lucide="lightbulb" className="w-4 h-4"></i>
                                Study This
                            </button>
                        </div>
                    </div>
                )}
            </div>

            <div className="grid md:grid-cols-2 gap-6">
                <div className="bg-gradient-to-br from-faith-500 to-faith-700 p-6 rounded-2xl text-white">
                    <h3 className="font-semibold mb-2 flex items-center gap-2">
                        <i data-lucide="bookmark" className="w-5 h-5"></i>
                        Popular Verses
                    </h3>
                    <ul className="space-y-2 text-sm text-faith-100">
                        <li>• John 3:16 - For God so loved the world...</li>
                        <li>• Jeremiah 29:11 - Plans to prosper you...</li>
                        <li>• Romans 8:28 - All things work together...</li>
                        <li>• Philippians 4:13 - I can do all things...</li>
                    </ul>
                </div>
                <div className="bg-white p-6 rounded-2xl shadow-sm border border-warm-200">
                    <h3 className="font-semibold text-warm-900 mb-2 flex items-center gap-2">
                        <i data-lucide="history" className="w-5 h-5 text-faith-600"></i>
                        Recently Viewed
                    </h3>
                    <p className="text-warm-500 text-sm italic">Your reading history will appear here...</p>
                </div>
            </div>
        </div>
    );
};

// Bible Study Page
const BibleStudyPage = () => {
    const [reference, setReference] = useState('');
    const [study, setStudy] = useState(null);
    const [loading, setLoading] = useState(false);

    const generateStudy = async () => {
        if (!reference.trim()) return;
        setLoading(true);
        
        // Simulate AI processing
        setTimeout(() => {
            const studies = {
                'john 3:16': {
                    context: "Written by the Apostle John, this verse appears in Jesus' conversation with Nicodemus about being born again.",
                    historical: "In the first century, 'God so loved the world' was radical - showing God's love extended beyond Israel to all nations (Greek: kosmos).",
                    theological: "The doctrine of God's agape love - unconditional and sacrificial. The word 'so' (houtos) emphasizes the manner and degree of love.",
                    application: "This verse reminds us that salvation is a gift, not earned. How can we live today reflecting this undeserved grace to others?",
                    keywords: ['Love', 'Sacrifice', 'Salvation', 'Faith']
                },
                'default': {
                    context: `This passage from ${reference} appears within the broader narrative of Scripture, connecting to themes of redemption and hope.`,
                    historical: "Historically, this text would have spoken to its original audience in powerful ways, addressing their specific cultural and spiritual needs.",
                    theological: "Theologically, this verse reveals aspects of God's character - His faithfulness, mercy, and sovereign plan for humanity.",
                    application: "Application: Consider how this truth changes your perspective today. Where do you need to apply this promise or command in your current circumstances?",
                    keywords: ['Faith', 'Trust', 'Obedience', 'Grace']
                }
            };
            
            const key = reference.toLowerCase();
            setStudy(studies[key] || studies['default']);
            setLoading(false);
        }, 2000);
    };

    return (
        <div className="max-w-4xl mx-auto space-y-6">
            <div className="bg-white p-6 rounded-2xl shadow-sm border border-warm-200">
                <h2 className="text-2xl font-bold text-warm-900 mb-4">AI Bible Study</h2>
                <p className="text-warm-600 mb-4">Enter a verse or passage to receive historical context, theological insights, and personal application.</p>
                
                <div className="flex gap-2">
                    <input
                        type="text"
                        value={reference}
                        onChange={(e) => setReference(e.target.value)}
                        placeholder="e.g., John 3:16 or Romans 8:28"
                        className="flex-1 px-4 py-2 border border-warm-300 rounded-lg focus:ring-2 focus:ring-faith-500 outline-none"
                        onKeyPress={(e) => e.key === 'Enter' && generateStudy()}
                    />
                    <button 
                        onClick={generateStudy}
                        disabled={loading}
                        className="px-6 py-2 bg-faith-600 text-white rounded-lg hover:bg-faith-700 transition disabled:opacity-50 flex items-center gap-2"
                    >
                        {loading ? (
                            <>
                                <span className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></span>
                                Studying...
                            </>
                        ) : (
                            <>
                                <i data-lucide="search" className="w-4 h-4"></i>
                                Study
                            </>
                        )}
                    </button>
                </div>
            </div>

            {study && (
                <div className="space-y-4 animate-in fade-in slide-in-from-bottom-4">
                    <div className="bg-blue-50 border-l-4 border-blue-500 p-4 rounded-r-lg">
                        <h3 className="font-semibold text-blue-900 mb-1 flex items-center gap-2">
                            <i data-lucide="clock" className="w-4 h-4"></i>
                            Historical Context
                        </h3>
                        <p className="text-blue-800 text-sm leading-relaxed">{study.historical}</p>
                    </div>

                    <div className="bg-purple-50 border-l-4 border-purple-500 p-4 rounded-r-lg">
                        <h3 className="font-semibold text-purple-900 mb-1 flex items-center gap-2">
                            <i data-lucide="book-open" className="w-4 h-4"></i>
                            Literary Context
                        </h3>
                        <p className="text-purple-800 text-sm leading-relaxed">{study.context}</p>
                    </div>

                    <div className="bg-faith-50 border-l-4 border-faith-500 p-4 rounded-r-lg">
                        <h3 className="font-semibold text-faith-900 mb-1 flex items-center gap-2">
                            <i data-lucide="cross" className="w-4 h-4"></i>
                            Theological Insights
                        </h3>
                        <p className="text-faith-800 text-sm leading-relaxed">{study.theological}</p>
                    </div>

                    <div className="bg-amber-50 border-l-4 border-amber-500 p-4 rounded-r-lg">
                        <h3 className="font-semibold text-amber-900 mb-1 flex items-center gap-2">
                            <i data-lucide="heart" className="w-4 h-4"></i>
                            Personal Application
                        </h3>
                        <p className="text-amber-800 text-sm leading-relaxed">{study.application}</p>
                    </div>

                    <div className="flex gap-2 mt-4">
                        {study.keywords.map((kw, idx) => (
                            <span key={idx} className="px-3 py-1 bg-warm-100 text-warm-700 rounded-full text-xs font-medium">
                                #{kw}
                            </span>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
};

// Emotional Support Page
const EmotionalSupportPage = () => {
    const [selectedMood, setSelectedMood] = useState(null);
    const [comfort, setComfort] = useState(null);

    const moods = [
        { id: 'anxious', label: 'Anxious', icon: 'cloud-rain', color: 'bg-blue-100 text-blue-700', verse: 'Philippians 4:6-7', text: 'Do not be anxious about anything... the peace of God will guard your hearts.' },
        { id: 'sad', label: 'Sad', icon: 'cloud', color: 'bg-gray-100 text-gray-700', verse: 'Psalm 34:18', text: 'The Lord is close to the brokenhearted and saves those who are crushed in spirit.' },
        { id: 'afraid', label: 'Afraid', icon: 'alert-circle', color: 'bg-red-100 text-red-700', verse: 'Isaiah 41:10', text: 'Do not fear, for I am with you; do not be dismayed, for I am your God.' },
        { id: 'angry', label: 'Angry', icon: 'flame', color: 'bg-orange-100 text-orange-700', verse: 'Ephesians 4:26', text: 'In your anger do not sin. Do not let the sun go down while you are still angry.' },
        { id: 'lonely', label: 'Lonely', icon: 'user-x', color: 'bg-purple-100 text-purple-700', verse: 'Deuteronomy 31:6', text: 'The Lord your God goes with you; he will never leave you nor forsake you.' },
        { id: 'hopeful', label: 'Hopeful', icon: 'sun', color: 'bg-amber-100 text-amber-700', verse: 'Romans 15:13', text: 'May the God of hope fill you with all joy and peace as you trust in him.' }
    ];

    const selectMood = (mood) => {
        setSelectedMood(mood);
        setTimeout(() => setComfort(mood), 500);
    };

    return (
        <div className="max-w-4xl mx-auto space-y-6">
            <div className="text-center mb-8">
                <h2 className="text-3xl font-bold text-warm-900 mb-2">How are you feeling today?</h2>
                <p className="text-warm-600">Select your current emotion to receive comforting scripture and support</p>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                {moods.map((mood) => (
                    <button
                        key={mood.id}
                        onClick={() => selectMood(mood)}
                        className={`p-6 rounded-2xl border-2 transition-all ${
                            selectedMood?.id === mood.id 
                                ? 'border-faith-500 ring-2 ring-faith-200' 
                                : 'border-warm-200 hover:border-faith-300'
                        } ${mood.color} mood-btn`}
                    >
                        <i data-lucide={mood.icon} className="w-8 h-8 mx-auto mb-2"></i>
                        <span className="font-medium">{mood.label}</span>
                    </button>
                ))}
            </div>

            {comfort && (
                <div className="bg-white p-8 rounded-2xl shadow-lg border border-warm-200 text-center chat-bubble">
                    <div className="w-16 h-16 bg-faith-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i data-lucide="heart" className="w-8 h-8 text-faith-600"></i>
                    </div>
                    <blockquote className="text-xl md:text-2xl serif text-warm-800 italic mb-4 leading-relaxed">
                        "{comfort.text}"
                    </blockquote>
                    <cite className="text-faith-600 font-semibold not-italic block mb-6">— {comfort.verse}</cite>
                    
                    <div className="bg-warm-50 p-4 rounded-lg text-left">
                        <p className="text-sm text-warm-600 mb-2 font-medium">Reflection:</p>
                        <p className="text-warm-700 text-sm leading-relaxed">
                            Whatever you're feeling right now, know that God meets you in this moment. 
                            These emotions are valid, and Scripture acknowledges the full range of human experience. 
                            Take a deep breath and remember: you are loved, you are seen, and this moment will pass.
                        </p>
                    </div>

                    <div className="mt-6 flex justify-center gap-3">
                        <button className="px-4 py-2 bg-faith-600 text-white rounded-lg text-sm hover:bg-faith-700 transition">
                            Talk to AI Counselor
                        </button>
                        <button className="px-4 py-2 bg-white border border-warm-300 text-warm-700 rounded-lg text-sm hover:bg-warm-50 transition">
                            Save to Journal
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
};

// Daily Devotion Page
const DevotionPage = () => {
    const [devotion, setDevotion] = useState({
        title: "Walking in Faith",
        scripture: "Hebrews 11:1",
        verse: "Now faith is confidence in what we hope for and assurance about what we do not see.",
        reflection: "Faith is not blind optimism, but confident trust in God's character. Today, consider what areas of your life need that confident assurance. Even when circumstances seem uncertain, we can trust in the One who never changes.",
        prayer: "Lord, increase my faith today. Help me to trust You even when I cannot see the way forward. Give me confidence in Your promises and assurance of Your presence. Amen.",
        challenge: "Take a step of faith today - whether that's making a difficult decision, extending forgiveness, or starting a new habit. Write down what you're trusting God with."
    });

    const [prayerDone, setPrayerDone] = useState(false);

    return (
        <div className="max-w-3xl mx-auto">
            <div className="bg-gradient-to-br from-amber-50 to-orange-50 p-8 rounded-3xl shadow-sm border border-amber-200 mb-6">
                <div className="flex items-center justify-between mb-6">
                    <span className="text-amber-600 font-semibold text-sm uppercase tracking-wider">Today's Devotion</span>
                    <span className="text-amber-400 text-sm">{new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}</span>
                </div>
                
                <h1 className="text-3xl font-bold text-warm-900 mb-6 serif">{devotion.title}</h1>
                
                <div className="bg-white/70 backdrop-blur p-6 rounded-2xl mb-6 border border-amber-100">
                    <blockquote className="text-xl serif text-warm-800 italic mb-3 leading-relaxed">
                        "{devotion.verse}"
                    </blockquote>
                    <cite className="text-amber-700 font-semibold not-italic text-sm">{devotion.scripture}</cite>
                </div>

                <div className="space-y-6">
                    <div>
                        <h3 className="font-semibold text-amber-900 mb-2 flex items-center gap-2">
                            <i data-lucide="book-open" className="w-4 h-4"></i>
                            Reflection
                        </h3>
                        <p className="text-warm-700 leading-relaxed">{devotion.reflection}</p>
                    </div>

                    <div className="bg-white/50 p-4 rounded-xl border border-amber-100">
                        <h3 className="font-semibold text-amber-900 mb-2 flex items-center gap-2">
                            <i data-lucide="heart" className="w-4 h-4"></i>
                            Prayer
                        </h3>
                        <p className="text-warm-700 italic serif leading-relaxed mb-3">{devotion.prayer}</p>
                        <button 
                            onClick={() => setPrayerDone(!prayerDone)}
                            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition ${
                                prayerDone 
                                    ? 'bg-green-100 text-green-700' 
                                    : 'bg-amber-100 text-amber-700 hover:bg-amber-200'
                            }`}
                        >
                            <i data-lucide={prayerDone ? "check-circle" : "circle"} className="w-4 h-4"></i>
                            {prayerDone ? 'Prayer Completed' : 'Mark as Prayed'}
                        </button>
                    </div>

                    <div className="bg-amber-100/50 p-4 rounded-xl border border-amber-200">
                        <h3 className="font-semibold text-amber-900 mb-2 flex items-center gap-2">
                            <i data-lucide="target" className="w-4 h-4"></i>
                            Today's Challenge
                        </h3>
                        <p className="text-warm-700 text-sm leading-relaxed">{devotion.challenge}</p>
                    </div>
                </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
                <button className="bg-white p-4 rounded-xl shadow-sm border border-warm-200 text-left hover:shadow-md transition">
                    <span className="text-warm-500 text-xs uppercase tracking-wider block mb-1">Previous</span>
                    <span className="font-medium text-warm-900">Yesterday's Devotion</span>
                </button>
                <button className="bg-white p-4 rounded-xl shadow-sm border border-warm-200 text-left hover:shadow-md transition">
                    <span className="text-warm-500 text-xs uppercase tracking-wider block mb-1">Next</span>
                    <span className="font-medium text-warm-900">Tomorrow's Devotion</span>
                </button>
            </div>
        </div>
    );
};

// Profile Page
const ProfilePage = () => {
    const { user, updateProfile, logout } = useAuth();
    const navigate = useNavigate();
    const [name, setName] = useState(user?.name || '');
    const [savedVerses] = useState([
        { ref: 'Philippians 4:13', text: 'I can do all things through Christ...', date: '2024-01-15' },
        { ref: 'Psalm 23:1', text: 'The Lord is my shepherd...', date: '2024-01-10' }
    ]);

    const handleUpdate = (e) => {
        e.preventDefault();
        updateProfile({ name });
    };

    const handleLogout = () => {
        logout();
        navigate('/');
    };

    return (
        <div className="max-w-2xl mx-auto space-y-6">
            <div className="bg-white p-6 rounded-2xl shadow-sm border border-warm-200">
                <div className="flex items-center gap-4 mb-6">
                    <div className="w-20 h-20 rounded-full bg-faith-100 flex items-center justify-center text-3xl font-bold text-faith-700">
                        {user?.name?.[0]?.toUpperCase()}
                    </div>
                    <div>
                        <h2 className="text-2xl font-bold text-warm-900">{user?.name}</h2>
                        <p className="text-warm-600">{user?.email}</p>
                        <p className="text-xs text-warm-400 mt-1">Member since {new Date(user?.created_at).toLocaleDateString()}</p>
                    </div>
                </div>

                <form onSubmit={handleUpdate} className="space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-warm-700 mb-1">Display Name</label>
                        <input 
                            type="text" 
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                            className="w-full px-3 py-2 border border-warm-300 rounded-lg focus:ring-2 focus:ring-faith-500 outline-none"
                        />
                    </div>
                    <button type="submit" className="px-4 py-2 bg-faith-600 text-white rounded-lg hover:bg-faith-700 transition text-sm font-medium">
                        Update Profile
                    </button>
                </form>
            </div>

            <div className="bg-white p-6 rounded-2xl shadow-sm border border-warm-200">
                <h3 className="font-semibold text-warm-900 mb-4 flex items-center gap-2">
                    <i data-lucide="bookmark" className="w-5 h-5 text-faith-600"></i>
                    Saved Verses
                </h3>
                {savedVerses.length > 0 ? (
                    <div className="space-y-3">
                        {savedVerses.map((verse, idx) => (
                            <div key={idx} className="p-3 bg-warm-50 rounded-lg border border-warm-200">
                                <div className="flex justify-between items-start mb-1">
                                    <span className="font-semibold text-faith-700 text-sm">{verse.ref}</span>
                                    <span className="text-xs text-warm-400">{verse.date}</span>
                                </div>
                                <p className="text-sm text-warm-700">{verse.text}</p>
                            </div>
                        ))}
                    </div>
                ) : (
                    <p className="text-warm-500 text-sm italic">No saved verses yet...</p>
                )}
            </div>

            <button 
                onClick={handleLogout}
                className="w-full p-4 bg-red-50 text-red-600 rounded-2xl border border-red-200 hover:bg-red-100 transition flex items-center justify-center gap-2 font-medium"
            >
                <i data-lucide="log-out" className="w-5 h-5"></i>
                Sign Out
            </button>
        </div>
    );
};

// Main App Component
const App = () => {
    useEffect(() => {
        // Initialize Lucide icons after render
        setTimeout(() => {
            if (window.lucide) {
                lucide.createIcons();
            }
        }, 100);
    }, []);

    // If React Router isn't loaded, show error
    if (!BrowserRouter) {
        return (
            <div style={{ padding: '20px', textAlign: 'center', fontFamily: 'sans-serif' }}>
                <h2 style={{ color: '#dc2626' }}>Loading Error</h2>
                <p>Unable to load React Router. Please check your internet connection and refresh.</p>
                <p style={{ fontSize: '12px', color: '#666' }}>Error: ReactRouterDOM not found</p>
            </div>
        );
    }

    return (
        <AuthProvider>
            <BrowserRouter>
                <Routes>
                    <Route path="/" element={<LandingPage />} />
                    <Route path="/login" element={<LoginPage />} />
                    <Route path="/register" element={<RegisterPage />} />
                    <Route path="/dashboard" element={
                        <ProtectedRoute>
                            <Layout><Dashboard /></Layout>
                        </ProtectedRoute>
                    } />
                    <Route path="/chat" element={
                        <ProtectedRoute>
                            <Layout><AIChat /></Layout>
                        </ProtectedRoute>
                    } />
                    <Route path="/bible" element={
                        <ProtectedRoute>
                            <Layout><BiblePage /></Layout>
                        </ProtectedRoute>
                    } />
                    <Route path="/study" element={
                        <ProtectedRoute>
                            <Layout><BibleStudyPage /></Layout>
                        </ProtectedRoute>
                    } />
                    <Route path="/support" element={
                        <ProtectedRoute>
                            <Layout><EmotionalSupportPage /></Layout>
                        </ProtectedRoute>
                    } />
                    <Route path="/devotion" element={
                        <ProtectedRoute>
                            <Layout><DevotionPage /></Layout>
                        </ProtectedRoute>
                    } />
                    <Route path="/profile" element={
                        <ProtectedRoute>
                            <Layout><ProfilePage /></Layout>
                        </ProtectedRoute>
                    } />
                </Routes>
            </BrowserRouter>
        </AuthProvider>
    );
};

// Render with error handling
try {
    const rootElement = document.getElementById('root');
    if (!rootElement) {
        console.error('Root element not found!');
    } else {
        const root = ReactDOM.createRoot(rootElement);
        root.render(<App />);
    }
} catch (error) {
    console.error('Failed to render app:', error);
    document.body.innerHTML = '<div style="padding: 20px; color: red;">Failed to start application. Please check console for errors.</div>';
}