/**
 * 07 - Lists - רינדור רשימות ב-React
 * 
 * שימוש ב-map() להצגת רשימות,
 * חשיבות ה-key, סינון ומיון.
 */

import React, { useState, useMemo } from 'react';

// ============================================
// רשימה פשוטה
// ============================================

function SimpleList() {
    const fruits = ['תפוח', 'בננה', 'תפוז', 'ענבים', 'אבטיח'];

    return (
        <div className="simple-list">
            <h3>רשימה פשוטה</h3>
            <ul>
                {fruits.map((fruit, index) => (
                    <li key={index}>{fruit}</li>
                ))}
            </ul>
        </div>
    );
}

// ============================================
// רשימת אובייקטים
// ============================================

function ObjectList() {
    const users = [
        { id: 1, name: 'דני', age: 25, city: 'תל אביב' },
        { id: 2, name: 'רונית', age: 30, city: 'ירושלים' },
        { id: 3, name: 'משה', age: 28, city: 'חיפה' },
        { id: 4, name: 'שרה', age: 22, city: 'באר שבע' }
    ];

    return (
        <div className="object-list">
            <h3>רשימת אובייקטים</h3>
            <div className="cards">
                {users.map(user => (
                    <div key={user.id} className="card" style={{
                        border: '1px solid #ddd',
                        borderRadius: '8px',
                        padding: '12px',
                        margin: '8px',
                        display: 'inline-block'
                    }}>
                        <h4>{user.name}</h4>
                        <p>גיל: {user.age}</p>
                        <p>עיר: {user.city}</p>
                    </div>
                ))}
            </div>
        </div>
    );
}

// ============================================
// סינון רשימה
// ============================================

function FilteredList() {
    const [filter, setFilter] = useState('');

    const products = [
        { id: 1, name: 'מקלדת', category: 'מחשבים', price: 150 },
        { id: 2, name: 'עכבר', category: 'מחשבים', price: 80 },
        { id: 3, name: 'מסך', category: 'מחשבים', price: 1200 },
        { id: 4, name: 'אוזניות', category: 'אודיו', price: 200 },
        { id: 5, name: 'רמקול', category: 'אודיו', price: 350 },
        { id: 6, name: 'מצלמה', category: 'צילום', price: 2500 }
    ];

    const filteredProducts = products.filter(product =>
        product.name.includes(filter) ||
        product.category.includes(filter)
    );

    return (
        <div className="filtered-list">
            <h3>סינון רשימה</h3>

            <input
                type="text"
                value={filter}
                onChange={(e) => setFilter(e.target.value)}
                placeholder="חפש מוצר או קטגוריה..."
                style={{ padding: '8px', marginBottom: '10px', width: '100%' }}
            />

            <p>נמצאו {filteredProducts.length} תוצאות</p>

            <ul>
                {filteredProducts.map(product => (
                    <li key={product.id}>
                        <strong>{product.name}</strong> - {product.category} - ₪{product.price}
                    </li>
                ))}
            </ul>
        </div>
    );
}

// ============================================
// מיון רשימה
// ============================================

