// ===============================
// 1. Core Components
// ===============================

// View - The fundamental container component (like div)
import { View } from 'react-native';
const BasicContainer = () => (
  <View style={{ flex: 1, padding: 20 }}>
    {/* Child components go here */}
  </View>
);

// Text - For displaying text (all text must be inside Text components)
import { Text } from 'react-native';
const TextExample = () => (
  <Text style={{ fontSize: 16, color: 'black' }}>
    Hello React Native
  </Text>
);

// Image - For displaying images
import { Image } from 'react-native';
const ImageExample = () => (
  <Image
    source={{ uri: '<https://example.com/image.jpg>' }}
    // Or local image: source={require('./assets/image.jpg')}
    style={{ width: 200, height: 200 }}
  />
);

// TouchableOpacity - For handling touch events
import { TouchableOpacity } from 'react-native';
const ButtonExample = () => (
  <TouchableOpacity 
    onPress={() => console.log('Pressed!')}
    style={{ padding: 10, backgroundColor: 'blue' }}
  >
    <Text style={{ color: 'white' }}>Press Me</Text>
  </TouchableOpacity>
);

// ScrollView - For scrollable content
import { ScrollView } from 'react-native';
const ScrollViewExample = () => (
  <ScrollView>
    {/* Scrollable content */}
  </ScrollView>
);

// FlatList - For efficient list rendering
import { FlatList } from 'react-native';
const ListExample = () => {
  const data = [
    { id: '1', title: 'Item 1' },
    { id: '2', title: 'Item 2' },
  ];

  return (
    <FlatList
      data={data}
      renderItem={({ item }) => (
        <Text>{item.title}</Text>
      )}
      keyExtractor={item => item.id}
    />
  );
};

// ===============================
// 2. Styling
// ===============================

// StyleSheet for better performance
import { StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: 'white',
  },
  text: {
    fontSize: 16,
    color: 'black',
  },
  button: {
    padding: 10,
    borderRadius: 5,
    backgroundColor: 'blue',
  },
});

// Flexbox layout example
const FlexboxExample = () => (
  <View style={{
    flex: 1,
    flexDirection: 'column', // or 'row'
    justifyContent: 'center', // main axis
    alignItems: 'center', // cross axis
  }}>
    <View style={{ width: 50, height: 50, backgroundColor: 'red' }} />
    <View style={{ width: 50, height: 50, backgroundColor: 'blue' }} />
  </View>
);

// ===============================
// 3. Hooks and State Management
// ===============================

import { useState, useEffect } from 'react';

const StateExample = () => {
  const [count, setCount] = useState(0);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // Component lifecycle logic
    console.log('Component mounted');
    return () => console.log('Component will unmount');
  }, []);

  return (
    <View>
      <Text>Count: {count}</Text>
      <TouchableOpacity onPress={() => setCount(count + 1)}>
        <Text>Increment</Text>
      </TouchableOpacity>
    </View>
  );
};

// ===============================
// 4. Navigation
// ===============================

// Using React Navigation
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

const NavigationExample = () => (
  <NavigationContainer>
    <Stack.Navigator>
      <Stack.Screen 
        name="Home" 
        component={HomeScreen} 
        options={{ title: 'Home' }}
      />
      <Stack.Screen 
        name="Details" 
        component={DetailsScreen} 
      />
    </Stack.Navigator>
  </NavigationContainer>
);

// Screen component with navigation
const HomeScreen = ({ navigation }) => (
  <View>
    <TouchableOpacity
      onPress={() => navigation.navigate('Details', { id: 123 })}
    >
      <Text>Go to Details</Text>
    </TouchableOpacity>
  </View>
);

// ===============================
// 5. Handling User Input
// ===============================

import { TextInput } from 'react-native';

const InputExample = () => {
  const [text, setText] = useState('');

  return (
    <TextInput
      value={text}
      onChangeText={setText}
      placeholder="Enter text"
      style={{
        height: 40,
        borderColor: 'gray',
        borderWidth: 1,
        padding: 10,
      }}
    />
  );
};

// ===============================
// 6. Platform Specific Code
// ===============================

import { Platform } from 'react-native';

const PlatformSpecificStyle = StyleSheet.create({
  header: {
    paddingTop: Platform.OS === 'ios' ? 40 : 20,
    ...Platform.select({
      ios: {
        shadowColor: 'black',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.2,
      },
      android: {
        elevation: 4,
      },
    }),
  },
});

// ===============================
// 7. Basic App Structure
// ===============================

import React from 'react';
import { SafeAreaView, StatusBar } from 'react-native';

const App = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView style={{ flex: 1 }}>
        <NavigationContainer>
          {/* App content */}
        </NavigationContainer>
      </SafeAreaView>
    </>
  );
};

// ===============================
// 8. Data Fetching
// ===============================

