/**
 * 06 - Conditional Rendering - רינדור מותנה
 * 
 * ב-React, אנחנו מציגים תוכן שונה
 * בהתאם לתנאים באמצעות JavaScript רגיל.
 */

import React, { useState } from 'react';

// ============================================
// Ternary Operator (? :)
// ============================================

function TernaryExample() {
    const [isLoggedIn, setIsLoggedIn] = useState(false);

    return (
        <div className="ternary-example">
            <h3>Ternary Operator</h3>

            {isLoggedIn ? (
                <div>
                    <p>👋 שלום, משתמש!</p>
                    <button onClick={() => setIsLoggedIn(false)}>התנתק</button>
                </div>
            ) : (
                <div>
                    <p>🔒 אינך מחובר</p>
                    <button onClick={() => setIsLoggedIn(true)}>התחבר</button>
                </div>
            )}
        </div>
    );
}

// ============================================
// Logical AND (&&)
// ============================================

function AndExample() {
    const [showMessage, setShowMessage] = useState(false);
    const [notifications, setNotifications] = useState(3);

    return (
        <div className="and-example">
            <h3>Logical AND (&&)</h3>

            <button onClick={() => setShowMessage(!showMessage)}>
                {showMessage ? 'הסתר הודעה' : 'הצג הודעה'}
            </button>

            {showMessage && (
                <p className="message" style={{ backgroundColor: '#e8f5e9', padding: '10px' }}>
                    ✅ זו הודעה שמוצגת רק כש-showMessage הוא true!
                </p>
            )}

            <hr />

            <button onClick={() => setNotifications(n => n > 0 ? n - 1 : 0)}>
                מחק התראה
            </button>

            {/* זהירות עם 0! */}
            {notifications > 0 && (
                <span className="badge" style={{
                    backgroundColor: 'red',
                    color: 'white',
                    borderRadius: '50%',
                    padding: '5px 10px',
                    marginRight: '10px'
                }}>
                    {notifications}
                </span>
            )}

            <p>התראות: {notifications}</p>
        </div>
    );
}

// ============================================
// if/else רגיל
// ============================================

function IfElseExample() {
    const [status, setStatus] = useState('idle');

    let content;
    let statusColor;

    if (status === 'idle') {
        content = <p>⚪ ממתין לפעולה</p>;
        statusColor = '#95a5a6';
    } else if (status === 'loading') {
        content = <p>⏳ טוען...</p>;
        statusColor = '#f39c12';
    } else if (status === 'success') {
        content = <p>✅ הפעולה הצליחה!</p>;
        statusColor = '#27ae60';
    } else if (status === 'error') {
        content = <p>❌ שגיאה בפעולה!</p>;
        statusColor = '#e74c3c';
    }

    return (
        <div className="if-else-example">
            <h3>if/else רגיל</h3>

            <div style={{ backgroundColor: statusColor, padding: '10px', color: 'white' }}>
                {content}
            </div>

            <div style={{ marginTop: '10px' }}>
                <button onClick={() => setStatus('idle')}>Idle</button>
                <button onClick={() => setStatus('loading')}>Loading</button>
                <button onClick={() => setStatus('success')}>Success</button>
                <button onClick={() => setStatus('error')}>Error</button>
            </div>
        </div>
    );
}

// ============================================
// switch/case
// ============================================

function SwitchExample() {
    const [step, setStep] = useState(1);

    const renderStep = () => {
        switch (step) {
            case 1:
                return (
                    <div>
                        <h4>שלב 1: פרטים אישיים</h4>
                        <input placeholder="שם" />
                        <input placeholder="אימייל" />
                    </div>
                );
            case 2:
                return (
                    <div>
                        <h4>שלב 2: כתובת</h4>
                        <input placeholder="עיר" />
                        <input placeholder="רחוב" />
                    </div>
                );
            case 3:
                return (
                    <div>
                        <h4>שלב 3: אישור</h4>
                        <p>✅ כל הפרטים נשמרו!</p>
                    </div>
                );
            default:
                return <p>שלב לא ידוע</p>;
        }
    };

    return (
        <div className="switch-example">
            <h3>switch/case</h3>

            <div className="steps-indicator">
                {[1, 2, 3].map(s => (
                    <span key={s} style={{
                        padding: '5px 15px',
                        backgroundColor: step === s ? '#3498db' : '#bdc3c7',
                        color: step === s ? 'white' : 'black',
                        borderRadius: '50%',
                        margin: '0 5px'
                    }}>
                        {s}
                    </span>
                ))}
            </div>

            <div style={{ padding: '20px', border: '1px solid #ddd', margin: '10px 0' }}>
                {renderStep()}
            </div>

            <div>
                <button
                    onClick={() => setStep(s => Math.max(1, s - 1))}
                    disabled={step === 1}
                >
                    ← הקודם
                </button>
                <button
                    onClick={() => setStep(s => Math.min(3, s + 1))}
                    disabled={step === 3}
                >
                    הבא →
                </button>
            </div>
        </div>
    );
}

