/**
 * 10 - Lifting State Up Example
 * 
 * דוגמה להעלאת State להורה משותף
 * לצורך שיתוף נתונים בין קומפוננטות.
 */

import React, { useState } from 'react';

// ============================================
// דוגמה 1: ממיר טמפרטורות
// ============================================

function TemperatureConverter() {
    // State מורם להורה המשותף
    const [temperature, setTemperature] = useState('');
    const [scale, setScale] = useState('celsius');

    const handleCelsiusChange = (temp) => {
        setTemperature(temp);
        setScale('celsius');
    };

    const handleFahrenheitChange = (temp) => {
        setTemperature(temp);
        setScale('fahrenheit');
    };

    // חישובי המרה
    const celsius = scale === 'fahrenheit'
        ? ((temperature - 32) * 5 / 9).toFixed(2)
        : temperature;

    const fahrenheit = scale === 'celsius'
        ? ((temperature * 9 / 5) + 32).toFixed(2)
        : temperature;

    return (
        <div className="converter">
            <h2>🌡️ ממיר טמפרטורות</h2>

            <TemperatureInput
                label="צלזיוס"
                value={celsius}
                onChange={handleCelsiusChange}
            />

            <TemperatureInput
                label="פרנהייט"
                value={fahrenheit}
                onChange={handleFahrenheitChange}
            />

            <WaterStatus celsius={parseFloat(celsius)} />
        </div>
    );
}

function TemperatureInput({ label, value, onChange }) {
    return (
        <div style={{ margin: '10px 0' }}>
            <label>
                {label}:
                <input
                    type="number"
                    value={value}
                    onChange={(e) => onChange(e.target.value)}
                    style={{ marginRight: '10px', padding: '5px' }}
                />
            </label>
        </div>
    );
}

function WaterStatus({ celsius }) {
    if (isNaN(celsius)) return null;

    let status;
    if (celsius <= 0) {
        status = '🧊 המים קפואים';
    } else if (celsius >= 100) {
        status = '💨 המים רותחים';
    } else {
        status = '💧 המים נוזליים';
    }

    return <p style={{ fontSize: '1.5rem' }}>{status}</p>;
}

// ============================================
// דוגמה 2: מוצרים וסל קניות
// ============================================

function ShoppingApp() {
    // State מורם
    const [cart, setCart] = useState([]);

    const products = [
        { id: 1, name: 'חולצה', price: 99 },
        { id: 2, name: 'מכנסיים', price: 149 },
        { id: 3, name: 'נעליים', price: 299 },
        { id: 4, name: 'כובע', price: 49 },
    ];

    const addToCart = (product) => {
        setCart(prev => [...prev, { ...product, cartId: Date.now() }]);
    };

    const removeFromCart = (cartId) => {
        setCart(prev => prev.filter(item => item.cartId !== cartId));
    };

    const clearCart = () => setCart([]);

    return (
        <div className="shopping-app">
            <h2>🛒 חנות</h2>

            <div style={{ display: 'flex', gap: '20px' }}>
                <ProductList products={products} onAddToCart={addToCart} />
                <Cart
                    items={cart}
                    onRemove={removeFromCart}
                    onClear={clearCart}
                />
            </div>
        </div>
    );
}

function ProductList({ products, onAddToCart }) {
    return (
        <div style={{ flex: 1 }}>
            <h3>מוצרים</h3>
            <ul style={{ listStyle: 'none', padding: 0 }}>
                {products.map(product => (
                    <li key={product.id} style={{
                        padding: '10px',
                        marginBottom: '5px',
                        backgroundColor: '#f5f5f5',
                        display: 'flex',
                        justifyContent: 'space-between'
                    }}>
                        <span>{product.name} - ₪{product.price}</span>
                        <button onClick={() => onAddToCart(product)}>
                            ➕ הוסף לסל
                        </button>
                    </li>
                ))}
            </ul>
        </div>
    );
}

