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, Layers, Rss } from 'lucide-react';
import useTranslation from '@/hooks/useTranslation';

export default function Show({ source, 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]);

    const loadMorePosts = async () => {
        if (!nextPageUrl || loading) return;
        
        setLoading(true);
        try {
            const res = await axios.get(nextPageUrl, { 
                headers: { 'Accept': 'application/json' } 
            });

            // Check if response data structure is valid
            if (res.data && Array.isArray(res.data.data)) {
                setPosts(prev => [...prev, ...res.data.data]);
                setNextPageUrl(res.data.next_page_url);
            } else {
                setNextPageUrl(null); // Stop crawling if API breaks
            }
        } catch (e) {
            console.error("Failed to load more posts:", e);
            setNextPageUrl(null); // Prevent infinite retry loops on error
        } 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">
                <Skeleton className="h-4 w-20 rounded-full" />
                <Skeleton className="h-6 w-full" />
                <Skeleton className="h-4 w-3/4" />
            </div>
        </div>
    );

    return (
        <>
            <Head title={`${t('_news_from', 'News from')} ${source.name}`} />

            <div className="bg-background min-h-screen pb-20">
                
                <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]">
                        
                        <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">{source.name}</span>
                        </nav>

                        <div className="flex flex-col md:flex-row md:items-center gap-6">
                            {source.feed_logo && (
                                <img src={source.feed_logo} alt={source.name} className="w-20 h-20 rounded-lg object-contain bg-white p-1 border shadow-sm" />
                            )}
                            <div className="space-y-2">
                                <h1 className="text-4xl md:text-5xl font-black tracking-tight text-foreground font-serif">
                                    {source.name}
                                </h1>
                                <p className="text-lg text-muted-foreground max-w-2xl leading-relaxed">
                                    {t('_latest_from_source', 'The latest articles automatically sourced from {sourceName}.').replace('{sourceName}', source.name)}
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-12 max-w-[1280px]">
                    
                    {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 && (
                                <>
                                    <PostSkeleton /><PostSkeleton /><PostSkeleton /><PostSkeleton />
                                </>
                            )}
                        </div>
                    ) : (
                        <div className="text-center py-24 bg-muted/20 rounded-xl border border-dashed 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_from_source', 'No news found from this source.')}</h3>
                            <Button asChild variant="outline" className="mt-6">
                                <Link href="/">{t('_back_to_home', 'Back to Home')}</Link>
                            </Button>
                        </div>
                    )}

                    <div ref={observerTarget} className="py-12 text-center">
                        {!loading && !nextPageUrl && posts.length > 0 && (
                            <div className="text-sm text-muted-foreground italic">{t('_end_of_content', 'End of content')}</div>
                        )}
                    </div>

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

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