/**
 * 05 - Hooks - שימוש ב-useState, useEffect, useRef ועוד
 * 
 * Hooks הם פונקציות מיוחדות שמאפשרות שימוש
 * ב-state ו-lifecycle בתוך Function Components.
 */

import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';

// ============================================
// useEffect - Side Effects
// ============================================

function EffectExample() {
    const [count, setCount] = useState(0);
    const [name, setName] = useState('');

    // רץ בכל רינדור
    useEffect(() => {
        console.log('🔄 רינדור התבצע');
    });

    // רץ פעם אחת בטעינה
    useEffect(() => {
        console.log('🚀 קומפוננטה נטענה');
        document.title = 'דף React';

        return () => {
            console.log('👋 קומפוננטה נהרסה');
        };
    }, []);

    // רץ כשהתלות משתנה
    useEffect(() => {
        console.log(`📊 count השתנה ל: ${count}`);
        document.title = `ספירה: ${count}`;
    }, [count]);

    return (
        <div className="effect-example">
            <h3>useEffect</h3>
            <p>ספירה: {count}</p>
            <button onClick={() => setCount(c => c + 1)}>הוסף</button>

            <input
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="שם (לא משפיע על אפקט השני)"
            />
        </div>
    );
}

// ============================================
// useEffect - Fetch Data
// ============================================

function FetchExample() {
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/users')
            .then(res => {
                if (!res.ok) throw new Error('שגיאה בטעינה');
                return res.json();
            })
            .then(data => {
                setUsers(data.slice(0, 5)); // רק 5 ראשונים
                setLoading(false);
            })
            .catch(err => {
                setError(err.message);
                setLoading(false);
            });
    }, []);

    if (loading) return <p>⏳ טוען משתמשים...</p>;
    if (error) return <p>❌ שגיאה: {error}</p>;

    return (
        <div className="fetch-example">
            <h3>useEffect - Fetch Data</h3>
            <ul>
                {users.map(user => (
                    <li key={user.id}>
                        <strong>{user.name}</strong> - {user.email}
                    </li>
                ))}
            </ul>
        </div>
    );
}

// ============================================
// useEffect - Timer
// ============================================

function TimerExample() {
    const [seconds, setSeconds] = useState(0);
    const [isRunning, setIsRunning] = useState(false);

    useEffect(() => {
        let intervalId = null;

        if (isRunning) {
            intervalId = setInterval(() => {
                setSeconds(s => s + 1);
            }, 1000);
        }

        // Cleanup - עוצר את הטיימר
        return () => {
            if (intervalId) clearInterval(intervalId);
        };
    }, [isRunning]);

    const formatTime = (totalSeconds) => {
        const mins = Math.floor(totalSeconds / 60);
        const secs = totalSeconds % 60;
        return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    };

    return (
        <div className="timer-example">
            <h3>useEffect - Timer</h3>
            <p style={{ fontSize: '2rem' }}>{formatTime(seconds)}</p>
            <button onClick={() => setIsRunning(!isRunning)}>
                {isRunning ? '⏸️ עצור' : '▶️ התחל'}
            </button>
            <button onClick={() => { setSeconds(0); setIsRunning(false); }}>
                🔄 אפס
            </button>
        </div>
    );
}

// ============================================
// useRef - Reference ל-DOM
// ============================================

function RefDomExample() {
    const inputRef = useRef(null);
    const divRef = useRef(null);

    const focusInput = () => {
        inputRef.current.focus();
    };

    const scrollToDiv = () => {
        divRef.current.scrollIntoView({ behavior: 'smooth' });
    };

    return (
        <div className="ref-dom-example">
            <h3>useRef - DOM</h3>

            <input ref={inputRef} type="text" placeholder="התמקד בי..." />
            <button onClick={focusInput}>🎯 Focus</button>

            <div style={{ height: '100px' }} />

            <div ref={divRef} style={{ backgroundColor: '#3498db', padding: '20px', color: 'white' }}>
                גלול אליי!
            </div>
            <button onClick={scrollToDiv}>⬇️ גלול</button>
        </div>
    );
}

// ============================================
// useRef - שמירת ערך
// ============================================

