// 17_react_native_example.jsx
// דוגמאות קוד ל-React Native עם Expo

// ============================================
// 1. קומפוננטה בסיסית
// ============================================

import { View, Text, StyleSheet } from 'react-native';

function HelloWorld() {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>שלום עולם!</Text>
      <Text style={styles.subtitle}>זו האפליקציה הראשונה שלי</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 32,
    fontWeight: 'bold',
    color: '#333',
  },
  subtitle: {
    fontSize: 18,
    color: '#666',
    marginTop: 10,
  },
});


// ============================================
// 2. כפתורים ואינטראקציה
// ============================================

import { useState } from 'react';
import { View, Text, Pressable, Alert, StyleSheet } from 'react-native';

function ButtonExample() {
  const [count, setCount] = useState(0);

  const handlePress = () => {
    setCount(count + 1);
  };

  const handleLongPress = () => {
    Alert.alert('לחיצה ארוכה!', 'לחצת לחיצה ארוכה על הכפתור');
  };

  return (
    <View style={styles.container}>
      <Text style={styles.countText}>לחצת {count} פעמים</Text>
      
      <Pressable
        style={({ pressed }) => [
          styles.button,
          pressed && styles.buttonPressed,
        ]}
        onPress={handlePress}
        onLongPress={handleLongPress}
      >
        <Text style={styles.buttonText}>לחץ עליי</Text>
      </Pressable>
    </View>
  );
}


// ============================================
// 3. TextInput - שדות קלט
// ============================================

import { useState } from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';

function FormExample() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  return (
    <View style={styles.form}>
      <Text style={styles.label}>שם:</Text>
      <TextInput
        style={styles.input}
        value={name}
        onChangeText={setName}
        placeholder="הכנס את שמך"
      />

      <Text style={styles.label}>אימייל:</Text>
      <TextInput
        style={styles.input}
        value={email}
        onChangeText={setEmail}
        placeholder="example@email.com"
        keyboardType="email-address"
        autoCapitalize="none"
      />

      <Text style={styles.label}>סיסמה:</Text>
      <TextInput
        style={styles.input}
        value={password}
        onChangeText={setPassword}
        placeholder="********"
        secureTextEntry={true}
      />

      <Text style={styles.preview}>
        שלום {name || 'אורח'}!
      </Text>
    </View>
  );
}


// ============================================
// 4. FlatList - רשימה יעילה
// ============================================

import { FlatList, View, Text, Image, StyleSheet } from 'react-native';

const CONTACTS = [
  { id: '1', name: 'דני כהן', phone: '050-1234567', avatar: '👨' },
  { id: '2', name: 'שרה לוי', phone: '052-7654321', avatar: '👩' },
  { id: '3', name: 'יוסי אברהם', phone: '054-9876543', avatar: '👴' },
  { id: '4', name: 'מיכל דוד', phone: '053-1357924', avatar: '👧' },
];

function ContactList() {
  const renderContact = ({ item }) => (
    <View style={styles.contactItem}>
      <Text style={styles.avatar}>{item.avatar}</Text>
      <View style={styles.contactInfo}>
        <Text style={styles.contactName}>{item.name}</Text>
        <Text style={styles.contactPhone}>{item.phone}</Text>
      </View>
    </View>
  );

  return (
    <FlatList
      data={CONTACTS}
      renderItem={renderContact}
      keyExtractor={(item) => item.id}
      ItemSeparatorComponent={() => <View style={styles.separator} />}
      ListHeaderComponent={() => (
        <Text style={styles.header}>אנשי קשר</Text>
      )}
    />
  );
}


// ============================================
// 5. ScrollView עם תמונות
// ============================================

import { ScrollView, View, Text, Image, StyleSheet, Dimensions } from 'react-native';

const { width } = Dimensions.get('window');