function SortedList() {
    const [sortBy, setSortBy] = useState('name');
    const [sortOrder, setSortOrder] = useState('asc');

    const items = [
        { id: 1, name: 'בננה', price: 5, stock: 100 },
        { id: 2, name: 'תפוח', price: 8, stock: 50 },
        { id: 3, name: 'תפוז', price: 6, stock: 75 },
        { id: 4, name: 'אבטיח', price: 15, stock: 20 },
        { id: 5, name: 'ענבים', price: 12, stock: 60 }
    ];

    const sortedItems = useMemo(() => {
        return [...items].sort((a, b) => {
            let comparison = 0;

            if (sortBy === 'name') {
                comparison = a.name.localeCompare(b.name, 'he');
            } else if (sortBy === 'price') {
                comparison = a.price - b.price;
            } else if (sortBy === 'stock') {
                comparison = a.stock - b.stock;
            }

            return sortOrder === 'asc' ? comparison : -comparison;
        });
    }, [sortBy, sortOrder]);

    return (
        <div className="sorted-list">
            <h3>מיון רשימה</h3>

            <div style={{ marginBottom: '10px' }}>
                <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}>
                    <option value="name">שם</option>
                    <option value="price">מחיר</option>
                    <option value="stock">מלאי</option>
                </select>

                <button onClick={() => setSortOrder(o => o === 'asc' ? 'desc' : 'asc')}>
                    {sortOrder === 'asc' ? '⬆️ עולה' : '⬇️ יורד'}
                </button>
            </div>

            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                    <tr style={{ backgroundColor: '#f0f0f0' }}>
                        <th style={{ padding: '8px', textAlign: 'right' }}>שם</th>
                        <th style={{ padding: '8px', textAlign: 'right' }}>מחיר</th>
                        <th style={{ padding: '8px', textAlign: 'right' }}>מלאי</th>
                    </tr>
                </thead>
                <tbody>
                    {sortedItems.map(item => (
                        <tr key={item.id} style={{ borderBottom: '1px solid #ddd' }}>
                            <td style={{ padding: '8px' }}>{item.name}</td>
                            <td style={{ padding: '8px' }}>₪{item.price}</td>
                            <td style={{ padding: '8px' }}>{item.stock}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}

// ============================================
// הוספה ומחיקה מרשימה
// ============================================

function DynamicList() {
    const [items, setItems] = useState([
        { id: 1, text: 'לקנות חלב' },
        { id: 2, text: 'לשלם חשבונות' },
        { id: 3, text: 'להתקשר לאמא' }
    ]);
    const [newItem, setNewItem] = useState('');

    const addItem = () => {
        if (!newItem.trim()) return;

        setItems(prev => [
            ...prev,
            { id: Date.now(), text: newItem.trim() }
        ]);
        setNewItem('');
    };

    const removeItem = (id) => {
        setItems(prev => prev.filter(item => item.id !== id));
    };

    const moveUp = (index) => {
        if (index === 0) return;
        setItems(prev => {
            const newItems = [...prev];
            [newItems[index - 1], newItems[index]] = [newItems[index], newItems[index - 1]];
            return newItems;
        });
    };

    const moveDown = (index) => {
        if (index === items.length - 1) return;
        setItems(prev => {
            const newItems = [...prev];
            [newItems[index], newItems[index + 1]] = [newItems[index + 1], newItems[index]];
            return newItems;
        });
    };

    return (
        <div className="dynamic-list">
            <h3>הוספה ומחיקה</h3>

            <div style={{ marginBottom: '10px' }}>
                <input
                    value={newItem}
                    onChange={(e) => setNewItem(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && addItem()}
                    placeholder="הוסף פריט חדש..."
                    style={{ padding: '8px', marginLeft: '5px' }}
                />
                <button onClick={addItem}>➕ הוסף</button>
            </div>

            {items.length === 0 ? (
                <p>📭 הרשימה ריקה</p>
            ) : (
                <ul style={{ listStyle: 'none', padding: 0 }}>
                    {items.map((item, index) => (
                        <li key={item.id} style={{
                            display: 'flex',
                            alignItems: 'center',
                            padding: '8px',
                            backgroundColor: index % 2 === 0 ? '#f9f9f9' : 'white',
                            marginBottom: '2px'
                        }}>
                            <span style={{ flex: 1 }}>{item.text}</span>
                            <button onClick={() => moveUp(index)} disabled={index === 0}>⬆️</button>
                            <button onClick={() => moveDown(index)} disabled={index === items.length - 1}>⬇️</button>
                            <button onClick={() => removeItem(item.id)} style={{ color: 'red' }}>❌</button>
                        </li>
                    ))}
                </ul>
            )}

            <p>סה"כ: {items.length} פריטים</p>
        </div>
    );
}

// ============================================
// רשימות מקוננות
// ============================================

function NestedList() {
    const categories = [
        {
            id: 1,
            name: 'פירות',
            items: ['תפוח', 'בננה', 'תפוז', 'ענבים']
        },
        {
            id: 2,
            name: 'ירקות',
            items: ['מלפפון', 'עגבנייה', 'גזר', 'חסה']
        },
        {
            id: 3,
            name: 'מוצרי חלב',
            items: ['חלב', 'גבינה', 'יוגורט']
        }
    ];

    return (
        <div className="nested-list">
            <h3>רשימות מקוננות</h3>

            {categories.map(category => (
                <div key={category.id} style={{ marginBottom: '15px' }}>
                    <h4 style={{ color: '#3498db' }}>{category.name}</h4>
                    <ul>
                        {category.items.map((item, index) => (
                            <li key={index}>{item}</li>
                        ))}
                    </ul>
                </div>
            ))}
        </div>
    );
}

// ============================================
// רשימה עם קומפוננטת פריט
// ============================================

function ListWithComponent() {
    const [selectedId, setSelectedId] = useState(null);

    const people = [
        { id: 1, name: 'דני', role: 'מפתח', avatar: '👨‍💻' },
        { id: 2, name: 'רונית', role: 'מעצבת', avatar: '👩‍🎨' },
        { id: 3, name: 'משה', role: 'מנהל', avatar: '👨‍💼' }
    ];

    return (
        <div className="list-with-component">
            <h3>רשימה עם קומפוננטת פריט</h3>

            {people.map(person => (
                <PersonCard
                    key={person.id}
                    person={person}
                    isSelected={selectedId === person.id}
                    onSelect={() => setSelectedId(person.id)}
                />
            ))}
        </div>
    );
}

function PersonCard({ person, isSelected, onSelect }) {
    return (
        <div
            onClick={onSelect}
            style={{
                display: 'flex',
                alignItems: 'center',
                padding: '12px',
                margin: '8px 0',
                backgroundColor: isSelected ? '#e3f2fd' : 'white',
                border: `2px solid ${isSelected ? '#2196f3' : '#ddd'}`,
                borderRadius: '8px',
                cursor: 'pointer'
            }}
        >
            <span style={{ fontSize: '2rem', marginLeft: '12px' }}>{person.avatar}</span>
            <div>
                <strong>{person.name}</strong>
                <p style={{ margin: 0, color: '#666' }}>{person.role}</p>
            </div>
            {isSelected && <span style={{ marginRight: 'auto' }}>✓</span>}
        </div>
    );
}

// ============================================
// קומפוננטה ראשית
// ============================================

function App() {
    return (
        <div className="app" style={{ padding: '20px' }}>
            <h1>דוגמאות רשימות</h1>

            <SimpleList />
            <hr />

            <ObjectList />
            <hr />

            <FilteredList />
            <hr />

            <SortedList />
            <hr />

            <DynamicList />
            <hr />

            <NestedList />
            <hr />

            <ListWithComponent />
        </div>
    );
}

export default App;