function RefValueExample() {
    const [count, setCount] = useState(0);
    const renderCount = useRef(0);
    const prevCount = useRef(count);

    useEffect(() => {
        renderCount.current += 1;
    });

    useEffect(() => {
        prevCount.current = count;
    }, [count]);

    return (
        <div className="ref-value-example">
            <h3>useRef - שמירת ערך</h3>
            <p>ספירה נוכחית: {count}</p>
            <p>ספירה קודמת: {prevCount.current}</p>
            <p>מספר רינדורים: {renderCount.current}</p>
            <button onClick={() => setCount(c => c + 1)}>הוסף</button>
        </div>
    );
}

// ============================================
// useMemo - מניעת חישוב מיותר
// ============================================

function MemoExample() {
    const [count, setCount] = useState(0);
    const [text, setText] = useState('');

    // חישוב "כבד" - רץ רק כש-count משתנה
    const expensiveCalculation = useMemo(() => {
        console.log('🔢 מחשב...');
        let result = 0;
        for (let i = 0; i < count * 1000000; i++) {
            result += 1;
        }
        return result;
    }, [count]);

    return (
        <div className="memo-example">
            <h3>useMemo</h3>
            <p>ספירה: {count}</p>
            <p>תוצאת חישוב: {expensiveCalculation.toLocaleString()}</p>
            <button onClick={() => setCount(c => c + 1)}>הוסף</button>

            <input
                value={text}
                onChange={(e) => setText(e.target.value)}
                placeholder="הקלדה לא מפעילה חישוב מחדש"
            />
        </div>
    );
}

// ============================================
// useCallback - מניעת יצירת פונקציה מחדש
// ============================================

function CallbackExample() {
    const [count, setCount] = useState(0);

    // הפונקציה לא נוצרת מחדש בכל רינדור
    const increment = useCallback(() => {
        setCount(c => c + 1);
    }, []);

    const decrement = useCallback(() => {
        setCount(c => c - 1);
    }, []);

    return (
        <div className="callback-example">
            <h3>useCallback</h3>
            <p>ספירה: {count}</p>
            <ExpensiveButton onClick={increment} label="➕" />
            <ExpensiveButton onClick={decrement} label="➖" />
        </div>
    );
}

// קומפוננטה "כבדה" שלא צריכה להתרנדר מחדש
const ExpensiveButton = React.memo(({ onClick, label }) => {
    console.log(`🔘 Button "${label}" rendered`);
    return <button onClick={onClick}>{label}</button>;
});

// ============================================
// Custom Hook - useLocalStorage
// ============================================

function useLocalStorage(key, initialValue) {
    const [value, setValue] = useState(() => {
        try {
            const saved = localStorage.getItem(key);
            return saved ? JSON.parse(saved) : initialValue;
        } catch {
            return initialValue;
        }
    });

    useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
    }, [key, value]);

    return [value, setValue];
}

function LocalStorageExample() {
    const [name, setName] = useLocalStorage('user-name', '');
    const [theme, setTheme] = useLocalStorage('theme', 'light');

    return (
        <div className="localstorage-example">
            <h3>Custom Hook - useLocalStorage</h3>
            <p>הנתונים נשמרים גם אחרי רענון!</p>

            <input
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="השם שלך..."
            />
            <p>שלום, {name || 'אורח'}!</p>

            <button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
                ערכת נושא: {theme === 'light' ? '☀️' : '🌙'}
            </button>
        </div>
    );
}

// ============================================
// Custom Hook - useWindowSize
// ============================================

function useWindowSize() {
    const [size, setSize] = useState({
        width: window.innerWidth,
        height: window.innerHeight
    });

    useEffect(() => {
        const handleResize = () => {
            setSize({
                width: window.innerWidth,
                height: window.innerHeight
            });
        };

        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    return size;
}

function WindowSizeExample() {
    const { width, height } = useWindowSize();

    return (
        <div className="window-size-example">
            <h3>Custom Hook - useWindowSize</h3>
            <p>גודל חלון: {width} × {height}</p>
            <p>סוג מסך: {width < 768 ? '📱 מובייל' : '💻 דסקטופ'}</p>
        </div>
    );
}

// ============================================
// קומפוננטה ראשית
// ============================================

function App() {
    return (
        <div className="app" style={{ padding: '20px' }}>
            <h1>דוגמאות Hooks</h1>

            <EffectExample />
            <hr />

            <FetchExample />
            <hr />

            <TimerExample />
            <hr />

            <RefDomExample />
            <hr />

            <RefValueExample />
            <hr />

            <MemoExample />
            <hr />

            <CallbackExample />
            <hr />

            <LocalStorageExample />
            <hr />

            <WindowSizeExample />
        </div>
    );
}

export default App;
