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 { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { ChevronRight, Hash, Loader2, Frown } from 'lucide-react';
import useTranslation from '@/hooks/useTranslation'; 

export default function TagShow({ tag, initialPosts }) {
    const { t } = useTranslation(); 
    
    const [posts, setPosts] = useState(initialPosts.data || []);
    const [nextPageUrl, setNextPageUrl] = useState(initialPosts.next_page_url);
    const [loading, setLoading] = useState(false);
    const observerTarget = useRef(null);

    useEffect(() => {
        if (!observerTarget.current) return;

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

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

    const loadMorePosts = async () => {
        if (!nextPageUrl || loading) return;

        setLoading(true);
        try {
            const res = await axios.get(nextPageUrl, {
                headers: { 'Accept': 'application/json' }
            });

            if (res.data && Array.isArray(res.data.data)) {
                setPosts(prev => [...prev, ...res.data.data]);
                setNextPageUrl(res.data.next_page_url);
            } else {
                // Prevent infinite loop if API returns unexpected HTML/Text
                setNextPageUrl(null); 
            }
        } catch (error) {
            console.error("Failed to load more posts:", error);
            setNextPageUrl(null); // Stop fetching on error
        } finally {
            setLoading(false);
        }
    };

    return (
        <GuestLayout>
            <Head title={`${t('_tag', 'Tag')}: ${tag}`} />

            <div className="bg-background min-h-screen pb-20">
                <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-8 max-w-[1280px]">
                    
                    {/* Breadcrumbs */}
                    <nav className="flex items-center text-sm text-muted-foreground mb-6 font-medium">
                        <Link href="/" className="hover:text-primary hover:underline transition-colors">
                            {t('_home', 'Home')}
                        </Link>
                        <ChevronRight className="w-4 h-4 mx-2 text-gray-400 rtl:rotate-180" />
                        <span className="font-bold text-foreground">{t('_tag', 'Tag')}: {tag}</span>
                    </nav>

                    {/* Header */}
                    <div className="mb-8">
                        <h1 className="text-4xl font-extrabold tracking-tight capitalize flex items-center gap-3">
                            <Hash className="w-10 h-10 text-primary" /> {tag}
                        </h1>
                        <p className="text-muted-foreground mt-2 text-lg">
                            {t('_discover_articles', 'Discover articles related to the tag')} "{tag}".
                        </p>
                    </div>

                    <Separator className="my-8" />

                    {posts.length > 0 ? (
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                            {posts.map((post) => (
                                <PostCard key={post.id} post={post} />
                            ))}
                        </div>
                    ) : (
                        <div className="text-center py-20 bg-muted/30 rounded-lg border border-dashed flex flex-col items-center">
                            <Frown className="w-12 h-12 text-muted-foreground/50 mb-4" />
                            <h3 className="text-xl font-bold text-muted-foreground">{t('_no_posts_found', 'No posts found for this tag.')}</h3>
                            <p className="text-sm text-muted-foreground mt-1">{t('_check_back_later', 'Check back later for updates.')}</p>
                            <Button asChild className="mt-6" variant="outline">
                                <Link href="/">{t('_back_home', 'Back Home')}</Link>
                            </Button>
                        </div>
                    )}

                    <div ref={observerTarget} className="py-10 text-center">
                        {loading && (
                            <div className="flex justify-center items-center gap-2 text-muted-foreground">
                                <Loader2 className="w-5 h-5 animate-spin" />
                                <span>{t('_loading_more', 'Loading more...')}</span>
                            </div>
                        )}
                        {!loading && !nextPageUrl && posts.length > 0 && (
                            <p className="text-sm text-muted-foreground italic">{t('_end_of_list', "You've reached the end.")}</p>
                        )}
                    </div>

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