import { useEffect, useMemo, useState } from 'react'
import './App.css'
import Header from './components/Header'
import PostList from './components/PostList'
import type { Post } from './components/types'
import axios from 'axios'

function App() {


  const [posts, setPosts] = useState<Post[]>([]);

  const [searchTerm, setSearchTerm] = useState("");


  const fetchPosts = async () => {
    const response = await axios.get<Post[]>("https://jsonplaceholder.typicode.com/posts");


    setPosts(response.data);

    console.log("Posts fetched:", response.data);

  };

  useEffect(() => {

    fetchPosts();

  }, [])



  const normalize = (str: string) => str.replace(/\s+/g, " ").toLowerCase();


  const filteredPosts = useMemo(() => {
    return posts.filter(post => {
      if (searchTerm == "") {
        return true;
      }

      if (normalize(post.body).includes(searchTerm.toLowerCase()) || post.title.toLowerCase().includes(searchTerm.toLowerCase())) {
        return true;

      } else {
        return false;
      }
    }

    );
  },[posts, searchTerm]);










  return (
    <>

      <Header setRefresh={fetchPosts} searchTerm={searchTerm} setSearchTerm={setSearchTerm} />

      <PostList posts={filteredPosts} />

    </>

  )
}

export default App
