import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import axios from 'axios'
import { API_BASE_URL, SITE_TITLE } from '../config'

const HomePage = () => {
  const [posts, setPosts] = useState([])

  useEffect(() => {
    const fetchPosts = async () => {
      try {
        const response = await axios.get(`${ API_BASE_URL }/posts`)
        setPosts(response.data)
      } catch (error) {
        console.error('Failed to fetch posts:', error)
      }
    }
    fetchPosts()
    document.title = `${ SITE_TITLE }　〜 ぼざクリも、ぼざろ外も、外伝もあるんだよ。`
  }, [])

  return (
    <div className="flex flex-wrap gap-4 p-4">
      {posts.map (post => (
        <Link
          to={`/posts/${post.id}`}
          key={post.id}
          className="w-40 h-40 overflow-hidden rounded-lg shadow-md hover:shadow-lg"
        >
          <img
            src={post.thumbnail}
            className="object-cover w-full h-full"
          />
        </Link>
      ))}
    </div>
  )
}

export default HomePage
