import React, { useState, useEffect, useRef } from 'react';
import { Head, Link } from '@inertiajs/react';
import axios from 'axios';
import GuestLayout from '@/Layouts/GuestLayout';
import PostCard from '@/Components/PostCard';
import { Button } from '@/Components/ui/button';
import { Skeleton } from '@/Components/ui/skeleton';
import { ChevronRight, FolderOpen, Layers, Newspaper } from 'lucide-react';
import useTranslation from '@/hooks/useTranslation';

export default function Show({ category, posts: initialPosts }) {
    // --- State ---
    const [posts, setPosts] = useState(initialPosts.data);
    const [nextPageUrl, setNextPageUrl] = useState(initialPosts.next_page_url);
    const [loading, setLoading] = useState(false);
    const observerTarget = useRef(null);
    const { t } = useTranslation(); 

    // --- Infinite Scroll Observer ---
    useEffect(() => {
        if (!observerTarget.current) return;

        const observer = new IntersectionObserver(
            (entries) => {
                if (entries[0].isIntersecting && nextPageUrl && !loading) {
                    loadMorePosts();
                }
            },
            { threshold: 0.1, rootMargin: '100px' }
        );

        observer.observe(observerTarget.current);
        return () => observer.disconnect();
    }, [nextPageUrl, loading]);

    // --- Load More Logic ---
    const loadMorePosts = async () => {
        if (!nextPageUrl) return;
        
        setLoading(true);
        try {
            const res = await axios.get(nextPageUrl, {
                headers: { 'Accept': 'application/json' }
            });
            
            const newPosts = res.data;
            
            if (newPosts.data && Array.isArray(newPosts.data)) {
                setPosts(prev => [...prev, ...newPosts.data]);
                setNextPageUrl(newPosts.next_page_url);
            } else {
                console.error("API Error: Expected JSON with 'data' array, got:", newPosts);
                setNextPageUrl(null);
            }

        } catch (e) {
            console.error("Failed to load more posts:", e);
        } finally {
            setLoading(false);
        }
    };

    // --- Skeleton Component ---
    const PostSkeleton = () => (
        <div className="flex flex-col space-y-3">
            <Skeleton className="aspect-[16/9] w-full rounded-xl" />
            <div className="space-y-2 pt-2">
                <div className="flex justify-between items-center">
                    <Skeleton className="h-4 w-20 rounded-full" />
                    <Skeleton className="h-3 w-16" />
                </div>
                <Skeleton className="h-6 w-full" />
                <Skeleton className="h-6 w-3/4" />
            </div>
        </div>
    );

    // This component is wrapped in GuestLayout, so we don't need 'auth' prop here
    return (
        <>
            <Head title={`${category.name} ${t('_news_title', 'News')}`} />

            <div className="bg-background min-h-screen pb-20">
                
                {/* --- Hero Header Section --- */}
                <div className="relative bg-muted/30 border-b border-border">
                    <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-12 max-w-[1280px]">
                        
                        {/* Breadcrumb */}
                        <nav className="flex items-center text-sm text-muted-foreground mb-6 font-medium">
                            <Link href="/" className="hover:text-primary transition-colors">{t('_home', 'Home')}</Link>
                            <ChevronRight className="w-4 h-4 mx-2 opacity-50 rtl:-scale-x-100" />
                            <span className="text-foreground">{category.name}</span>
                        </nav>

                        <div className="flex flex-col md:flex-row md:items-end justify-between gap-6">
                            <div className="space-y-4">
                                <h1 className="text-4xl md:text-5xl font-black tracking-tight capitalize text-foreground font-serif flex items-center gap-3">
                                    <FolderOpen className="w-10 h-10 text-primary" />
                                    {category.name}
                                </h1>
                                <p className="text-lg text-muted-foreground max-w-2xl leading-relaxed">
                                    {t('_category_description_start', 'Browse the latest headlines, in-depth analysis, and reports from the')}
                                    <span className="font-semibold text-foreground mx-1">{category.name}</span>
                                    {t('_category_description_end', 'section.')}
                                </p>
                            </div>
                            <div className="hidden md:block opacity-50">
                                <Newspaper className="w-24 h-24 text-muted-foreground/20" />
                            </div>
                        </div>
                    </div>
                </div>

                <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-12 max-w-[1280px]">
                    
                    {/* --- Posts Grid --- */}
                    {posts.length > 0 ? (
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-x-6 gap-y-10">
                            {posts.map((post) => (
                                <div key={post.id} className="animate-in fade-in zoom-in-95 duration-500">
                                    <PostCard post={post} />
                                </div>
                            ))}
                            
                            {/* Loading Skeletons */}
                            {loading && (
                                <>
                                    <PostSkeleton />
                                    <PostSkeleton />
                                    <PostSkeleton />
                                    <PostSkeleton />
                                </>
                            )}
                        </div>
                    ) : (
                        <div className="text-center py-24 bg-muted/20 rounded-xl border border-dashed border-muted-foreground/25 flex flex-col items-center">
                            <Layers className="w-16 h-16 text-muted-foreground/30 mb-4" />
                            <h3 className="text-xl font-bold text-muted-foreground">{t('_no_news_in_category', 'No news found in this category.')}</h3>
                            <p className="text-sm text-muted-foreground mt-2 mb-6">{t('_check_back_soon', 'We haven\'t published any stories here yet. Check back soon.')}</p>
                            <Button asChild variant="outline">
                                <Link href="/">{t('_back_to_home', 'Back to Home')}</Link>
                            </Button>
                        </div>
                    )}

                    {/* --- Infinite Scroll Sentinel --- */}
                    <div ref={observerTarget} className="py-12 text-center">
                        {!loading && !nextPageUrl && posts.length > 0 && (
                            <div className="flex items-center justify-center gap-4 text-muted-foreground/50">
                                <div className="h-px w-16 bg-border"></div>
                                <span className="text-xs font-medium uppercase tracking-widest">{t('_end_of_content', 'End of content')}</span>
                                <div className="h-px w-16 bg-border"></div>
                            </div>
                        )}
                    </div>

                </div>
            </div>
        </>
    );
}

Show.layout = (page) => <GuestLayout children={page} />;