/**
 * 11 - Context API Example
 * 
 * דוגמה לשימוש ב-Context API
 * לניהול state גלובלי (Theme, Auth).
 */

import React, { createContext, useContext, useState, useEffect } from 'react';

// ============================================
// 1. Theme Context
// ============================================

// יצירת Context
const ThemeContext = createContext(null);

// Provider Component
function ThemeProvider({ children }) {
    const [theme, setTheme] = useState(() => {
        return localStorage.getItem('theme') || 'light';
    });

    useEffect(() => {
        localStorage.setItem('theme', theme);
        document.body.className = theme;
    }, [theme]);

    const toggleTheme = () => {
        setTheme(prev => prev === 'light' ? 'dark' : 'light');
    };

    const value = {
        theme,
        toggleTheme,
        isDark: theme === 'dark'
    };

    return (
        <ThemeContext.Provider value={value}>
            {children}
        </ThemeContext.Provider>
    );
}

// Custom Hook
function useTheme() {
    const context = useContext(ThemeContext);
    if (!context) {
        throw new Error('useTheme must be used within ThemeProvider');
    }
    return context;
}

// ============================================
// 2. Auth Context
// ============================================

const AuthContext = createContext(null);

function AuthProvider({ children }) {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        // בדיקת משתמש שמור
        const savedUser = localStorage.getItem('user');
        if (savedUser) {
            setUser(JSON.parse(savedUser));
        }
        setLoading(false);
    }, []);

    const login = (email, password) => {
        // סימולציית התחברות
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (email && password.length >= 4) {
                    const userData = {
                        id: 1,
                        name: email.split('@')[0],
                        email
                    };
                    setUser(userData);
                    localStorage.setItem('user', JSON.stringify(userData));
                    resolve(userData);
                } else {
                    reject(new Error('פרטים שגויים'));
                }
            }, 500);
        });
    };

    const logout = () => {
        setUser(null);
        localStorage.removeItem('user');
    };

    const value = {
        user,
        loading,
        isAuthenticated: !!user,
        login,
        logout
    };

    return (
        <AuthContext.Provider value={value}>
            {children}
        </AuthContext.Provider>
    );
}

function useAuth() {
    const context = useContext(AuthContext);
    if (!context) {
        throw new Error('useAuth must be used within AuthProvider');
    }
    return context;
}

// ============================================
// קומפוננטות שמשתמשות ב-Context
// ============================================

function Header() {
    const { theme, toggleTheme } = useTheme();
    const { user, logout, isAuthenticated } = useAuth();

    const headerStyle = {
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: '15px 20px',
        backgroundColor: theme === 'dark' ? '#333' : '#f5f5f5',
        color: theme === 'dark' ? '#fff' : '#333'
    };

    return (
        <header style={headerStyle}>
            <h1>🌐 האפליקציה שלי</h1>

            <div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
                <button onClick={toggleTheme}>
                    {theme === 'light' ? '🌙' : '☀️'}
                </button>

                {isAuthenticated ? (
                    <>
                        <span>👤 {user.name}</span>
                        <button onClick={logout}>התנתק</button>
                    </>
                ) : (
                    <span>אורח</span>
                )}
            </div>
        </header>
    );
}

function LoginForm() {
    const { login } = useAuth();
    const { isDark } = useTheme();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');
        setIsLoading(true);

        try {
            await login(email, password);
        } catch (err) {
            setError(err.message);
        } finally {
            setIsLoading(false);
        }
    };

    const formStyle = {
        maxWidth: '300px',
        margin: '20px auto',
        padding: '20px',
        backgroundColor: isDark ? '#444' : '#fff',
        color: isDark ? '#fff' : '#333',
        borderRadius: '8px',
        boxShadow: '0 2px 10px rgba(0,0,0,0.1)'
    };

    return (
        <form onSubmit={handleSubmit} style={formStyle}>
            <h2>🔐 התחברות</h2>

            {error && (
                <p style={{ color: 'red', marginBottom: '10px' }}>{error}</p>
            )}

            <div style={{ marginBottom: '15px' }}>
                <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="אימייל"
                    style={{ width: '100%', padding: '10px' }}
                />
            </div>

            <div style={{ marginBottom: '15px' }}>
                <input
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="סיסמה"
                    style={{ width: '100%', padding: '10px' }}
                />
            </div>

            <button
                type="submit"
                disabled={isLoading}
                style={{ width: '100%', padding: '10px' }}
            >
                {isLoading ? 'מתחבר...' : 'התחבר'}
            </button>
        </form>
    );
}

function Dashboard() {
    const { user } = useAuth();
    const { isDark } = useTheme();

    const style = {
        padding: '20px',
        backgroundColor: isDark ? '#2c3e50' : '#ecf0f1',
        color: isDark ? '#fff' : '#333',
        minHeight: '200px',
        borderRadius: '8px',
        margin: '20px'
    };

    return (
        <div style={style}>
            <h2>📊 Dashboard</h2>
            <p>ברוך הבא, {user.name}!</p>
            <p>אימייל: {user.email}</p>

            <ThemedCard title="סטטיסטיקות">
                <p>כניסות: 42</p>
                <p>פעולות: 128</p>
            </ThemedCard>
        </div>
    );
}

function ThemedCard({ title, children }) {
    const { isDark } = useTheme();

    const cardStyle = {
        padding: '15px',
        marginTop: '15px',
        backgroundColor: isDark ? '#34495e' : '#fff',
        borderRadius: '8px',
        boxShadow: '0 2px 5px rgba(0,0,0,0.1)'
    };

    return (
        <div style={cardStyle}>
            <h3>{title}</h3>
            {children}
        </div>
    );
}

function MainContent() {
    const { isAuthenticated, loading } = useAuth();
    const { isDark } = useTheme();

    if (loading) {
        return <p style={{ textAlign: 'center', padding: '20px' }}>טוען...</p>;
    }

    const contentStyle = {
        minHeight: '400px',
        backgroundColor: isDark ? '#1a1a1a' : '#fff',
        color: isDark ? '#fff' : '#333'
    };

    return (
        <main style={contentStyle}>
            {isAuthenticated ? <Dashboard /> : <LoginForm />}
        </main>
    );
}

// ============================================
// קומפוננטה ראשית
// ============================================

function App() {
    return (
        <ThemeProvider>
            <AuthProvider>
                <div className="app">
                    <Header />
                    <MainContent />
                </div>
            </AuthProvider>
        </ThemeProvider>
    );
}

export default App;