// ============================================
// אובייקט מיפוי
// ============================================

function ObjectMapExample() {
    const [icon, setIcon] = useState('home');

    const icons = {
        home: '🏠',
        settings: '⚙️',
        user: '👤',
        mail: '📧',
        search: '🔍'
    };

    const descriptions = {
        home: 'דף הבית',
        settings: 'הגדרות',
        user: 'פרופיל משתמש',
        mail: 'דואר',
        search: 'חיפוש'
    };

    return (
        <div className="object-map-example">
            <h3>אובייקט מיפוי</h3>

            <p style={{ fontSize: '3rem' }}>{icons[icon]}</p>
            <p>{descriptions[icon]}</p>

            <div>
                {Object.keys(icons).map(key => (
                    <button
                        key={key}
                        onClick={() => setIcon(key)}
                        style={{
                            backgroundColor: icon === key ? '#3498db' : '#ecf0f1',
                            border: 'none',
                            padding: '10px',
                            margin: '5px',
                            cursor: 'pointer'
                        }}
                    >
                        {icons[key]}
                    </button>
                ))}
            </div>
        </div>
    );
}

// ============================================
// החזרת null (הסתרה מלאה)
// ============================================

function NullExample() {
    const [isVisible, setIsVisible] = useState(true);

    return (
        <div className="null-example">
            <h3>החזרת null</h3>
            <button onClick={() => setIsVisible(!isVisible)}>
                {isVisible ? 'הסתר' : 'הצג'}
            </button>

            <HideableComponent visible={isVisible} />
        </div>
    );
}

function HideableComponent({ visible }) {
    if (!visible) {
        return null; // לא מרנדר כלום - נעלם מה-DOM לגמרי
    }

    return (
        <div style={{
            backgroundColor: '#3498db',
            color: 'white',
            padding: '20px',
            margin: '10px 0'
        }}>
            🎉 אני נראה!
        </div>
    );
}

// ============================================
// Classes דינמיים
// ============================================

function DynamicClassesExample() {
    const [isActive, setIsActive] = useState(false);
    const [isError, setIsError] = useState(false);
    const [size, setSize] = useState('medium');

    // שיטה 1: Template literal
    const className = `box ${isActive ? 'active' : ''} ${isError ? 'error' : ''} ${size}`;

    // שיטה 2: Array + filter + join (נקייה יותר)
    const classNames = [
        'box',
        isActive && 'active',
        isError && 'error',
        size
    ].filter(Boolean).join(' ');

    const boxStyle = {
        padding: '20px',
        border: `2px solid ${isError ? 'red' : isActive ? 'green' : 'gray'}`,
        backgroundColor: isActive ? '#e8f5e9' : isError ? '#ffebee' : 'white',
        fontSize: size === 'small' ? '12px' : size === 'large' ? '24px' : '16px'
    };

    return (
        <div className="dynamic-classes-example">
            <h3>Classes דינמיים</h3>

            <div className={classNames} style={boxStyle}>
                classes: {classNames}
            </div>

            <div style={{ marginTop: '10px' }}>
                <label>
                    <input
                        type="checkbox"
                        checked={isActive}
                        onChange={(e) => setIsActive(e.target.checked)}
                    />
                    Active
                </label>

                <label>
                    <input
                        type="checkbox"
                        checked={isError}
                        onChange={(e) => setIsError(e.target.checked)}
                    />
                    Error
                </label>

                <select value={size} onChange={(e) => setSize(e.target.value)}>
                    <option value="small">קטן</option>
                    <option value="medium">בינוני</option>
                    <option value="large">גדול</option>
                </select>
            </div>
        </div>
    );
}

// ============================================
// קומפוננטה ראשית
// ============================================

function App() {
    return (
        <div className="app" style={{ padding: '20px' }}>
            <h1>דוגמאות רינדור מותנה</h1>

            <TernaryExample />
            <hr />

            <AndExample />
            <hr />

            <IfElseExample />
            <hr />

            <SwitchExample />
            <hr />

            <ObjectMapExample />
            <hr />

            <NullExample />
            <hr />

            <DynamicClassesExample />
        </div>
    );
}

export default App;