function Cart({ items, onRemove, onClear }) {
    const total = items.reduce((sum, item) => sum + item.price, 0);

    return (
        <div style={{ flex: 1 }}>
            <h3>סל קניות ({items.length})</h3>

            {items.length === 0 ? (
                <p>הסל ריק</p>
            ) : (
                <>
                    <ul style={{ listStyle: 'none', padding: 0 }}>
                        {items.map(item => (
                            <li key={item.cartId} style={{
                                padding: '10px',
                                marginBottom: '5px',
                                backgroundColor: '#e3f2fd',
                                display: 'flex',
                                justifyContent: 'space-between'
                            }}>
                                <span>{item.name} - ₪{item.price}</span>
                                <button onClick={() => onRemove(item.cartId)}>
                                    ❌
                                </button>
                            </li>
                        ))}
                    </ul>
                    <p><strong>סה"כ: ₪{total}</strong></p>
                    <button onClick={onClear}>🗑️ נקה סל</button>
                </>
            )}
        </div>
    );
}

// ============================================
// דוגמה 3: Tabs עם תוכן משותף
// ============================================

function TabsExample() {
    // State מורם
    const [activeTab, setActiveTab] = useState('profile');
    const [userData, setUserData] = useState({
        name: 'דני',
        email: 'dani@example.com',
        notifications: true
    });

    const updateUserData = (field, value) => {
        setUserData(prev => ({ ...prev, [field]: value }));
    };

    return (
        <div>
            <h2>👤 הגדרות משתמש</h2>

            <TabButtons
                activeTab={activeTab}
                onTabChange={setActiveTab}
            />

            <TabContent
                activeTab={activeTab}
                userData={userData}
                onUpdate={updateUserData}
            />
        </div>
    );
}

function TabButtons({ activeTab, onTabChange }) {
    const tabs = [
        { id: 'profile', label: '👤 פרופיל' },
        { id: 'settings', label: '⚙️ הגדרות' },
        { id: 'summary', label: '📋 סיכום' }
    ];

    return (
        <div style={{ display: 'flex', gap: '5px', marginBottom: '20px' }}>
            {tabs.map(tab => (
                <button
                    key={tab.id}
                    onClick={() => onTabChange(tab.id)}
                    style={{
                        padding: '10px 20px',
                        backgroundColor: activeTab === tab.id ? '#3498db' : '#ecf0f1',
                        color: activeTab === tab.id ? 'white' : 'black',
                        border: 'none',
                        cursor: 'pointer'
                    }}
                >
                    {tab.label}
                </button>
            ))}
        </div>
    );
}

function TabContent({ activeTab, userData, onUpdate }) {
    switch (activeTab) {
        case 'profile':
            return (
                <div>
                    <h3>פרופיל</h3>
                    <label>
                        שם:
                        <input
                            value={userData.name}
                            onChange={(e) => onUpdate('name', e.target.value)}
                        />
                    </label>
                    <br /><br />
                    <label>
                        אימייל:
                        <input
                            value={userData.email}
                            onChange={(e) => onUpdate('email', e.target.value)}
                        />
                    </label>
                </div>
            );

        case 'settings':
            return (
                <div>
                    <h3>הגדרות</h3>
                    <label>
                        <input
                            type="checkbox"
                            checked={userData.notifications}
                            onChange={(e) => onUpdate('notifications', e.target.checked)}
                        />
                        קבל התראות
                    </label>
                </div>
            );

        case 'summary':
            return (
                <div>
                    <h3>סיכום</h3>
                    <p>שם: {userData.name}</p>
                    <p>אימייל: {userData.email}</p>
                    <p>התראות: {userData.notifications ? '✅ מופעל' : '❌ כבוי'}</p>
                </div>
            );

        default:
            return null;
    }
}

// ============================================
// קומפוננטה ראשית
// ============================================

function App() {
    return (
        <div style={{ padding: '20px' }}>
            <h1>🔝 Lifting State Up</h1>

            <section style={{ marginBottom: '40px' }}>
                <TemperatureConverter />
            </section>

            <hr />

            <section style={{ marginBottom: '40px' }}>
                <ShoppingApp />
            </section>

            <hr />

            <section>
                <TabsExample />
            </section>
        </div>
    );
}

export default App;