function ImageGallery() {
  const images = [
    'https://picsum.photos/400/300?random=1',
    'https://picsum.photos/400/300?random=2',
    'https://picsum.photos/400/300?random=3',
  ];

  return (
    <ScrollView>
      <Text style={styles.galleryTitle}>גלריית תמונות</Text>
      {images.map((uri, index) => (
        <View key={index} style={styles.imageContainer}>
          <Image
            source={{ uri }}
            style={styles.image}
            resizeMode="cover"
          />
          <Text style={styles.imageCaption}>תמונה {index + 1}</Text>
        </View>
      ))}
    </ScrollView>
  );
}


// ============================================
// 6. Expo Router - ניווט
// ============================================

// app/_layout.tsx
import { Stack } from 'expo-router';

export default function RootLayout() {
  return (
    <Stack
      screenOptions={{
        headerStyle: { backgroundColor: '#6200ee' },
        headerTintColor: '#fff',
        headerTitleStyle: { fontWeight: 'bold' },
      }}
    >
      <Stack.Screen name="index" options={{ title: 'בית' }} />
      <Stack.Screen name="profile" options={{ title: 'פרופיל' }} />
      <Stack.Screen name="settings" options={{ title: 'הגדרות' }} />
    </Stack>
  );
}

// app/index.tsx
import { Link } from 'expo-router';
import { View, Text, Pressable, StyleSheet } from 'react-native';

export default function HomeScreen() {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>דף הבית</Text>
      
      <Link href="/profile" asChild>
        <Pressable style={styles.link}>
          <Text style={styles.linkText}>עבור לפרופיל</Text>
        </Pressable>
      </Link>
      
      <Link href="/settings" asChild>
        <Pressable style={styles.link}>
          <Text style={styles.linkText}>עבור להגדרות</Text>
        </Pressable>
      </Link>
    </View>
  );
}


// ============================================
// 7. Tab Navigation
// ============================================

// app/(tabs)/_layout.tsx
import { Tabs } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';

export default function TabLayout() {
  return (
    <Tabs
      screenOptions={{
        tabBarActiveTintColor: '#6200ee',
        tabBarInactiveTintColor: '#666',
      }}
    >
      <Tabs.Screen
        name="home"
        options={{
          title: 'בית',
          tabBarIcon: ({ color, size }) => (
            <Ionicons name="home" size={size} color={color} />
          ),
        }}
      />
      <Tabs.Screen
        name="search"
        options={{
          title: 'חיפוש',
          tabBarIcon: ({ color, size }) => (
            <Ionicons name="search" size={size} color={color} />
          ),
        }}
      />
      <Tabs.Screen
        name="profile"
        options={{
          title: 'פרופיל',
          tabBarIcon: ({ color, size }) => (
            <Ionicons name="person" size={size} color={color} />
          ),
        }}
      />
    </Tabs>
  );
}


// ============================================
// 8. AsyncStorage - אחסון מקומי
// ============================================

import { useState, useEffect } from 'react';
import { View, Text, TextInput, Pressable, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

function StorageExample() {
  const [name, setName] = useState('');
  const [savedName, setSavedName] = useState('');

  // טעינה בהתחלה
  useEffect(() => {
    loadName();
  }, []);

  const loadName = async () => {
    try {
      const value = await AsyncStorage.getItem('userName');
      if (value !== null) {
        setSavedName(value);
      }
    } catch (e) {
      console.error('Error loading name:', e);
    }
  };

  const saveName = async () => {
    try {
      await AsyncStorage.setItem('userName', name);
      setSavedName(name);
      setName('');
    } catch (e) {
      console.error('Error saving name:', e);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>שם שמור: {savedName || 'אין'}</Text>
      
      <TextInput
        style={styles.input}
        value={name}
        onChangeText={setName}
        placeholder="הכנס שם חדש"
      />
      
      <Pressable style={styles.button} onPress={saveName}>
        <Text style={styles.buttonText}>שמור</Text>
      </Pressable>
    </View>
  );
}


// ============================================
// 9. Fetch API - קריאות לשרת
// ============================================

import { useState, useEffect } from 'react';
import { View, Text, FlatList, ActivityIndicator, StyleSheet } from 'react-native';

function FetchExample() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      const data = await response.json();
      setUsers(data);
    } catch (err) {
      setError('שגיאה בטעינת הנתונים');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <View style={styles.center}>
        <ActivityIndicator size="large" color="#6200ee" />
        <Text>טוען...</Text>
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.center}>
        <Text style={styles.error}>{error}</Text>
      </View>
    );
  }

  return (
    <FlatList
      data={users}
      keyExtractor={(item) => item.id.toString()}
      renderItem={({ item }) => (
        <View style={styles.userItem}>
          <Text style={styles.userName}>{item.name}</Text>
          <Text style={styles.userEmail}>{item.email}</Text>
        </View>
      )}
    />
  );
}