const DataFetchingExample = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const response = await fetch('<https://api.example.com/data>');
      const json = await response.json();
      setData(json);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <ActivityIndicator size="large" />;
  }

  return (
    <View>
      {/* Render data */}
    </View>
  );
};

// ===============================
// 9. Responsive Design
// ===============================

import { Dimensions } from 'react-native';

const window = Dimensions.get('window');
const isSmallDevice = window.width < 375;

const responsiveStyles = StyleSheet.create({
  container: {
    padding: isSmallDevice ? 10 : 20,
    fontSize: isSmallDevice ? 14 : 16,
  },
});

// ===============================
// 10. Basic Form Handler
// ===============================

const FormExample = () => {
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
  });

  const handleSubmit = () => {
    // Validate and submit form
    console.log(formData);
  };

  return (
    <View style={{ padding: 20 }}>
      <TextInput
        value={formData.username}
        onChangeText={(text) => 
          setFormData({ ...formData, username: text })
        }
        placeholder="Username"
      />
      <TextInput
        value={formData.email}
        onChangeText={(text) => 
          setFormData({ ...formData, email: text })
        }
        placeholder="Email"
        keyboardType="email-address"
      />
      <TextInput
        value={formData.password}
        onChangeText={(text) => 
          setFormData({ ...formData, password: text })
        }
        placeholder="Password"
        secureTextEntry
      />
      <TouchableOpacity onPress={handleSubmit}>
        <Text>Submit</Text>
      </TouchableOpacity>
    </View>
  );
};
import React, { useState, useEffect, useRef, useMemo, useCallback, useReducer, useContext, useLayoutEffect } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';

// Create a Context
const ThemeContext = React.createContext('light');

// Reducer for task management
const taskReducer = (state, action) => {
  switch (action.type) {
    case 'ADD':
      return [...state, { id: Date.now(), text: action.payload }];
    case 'REMOVE':
      return state.filter(task => task.id !== action.payload);
    default:
      return state;
  }
};

const HooksDemo = () => {
  // useState Demo
  const [count, setCount] = useState(0);
  const [inputValue, setInputValue] = useState('');

  // useReducer Demo
  const [tasks, dispatch] = useReducer(taskReducer, []);

  // useRef Demo
  const inputRef = useRef(null);
  const renderCount = useRef(0);

  // useContext Demo
  const theme = useContext(ThemeContext);

  // useEffect Demo
  useEffect(() => {
    document.title = `Count: ${count}`;
    // Cleanup function
    return () => {
      document.title = 'React App';
    };
  }, [count]);

  // useLayoutEffect Demo
  useLayoutEffect(() => {
    renderCount.current += 1;
  });

  // useMemo Demo
  const expensiveComputation = useMemo(() => {
    return count * count * count;
  }, [count]);

  // useCallback Demo
  const handleAddTask = useCallback(() => {
    if (inputValue.trim()) {
      dispatch({ type: 'ADD', payload: inputValue });
      setInputValue('');
      inputRef.current?.focus();
    }
  }, [inputValue]);

  return (
    <Card className="w-full max-w-2xl p-4">
      <CardHeader>
        <CardTitle>React Hooks Demo</CardTitle>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* useState and useEffect Demo */}
        <div className="space-y-2">
          <h3 className="text-lg font-medium">useState & useEffect</h3>
          <p>Count: {count}</p>
          <Button 
            onClick={() => setCount(prev => prev + 1)}
            className="mr-2"
          >
            Increment
          </Button>
          <p className="text-sm text-gray-600">
            Check the page title - it updates with useEffect!
          </p>
        </div>

        {/* useRef Demo */}
        <div className="space-y-2">
          <h3 className="text-lg font-medium">useRef</h3>
          <p>Render Count: {renderCount.current}</p>
          <Input
            ref={inputRef}
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder="Enter a task..."
            className="max-w-sm"
          />
        </div>

        {/* useMemo Demo */}
        <div className="space-y-2">
          <h3 className="text-lg font-medium">useMemo</h3>
          <p>Expensive Computation (count³): {expensiveComputation}</p>
        </div>

        {/* useReducer & useCallback Demo */}
        <div className="space-y-2">
          <h3 className="text-lg font-medium">useReducer & useCallback</h3>
          <div className="flex gap-2">
            <Button onClick={handleAddTask}>Add Task</Button>
          </div>
          <ul className="list-disc pl-6">
            {tasks.map(task => (
              <li key={task.id} className="flex items-center gap-2">
                {task.text}
                <Button 
                  onClick={() => dispatch({ type: 'REMOVE', payload: task.id })}
                  variant="destructive"
                  size="sm"
                >
                  Remove
                </Button>
              </li>
            ))}
          </ul>
        </div>

        {/* useContext Demo */}
        <div className="space-y-2">
          <h3 className="text-lg font-medium">useContext</h3>
          <p>Current Theme: {theme}</p>
        </div>
      </CardContent>
    </Card>
  );
};

export default HooksDemo;