// src/screens/HomeScreen.tsx

import React, { useCallback, useContext, useState, useEffect } from 'react';
import { 
  View, 
  FlatList, 
  Image, 
  TouchableOpacity, 
  StyleSheet, 
  SafeAreaView,
  ActivityIndicator,
  useWindowDimensions,
  RefreshControl,
  ScrollView,
  Alert,
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure } from '../types/types';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
import { useApp } from '../context/AppContext';
import { ChatContext } from '../context/ChatContext';
import { CoinContext } from '../context/CoinContext';
import uuid from 'react-native-uuid'; // Ensure correct import
import AsyncStorage from '@react-native-async-storage/async-storage';

const HomeScreen = () => {
  const navigation = useNavigation();
  const { 
    historicalFigures, 
    loading, 
    refreshing, 
    t, 
    currentTheme, 
    refreshFigures,
    categories,
  } = useApp();
  const { width } = useWindowDimensions();

  const { addChat } = useContext(ChatContext);
  const { coins, showRewardedAd } = useContext(CoinContext);
  const [selectedCategory, setSelectedCategory] = useState<string>('All');
  const [isCreatingChat, setIsCreatingChat] = useState<boolean>(false); // New state
  const [isGlobalLoading, setIsGlobalLoading] = useState<boolean>(false); // Central loading state

  const numColumns = 2;

  useEffect(() => {
    // Manage global loading state based on 'loading' or 'isCreatingChat'
    if (loading || isCreatingChat) {
      setIsGlobalLoading(true);
    } else {
      setIsGlobalLoading(false);
    }
  }, [loading, isCreatingChat]);

  const startChat = useCallback(async (figure: HistoricalFigure) => {
    if (isCreatingChat) return; // Prevent multiple chat creations
    setIsCreatingChat(true); // Set loading state
    try {
      const chatId = uuid.v4().toString();
      console.log('Generated chatId:', chatId); // Logging for debugging

      await addChat({
        id: chatId,
        figure,
        createdAt: Date.now(),
      });

      navigation.navigate('Chat', { chatId, figure });
    } catch (error) {
      console.error('Error starting chat:', error);
      Alert.alert(t('error'), t('errorStartingChat'));
    } finally {
      setIsCreatingChat(false); // Reset loading state
    }
  }, [addChat, navigation, t, isCreatingChat]);

  const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
    <TouchableOpacity
      style={[styles.figureItem, { backgroundColor: currentTheme.cardBackground }]}
      onPress={() => startChat(item)}
      disabled={isCreatingChat} // Disable while creating
    >
      <Image source={{ uri: item.image }} style={styles.avatar} />
      <View style={styles.figureTextContainer}>
        <CustomText bold style={[styles.figureName, { color: currentTheme.textColor }]}>
          {item.name}
        </CustomText>
        <CustomText style={[styles.figureCategory, { color: currentTheme.accentColor }]}>
          {item.category}
        </CustomText>
        <CustomText 
          style={[styles.figureDescription, { color: currentTheme.secondaryTextColor }]} 
          numberOfLines={3}
        >
          {item.description}
        </CustomText>
        <CustomText style={[styles.popularity, { color: currentTheme.accentColor }]}>
          {t('popularity')} {item.popularity || 0}
        </CustomText>
      </View>
    </TouchableOpacity>
  ), [currentTheme, startChat, t, isCreatingChat]);

  const keyExtractor = useCallback((item: HistoricalFigure) => item.id, []);

  const onRefresh = useCallback(async () => {
    await refreshFigures(); // This will handle refreshing state in AppContext
  }, [refreshFigures]);

  const filteredFigures = selectedCategory === 'All' 
    ? historicalFigures 
    : historicalFigures.filter(fig => fig.category === selectedCategory);

  const renderCategoryItem = useCallback((category: string, index: number) => {
    const isSelected = category === selectedCategory;
    return (
      <TouchableOpacity
        key={`${category}-${index}`} // Ensure each item has a unique key
        style={[
          styles.categoryButton,
          { 
            backgroundColor: isSelected ? currentTheme.accentColor : 'transparent',
            borderColor: isSelected ? currentTheme.accentColor : currentTheme.secondaryTextColor,
          }
        ]}
        onPress={() => setSelectedCategory(category)}
      >
        <CustomText 
          style={[
            styles.categoryText, 
            { 
              color: isSelected ? currentTheme.backgroundColor : currentTheme.textColor,
            }
          ]}
        >
          {t(category)}
        </CustomText>
      </TouchableOpacity>
    );
  }, [selectedCategory, currentTheme, t]);

  const renderCategoryRows = () => {
    // Display categories in two rows for better organization
    const halfLength = Math.ceil(categories.length / 2);
    return (
      <ScrollView 
        horizontal 
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.categoryRowsContainer}
      >
        <View>
          <View style={styles.categoryRow}>
            {categories.slice(0, halfLength).map((category, index) => renderCategoryItem(category, index))}
          </View>
          <View style={styles.categoryRow}>
            {categories.slice(halfLength).map((category, index) => renderCategoryItem(category, index + halfLength))}
          </View>
        </View>
      </ScrollView>
    );
  };

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: currentTheme.backgroundColor }]}>
      <StatusBar style={currentTheme.statusBarStyle} />
      <View style={styles.container}>
        {/* Header */}
        <View style={styles.header}>
          <CustomText bold style={[styles.title, { color: currentTheme.textColor }]}>
            {t('historicalFigures')}
          </CustomText>
          <View style={styles.headerRight}>
            {/* Coin Display */}
            <TouchableOpacity style={styles.coinContainer} onPress={showRewardedAd}>
              <Ionicons name="flash" size={20} color={currentTheme.accentColor} />
              <CustomText style={[styles.coinText, { color: currentTheme.textColor }]}>
                {coins}
              </CustomText>
            </TouchableOpacity>
            {/* Settings Button */}
            <TouchableOpacity 
              style={styles.settingsButton} 
              onPress={() => navigation.navigate('Settings')}
            >
              <Ionicons name="settings-outline" size={24} color={currentTheme.accentColor} />
            </TouchableOpacity>
          </View>
        </View>

        {/* Category Selector (Two Rows, Scrollable Horizontally) */}
        {renderCategoryRows()}

        {/* Content */}
        {loading ? (
          // Single centralized loading indicator
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={currentTheme.accentColor} />
          </View>
        ) : filteredFigures.length === 0 ? (
          <View style={styles.emptyContainer}>
            <CustomText style={[styles.emptyText, { color: currentTheme.textColor }]}>
              {t('noFiguresInThisCategory')}
            </CustomText>
          </View>
        ) : (
          <FlatList
            data={filteredFigures}
            renderItem={renderFigureItem}
            keyExtractor={keyExtractor}
            contentContainerStyle={styles.figureList}
            numColumns={numColumns}
            showsVerticalScrollIndicator={false}
            refreshControl={
              <RefreshControl
                refreshing={refreshing}
                onRefresh={onRefresh}
                colors={[currentTheme.accentColor]}
                tintColor={currentTheme.accentColor}
              />
            }
          />
        )}
      </View>

      {/* Global Loading Overlay */}
      {isGlobalLoading && (
        <View style={styles.loadingOverlay}>
          <ActivityIndicator size="large" color={currentTheme.accentColor} />
        </View>
      )}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
  },
  container: {
    flex: 1,
    paddingHorizontal: 10,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 15,
    paddingHorizontal: 15,
  },
  title: {
    fontFamily: 'Poppins_700Bold',
    fontSize: 24,
  },
  headerRight: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  coinContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 5,
  },
  coinText: {
    fontFamily: 'Poppins_700Bold',
    fontSize: 18,
    marginLeft: 5,
  },
  settingsButton: {
    padding: 2,
    marginLeft: 15, // Increased spacing for better visual separation
  },
  categoryRowsContainer: {
    paddingHorizontal: 5,
    paddingBottom: 20,
  },
  categoryRow: {
    flexDirection: 'row',
    marginBottom: 6,
  },
  categoryButton: {
    paddingVertical: 8,
    paddingHorizontal: 10, // Increased padding for better touch area
    borderRadius: 16,
    borderWidth: 1,
    marginRight: 5, // Increased margin for better spacing
  },
  categoryText: {
    fontFamily: 'Poppins_600SemiBold',
    fontSize: 14,
  },
  figureList: {
    paddingVertical: 10,
  },
  figureItem: {
    borderRadius: 12,
    elevation: 3,
    flex: 1,
    margin: 5,
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.22,
    shadowRadius: 2.22,
    shadowColor: '#000',
  },
  avatar: {
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    height: 120, // Uniform height across all images
    width: '100%', // Span the full width of the figure item
    resizeMode: 'cover', // Cover ensures the image fills the space without distortion
  },
  figureTextContainer: {
    padding: 10,
  },
  figureName: {
    fontFamily: 'Poppins_700Bold',
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 4,
  },
  figureCategory: {
    fontFamily: 'Poppins_600SemiBold',
        textAlign: 'center',

    fontSize: 12,
    marginBottom: 4,
  },
  figureDescription: {
    fontFamily: 'Poppins_400Regular',
    fontSize: 14,
    textAlign: 'center',
    marginBottom: 4,
  },
  popularity: {
        textAlign: 'center',

    fontSize: 14,
    fontFamily: 'Poppins_600SemiBold',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  emptyText: {
    fontSize: 16,
    textAlign: 'center',
  },
  loadingOverlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.3)', // Semi-transparent background
    zIndex: 1000, // Ensure overlay is on top
  },
});

