/**
 * 09 - Lifecycle Example - useEffect דוגמאות
 * 
 * דוגמאות לשימוש ב-useEffect עם dependencies,
 * cleanup, ומניעת memory leaks.
 */

import React, { useState, useEffect, useRef } from 'react';

// ============================================
// 1. רץ פעם אחת (Mount)
// ============================================

function MountExample() {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        console.log('🚀 קומפוננטה נטענה!');

        // סימולציית fetch
        setTimeout(() => {
            setData({ message: 'נתונים נטענו!' });
            setLoading(false);
        }, 1000);

        // זה לא רץ פעמיים בגלל [] ריק
    }, []); // מערך ריק = פעם אחת בלבד

    if (loading) return <p>⏳ טוען...</p>;
    return <p>✅ {data.message}</p>;
}

// ============================================
// 2. רץ כשתלות משתנה
// ============================================

function DependencyExample() {
    const [userId, setUserId] = useState(1);
    const [user, setUser] = useState(null);

    useEffect(() => {
        console.log(`📊 טוען משתמש ${userId}`);

        // סימולציית fetch
        setUser(null);
        setTimeout(() => {
            setUser({ id: userId, name: `משתמש ${userId}` });
        }, 500);
    }, [userId]); // רץ כל פעם ש-userId משתנה

    return (
        <div>
            <select value={userId} onChange={(e) => setUserId(Number(e.target.value))}>
                {[1, 2, 3, 4, 5].map(id => (
                    <option key={id} value={id}>משתמש {id}</option>
                ))}
            </select>
            {user ? <p>שם: {user.name}</p> : <p>טוען...</p>}
        </div>
    );
}

// ============================================
// 3. Cleanup - טיימר
// ============================================

function TimerExample() {
    const [seconds, setSeconds] = useState(0);
    const [isRunning, setIsRunning] = useState(false);

    useEffect(() => {
        if (!isRunning) return;

        console.log('▶️ מתחיל טיימר');

        const intervalId = setInterval(() => {
            setSeconds(s => s + 1);
        }, 1000);

        // Cleanup - חשוב למנוע memory leaks!
        return () => {
            console.log('⏹️ עוצר טיימר');
            clearInterval(intervalId);
        };
    }, [isRunning]);

    return (
        <div>
            <p style={{ fontSize: '2rem' }}>⏱️ {seconds}s</p>
            <button onClick={() => setIsRunning(!isRunning)}>
                {isRunning ? '⏸️ עצור' : '▶️ התחל'}
            </button>
            <button onClick={() => setSeconds(0)}>🔄 אפס</button>
        </div>
    );
}

// ============================================
// 4. Cleanup - Event Listeners
// ============================================

function WindowSizeTracker() {
    const [size, setSize] = useState({
        width: window.innerWidth,
        height: window.innerHeight
    });

    useEffect(() => {
        function handleResize() {
            setSize({
                width: window.innerWidth,
                height: window.innerHeight
            });
        }

        // הוספת listener
        window.addEventListener('resize', handleResize);
        console.log('👂 Listener נוסף');

        // הסרת listener (חובה!)
        return () => {
            window.removeEventListener('resize', handleResize);
            console.log('🔇 Listener הוסר');
        };
    }, []);

    return (
        <p>📐 גודל חלון: {size.width} × {size.height}</p>
    );
}

// ============================================
// 5. מניעת Memory Leaks ב-Fetch
// ============================================

function SafeFetch({ url }) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        const controller = new AbortController();

        async function fetchData() {
            try {
                setLoading(true);
                setError(null);

                const response = await fetch(url, {
                    signal: controller.signal
                });

                const json = await response.json();
                setData(json);
            } catch (err) {
                if (err.name !== 'AbortError') {
                    setError(err.message);
                }
            } finally {
                setLoading(false);
            }
        }

        fetchData();

        // ביטול הבקשה אם הקומפוננטה נהרסת
        return () => {
            controller.abort();
        };
    }, [url]);

    if (loading) return <p>טוען...</p>;
    if (error) return <p>שגיאה: {error}</p>;
    return <pre>{JSON.stringify(data, null, 2)}</pre>;
}

// ============================================
// 6. שימוש ב-isMounted flag
// ============================================

function IsMountedExample() {
    const [data, setData] = useState(null);
    const isMountedRef = useRef(true);

    useEffect(() => {
        isMountedRef.current = true;

        async function loadData() {
            // סימולציית API איטי
            await new Promise(resolve => setTimeout(resolve, 2000));

            // בדיקה לפני עדכון state
            if (isMountedRef.current) {
                setData({ loaded: true });
            }
        }

        loadData();

        return () => {
            isMountedRef.current = false;
        };
    }, []);

    return <p>{data ? '✅ נטען' : '⏳ טוען...'}</p>;
}

// ============================================
// 7. Document Title
// ============================================

function DocumentTitleExample() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        const originalTitle = document.title;
        document.title = `(${count}) הודעות חדשות`;

        return () => {
            document.title = originalTitle;
        };
    }, [count]);

    return (
        <div>
            <p>הודעות: {count}</p>
            <button onClick={() => setCount(c => c + 1)}>➕ הוסף הודעה</button>
            <button onClick={() => setCount(0)}>🗑️ נקה</button>
        </div>
    );
}

// ============================================
// קומפוננטה ראשית
// ============================================

function App() {
    const [showTimer, setShowTimer] = useState(true);

    return (
        <div style={{ padding: '20px' }}>
            <h1>🔄 דוגמאות Lifecycle</h1>

            <section>
                <h2>1. Mount בלבד</h2>
                <MountExample />
            </section>

            <hr />

            <section>
                <h2>2. Dependencies</h2>
                <DependencyExample />
            </section>

            <hr />

            <section>
                <h2>3. Timer עם Cleanup</h2>
                <button onClick={() => setShowTimer(!showTimer)}>
                    {showTimer ? 'הסתר' : 'הצג'} טיימר
                </button>
                {showTimer && <TimerExample />}
            </section>

            <hr />

            <section>
                <h2>4. Window Size Tracker</h2>
                <WindowSizeTracker />
            </section>

            <hr />

            <section>
                <h2>5. Document Title</h2>
                <DocumentTitleExample />
            </section>
        </div>
    );
}

export default App;
