import { useState, useEffect } from 'react';
import { wpApi } from '../api/wordpress';

export function usePosts(page = 1, perPage = 10, categoryByIdOrSlug = null) {
    const [posts, setPosts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [totalPages, setTotalPages] = useState(0);

    useEffect(() => {
        const fetchPosts = async () => {
            setLoading(true);
            try {
                let categoryId = null;

                // Determine if the input is a slug (string) or ID (number)
                if (typeof categoryByIdOrSlug === 'string') {
                    const categories = await wpApi.getCategories(categoryByIdOrSlug);
                    if (categories && categories.length > 0) {
                        categoryId = categories[0].id;
                    } else {
                        // Category not found by slug
                        console.warn(`Category slug "${categoryByIdOrSlug}" not found.`);
                        setPosts([]);
                        setLoading(false);
                        return;
                    }
                } else {
                    categoryId = categoryByIdOrSlug;
                }

                const { data, totalPages } = await wpApi.getPosts(page, perPage, categoryId);
                setPosts(data);
                setTotalPages(totalPages);
                setError(null);
            } catch (err) {
                setError(err);
            } finally {
                setLoading(false);
            }
        };

        fetchPosts();
    }, [page, perPage, categoryByIdOrSlug]);

    return { posts, loading, error, totalPages };
}