export default HomeScreen; hacı buradaki tüm loadingleri, loading activity indicatorleri hepsini kaldır. onun yerine bu paketi kullanarak placeholder yapacağız:
Example's react-content-loader

SVG-Powered component to easily create placeholder loadings (like Facebook's cards loading).

Features
⚙️ Customizable: Feel free to change the colors, speed, sizes, and even RTL;
👌 Plug and play: with many presets to use, see the examples;
✏️ DIY: use the create-content-loader to create your own custom loaders easily;
📱 React Native support: same API, as same powerful features;
⚛️ Really lightweight: less than 2kB and 0 dependencies for web version;
Index
Getting Started
Usage
Native
Options
Examples
Troubleshooting
Similar packages
Development
Getting Started
npm i react-content-loader --save
yarn add react-content-loader
For React Native
npm i react-content-loader react-native-svg --save
yarn add react-content-loader react-native-svg
CDN from JSDELIVR

Usage
There are two ways to use it:

1. Presets, see the examples:

import ContentLoader, { Facebook } from 'react-content-loader'

const MyLoader = () => <ContentLoader />
const MyFacebookLoader = () => <Facebook />
2. Custom mode, see the online tool

const MyLoader = () => (
  <ContentLoader viewBox="0 0 380 70">
    {/* Only SVG shapes */}    
    <rect x="0" y="0" rx="5" ry="5" width="70" height="70" />
    <rect x="80" y="17" rx="4" ry="4" width="300" height="13" />
    <rect x="80" y="40" rx="3" ry="3" width="250" height="10" />
  </ContentLoader>
)
Still not clear? Take a look at this working example at codesandbox.io Or try the components editable demo hands-on and install it from bit.dev

Native
react-content-loader can be used with React Native in the same way as web version with the same import:

1. Presets, see the examples:

import ContentLoader, { Facebook } from 'react-content-loader/native'

const MyLoader = () => <ContentLoader />
const MyFacebookLoader = () => <Facebook />
2. Custom mode

To create custom loaders there is an important difference: as React Native doesn't have any native module for SVG components, it's necessary to import the shapes from react-native-svg or use the named export Rect and Circle from react-content-loader import:

import ContentLoader, { Rect, Circle } from 'react-content-loader/native'

const MyLoader = () => (
  <ContentLoader viewBox="0 0 380 70">
    <Circle cx="30" cy="30" r="30" />
    <Rect x="80" y="17" rx="4" ry="4" width="300" height="13" />
    <Rect x="80" y="40" rx="3" ry="3" width="250" height="10" />
  </ContentLoader>
)
Options
Prop name and type
Environment	Description
animate?: boolean
Defaults to true	React DOM
React Native	Opt-out of animations with false
title?: string
Defaults to Loading...	React DOM only	It's used to describe what element it is. 
Use '' (empty string) to remove.
baseUrl?: string
Defaults to an empty string	React DOM only	Required if you're using <base url="/" /> document <head/>. 
This prop is common used as: 
<ContentLoader baseUrl={window.location.pathname} /> which will fill the SVG attribute with the relative path. Related #93.
speed?: number
Defaults to 1.2	React DOM
React Native	Animation speed in seconds.
viewBox?: string
Defaults to undefined	React DOM
React Native	Use viewBox props to set a custom viewBox value,
for more information about how to use it,
read the article How to Scale SVG.
gradientRatio?: number
Defaults to 1.2	React DOM only	Width of the animated gradient as a fraction of the view box width.
rtl?: boolean
Defaults to false	React DOM
React Native	Content right-to-left.
backgroundColor?: string
Defaults to #f5f6f7	React DOM
React Native	Used as background of animation.
foregroundColor?: string
Defaults to #eee	React DOM
React Native	Used as the foreground of animation.
backgroundOpacity?: number
Defaults to 1	React DOM only	Background opacity (0 = transparent, 1 = opaque)
used to solve an issue in Safari
foregroundOpacity?: number
Defaults to 1	React DOM only	Animation opacity (0 = transparent, 1 = opaque)
used to solve an issue in Safari
style?: React.CSSProperties
Defaults to {}	React DOM only	
uniqueKey?: string
Defaults to random unique id	React DOM only	Use the same value of prop key, 
that will solve inconsistency on the SSR, see more here.
beforeMask?: JSX.Element
Defaults to null	React DOM
React Native	Define custom shapes before content, 
see more here.
See all options live

Examples
Facebook Style
import { Facebook } from 'react-content-loader'

const MyFacebookLoader = () => <Facebook />
Facebook Style

Instagram Style
import { Instagram } from 'react-content-loader'

const MyInstagramLoader = () => <Instagram />
Instagram Style

Code Style
import { Code } from 'react-content-loader'

const MyCodeLoader = () => <Code />
Code Style

List Style
import { List } from 'react-content-loader'

const MyListLoader = () => <List />
List Style

Bullet list Style
import { BulletList } from 'react-content-loader'

const MyBulletListLoader = () => <BulletList />
Bullet list Style

Custom Style
For the custom mode, use the online tool.

const MyLoader = () => (
  <ContentLoader
    height={140}
    speed={1}
    backgroundColor={'#333'}
    foregroundColor={'#999'}
    viewBox="0 0 380 70"
  >
    {/* Only SVG shapes */}
    <rect x="0" y="0" rx="5" ry="5" width="70" height="70" />
    <rect x="80" y="17" rx="4" ry="4" width="300" height="13" />
    <rect x="80" y="40" rx="3" ry="3" width="250" height="10" />
  </ContentLoader>
)
Custom

Troubleshooting
Responsive - Mobile version
In order to avoid unexpected behavior, the package doesn't have opinioned settings. So if it needs to be responsive, have in mind that the output of the package is a regular SVG, so it just needs the same attributes to become a regular SVG responsive, which means:

import { Code } from 'react-content-loader'

const MyCodeLoader = () => (
  <Code
    width={100}
    height={100}
    viewBox="0 0 100 100"
    style={{ width: '100%' }}
  />
)
Server-side rendering (SSR) - Match snapshot
As the main component generates random values to match the id of the SVG element with background style, it can encounter unexpected errors and unmatching warning on render, once the random value of id will be generated twice, in case of SSR: server and client; or in case of snapshot test: on the first match and re-running the test.

To fix it, set the prop uniqueKey, then the id will not be random anymore:

import { Facebook } from 'react-content-loader'

const MyFacebookLoader = () => <Facebook uniqueKey="my-random-value" />
Alpha is not working: Safari / iOS
When using rgba as a backgroundColor or foregroundColor value, Safari does not respect the alpha channel, meaning that the color will be opaque. To prevent this, instead of using a rgba value for backgroundColor/foregroundColor, use the rgb equivalent and move the alpha channel value to the backgroundOpacity/foregroundOpacity props.

{/* Opaque color in Safari and iOS */}
<ContentLoader
  backgroundColor="rgba(0,0,0,0.06)"
  foregroundColor="rgba(0,0,0,0.12)">


{/_ Semi-transparent color in Safari and iOS _/}
<ContentLoader
    backgroundColor="rgb(0,0,0)"
    foregroundColor="rgb(0,0,0)"
    backgroundOpacity={0.06}
    foregroundOpacity={0.12}>
Black box in Safari / iOS (again)
Using the base tag on a page that contains SVG elements fails to render and it looks like a black box. Just remove the base-href tag from the <head /> and the issue has been solved.

black box

See: #93 / 109

Browser supports SVG-Animate
Old browsers don't support animation in SVG (compatibility list), and if your project must support IE, for examples, here's a couple of ways to make sure that browser supports SVG Animate:

window.SVGAnimateElement
document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#SVG-Animation", "1.1")
Or even use https://modernizr.com/
Similar packages
React Native: rn-placeholder, react-native-svg-animated-linear-gradient;
Preact;
Vue.js: vue-content-loading, vue-content-loader;
Angular: ngx-content-loading, ngx-content-loader.
Development
Fork the repo and then clone it

$ git clone git@github.com:YourUsername/react-content-loader.git && cd react-content-loader
$ npm i: Install the dependencies;

$ npm run build: Build to production;

$ npm run dev: Run the Storybook to see your changes;

$ npm run test: Run all tests: type checking, unit tests on web and native;

$ npm run test:watch: Watch unit tests;

React Native
As React Native doesn't support symbolic links (to link the dependency to another folder) and as there is no playground to check your contributions (like storybook), this is recommended strategy to run the project locally:

Create a new React Native from scratch, either Metro or create-react-native-app;
Install the dependency to your root project: yarn add react-content-loader react-native-svg
Open the project just created and clone this repository there;
Create your loading component and point the react-content-loader to the project just cloned, like: import ContentLoader, { Rect, Circle } from './react-content-loader/native'
Commit messages
Commit messages should follow the commit message convention so, changelogs could be generated automatically by that. Commit messages are validated automatically upon commit. If you aren't familiar with the commit message convention, you can use yarn commit (or npm run commit) instead of git commit, which provides an interactive CLI for generating proper commit messages.

License