// ============================================
// 10. אפליקציית Todo מלאה
// ============================================

import { useState, useEffect } from 'react';
import {
  View,
  Text,
  TextInput,
  FlatList,
  Pressable,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

function TodoApp() {
  const [todos, setTodos] = useState([]);
  const [inputText, setInputText] = useState('');

  // טעינה מ-AsyncStorage
  useEffect(() => {
    loadTodos();
  }, []);

  // שמירה ל-AsyncStorage
  useEffect(() => {
    saveTodos();
  }, [todos]);

  const loadTodos = async () => {
    try {
      const json = await AsyncStorage.getItem('todos');
      if (json) {
        setTodos(JSON.parse(json));
      }
    } catch (e) {
      console.error(e);
    }
  };

  const saveTodos = async () => {
    try {
      await AsyncStorage.setItem('todos', JSON.stringify(todos));
    } catch (e) {
      console.error(e);
    }
  };

  const addTodo = () => {
    if (inputText.trim()) {
      setTodos([
        ...todos,
        {
          id: Date.now().toString(),
          text: inputText.trim(),
          completed: false,
        },
      ]);
      setInputText('');
    }
  };

  const toggleTodo = (id) => {
    setTodos(
      todos.map((todo) =>
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  };

  const deleteTodo = (id) => {
    setTodos(todos.filter((todo) => todo.id !== id));
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <Text style={styles.title}>📝 המשימות שלי</Text>

      <View style={styles.inputRow}>
        <TextInput
          style={styles.input}
          value={inputText}
          onChangeText={setInputText}
          placeholder="הוסף משימה..."
          onSubmitEditing={addTodo}
        />
        <Pressable style={styles.addButton} onPress={addTodo}>
          <Text style={styles.addButtonText}>+</Text>
        </Pressable>
      </View>

      <FlatList
        data={todos}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <View style={styles.todoItem}>
            <Pressable
              style={styles.checkbox}
              onPress={() => toggleTodo(item.id)}
            >
              <Text>{item.completed ? '✅' : '⬜'}</Text>
            </Pressable>
            <Text
              style={[
                styles.todoText,
                item.completed && styles.completedText,
              ]}
            >
              {item.text}
            </Text>
            <Pressable onPress={() => deleteTodo(item.id)}>
              <Text style={styles.deleteBtn}>🗑️</Text>
            </Pressable>
          </View>
        )}
        ListEmptyComponent={
          <Text style={styles.emptyText}>אין משימות. הוסף אחת!</Text>
        }
      />

      <Text style={styles.stats}>
        {todos.filter((t) => !t.completed).length} משימות נותרו
      </Text>
    </KeyboardAvoidingView>
  );
}


// ============================================
// סגנונות משותפים
// ============================================

const commonStyles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 20,
  },
  input: {
    backgroundColor: 'white',
    padding: 15,
    borderRadius: 10,
    fontSize: 16,
    borderWidth: 1,
    borderColor: '#ddd',
  },
  button: {
    backgroundColor: '#6200ee',
    padding: 15,
    borderRadius: 10,
    alignItems: 'center',
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export {
  HelloWorld,
  ButtonExample,
  FormExample,
  ContactList,
  ImageGallery,
  StorageExample,
  FetchExample,
  TodoApp,
};
