import React, { useState, useEffect, useRef } from 'react';
import { Head, Link, usePage } from '@inertiajs/react';
import axios from 'axios';
import { cn } from '@/lib/utils';
import GuestLayout from '@/Layouts/GuestLayout';
import { Avatar, AvatarFallback, AvatarImage } from '@/Components/ui/avatar';
import { Skeleton } from '@/Components/ui/skeleton';
import { Calendar, Layers } from 'lucide-react'; 
import AdSlot from '@/Components/AdSlot'; 
import useTranslation from '@/hooks/useTranslation';
import FeedItem from '@/Pages/Welcome/Partials/FeedItem'; // <-- Imported FeedItem

export default function Profile({ auth, author, posts: initialPosts, ads }) {
    const { t } = useTranslation();
    
    // 1. Get site_settings from global props
    const { locale, site_settings } = usePage().props;

    const [posts, setPosts] = useState(initialPosts.data);
    const [nextPageUrl, setNextPageUrl] = useState(initialPosts.next_page_url);
    const [loading, setLoading] = useState(false);
    const observerTarget = useRef(null);

    // --- Dynamic Date Formatting ---
    const safeLocale = locale ? locale.replace('_', '-') : 'en-US';

    const formatDate = (dateString) => {
        if (!dateString) return '';
        return new Intl.DateTimeFormat(safeLocale, { 
            year: 'numeric', 
            month: 'long' 
        }).format(new Date(dateString));
    };

    // --- Infinite Scroll ---
    useEffect(() => {
        if (!observerTarget.current) return;
        const observer = new IntersectionObserver(
            (entries) => {
                if (entries[0].isIntersecting && nextPageUrl && !loading) {
                    loadMorePosts();
                }
            },
            { threshold: 0.5 }
        );
        observer.observe(observerTarget.current);
        return () => observer.disconnect();
    }, [nextPageUrl, loading]);

    const loadMorePosts = () => {
        if (loading || !nextPageUrl) return;
        setLoading(true);
        axios.get(nextPageUrl, {
            headers: { 'Accept': 'application/json' }
        }).then(res => {
            const newPostsData = res.data;
            if (newPostsData.data) {
                setPosts(prevPosts =>[...prevPosts, ...newPostsData.data]);
                setNextPageUrl(newPostsData.next_page_url);
            }
        }).catch(error => {
            console.error("Failed to load more posts", error);
        }).finally(() => {
            setLoading(false);
        });
    };

    const adMobileTop = ads?.['author_mobile_top'];
    const adSidebar1 = ads?.['author_sidebar_1'];
    const adSidebar2 = ads?.['author_sidebar_2'];
    const shouldShowAd = (ad) => ad && ad.is_active;

    // --- SEO & SHARE IMAGE LOGIC ---
    const siteName = site_settings?.site_name || 'Titan News';
    const pageTitle = `${author.name} - ${t('_author_profile', 'Author Profile')}`;
    const pageDescription = author.bio || t('_read_latest_articles_by', 'Read the latest articles by {name} on {site}.').replace('{name}', author.name).replace('{site}', siteName);
    
    // Image Logic: Author Avatar -> Default OG -> Null
    let shareImage = author.avatar || site_settings?.og_image;
    
    if (shareImage && !shareImage.startsWith('http')) {
        shareImage = `${window.location.origin}${shareImage}`;
    }

    // Matching Skeleton for FeedItem
    const FeedSkeleton = () => (
        <div className="flex flex-row gap-3 sm:gap-6 items-stretch border-b border-border pb-6 pt-4 last:border-0 animate-in fade-in slide-in-from-bottom-2">
            <Skeleton className="shrink-0 w-[35%] sm:w-[240px] min-h-[100px] sm:min-h-[140px] rounded-lg" />
            <div className="flex-1 flex flex-col justify-between py-1">
                <div>
                    <Skeleton className="h-3 w-16 mb-2 sm:mb-2 rounded-full" />
                    <Skeleton className="h-5 sm:h-6 w-11/12 mb-2 rounded-md" />
                    <Skeleton className="h-5 sm:h-6 w-3/4 mb-2 rounded-md" />
                    <div className="hidden sm:block space-y-1.5 mt-2">
                        <Skeleton className="h-3 w-full" />
                        <Skeleton className="h-3 w-5/6" />
                    </div>
                </div>
                <div className="flex flex-wrap items-center justify-between mt-2 w-full gap-2">
                    <div className="flex items-center gap-2 sm:gap-4">
                        <div className="flex items-center gap-1.5">
                            <Skeleton className="h-4 w-4 sm:h-5 sm:w-5 rounded-full" />
                            <Skeleton className="h-3 w-16 sm:w-20 rounded-md" />
                        </div>
                        <Skeleton className="h-3 w-px hidden sm:inline" />
                        <Skeleton className="h-3 w-16 rounded-md hidden sm:flex" />
                    </div>
                    <div className="flex items-center gap-3">
                        <Skeleton className="h-6 w-20 rounded-full" />
                        <Skeleton className="h-4 w-8 rounded-md" />
                    </div>
                </div>
            </div>
        </div>
    );

    return (
        <GuestLayout>
            <Head>
                <title>{pageTitle}</title>
                <meta name="description" content={pageDescription} />
                <meta property="og:type" content="profile" />
                <meta property="og:title" content={pageTitle} />
                <meta property="og:description" content={pageDescription} />
                {shareImage && <meta property="og:image" content={shareImage} />}
                <meta name="twitter:card" content="summary_large_image" />
                <meta name="twitter:title" content={pageTitle} />
                <meta name="twitter:description" content={pageDescription} />
                {shareImage && <meta name="twitter:image" content={shareImage} />}
            </Head>

            <div className="bg-background min-h-screen pb-12">
                
                {/* --- COVER IMAGE SECTION --- */}
                {author.cover_image ? (
                    <div className="w-full h-48 md:h-64 overflow-hidden relative">
                        <img 
                            src={author.cover_image} 
                            alt={`${author.name} cover`} 
                            className="w-full h-full object-cover"
                        />
                        <div className="absolute inset-0 bg-gradient-to-t from-background/80 to-transparent" />
                    </div>
                ) : (
                    <div className="w-full h-32 md:h-48 bg-gradient-to-r from-gray-100 to-gray-200 dark:from-zinc-900 dark:to-black" />
                )}

                <div className="container mx-auto px-4 sm:px-6 lg:px-8 max-w-[1200px]">
                    
                    {/* --- AUTHOR INFO --- */}
                    <div className="relative -mt-12 mb-8 flex flex-col items-center sm:items-start text-center sm:text-start">
                        <Avatar className="h-32 w-32 border-[6px] border-background shadow-lg bg-background">
                            <AvatarImage src={author.avatar || `https://ui-avatars.com/api/?name=${author.name.replace(/\s/g, '+')}&size=128`} className="object-cover" />
                            <AvatarFallback className="text-4xl">{author.name.charAt(0)}</AvatarFallback>
                        </Avatar>
                        
                        <div className="mt-4 space-y-2 max-w-2xl">
                            <div>
                                <h1 className="text-3xl font-extrabold tracking-tight text-foreground">{author.name}</h1>
                                <p className="text-sm font-medium text-muted-foreground flex items-center justify-center sm:justify-start gap-1">
                                    @{author.username} 
                                    <span className="mx-1">•</span> 
                                    <Calendar className="w-3 h-3" /> {t('_joined', 'Joined')} {formatDate(author.created_at)}
                                </p>
                            </div>
                            
                            <p className="text-base text-foreground/80 leading-relaxed whitespace-pre-wrap">
                                {author.bio || t('_no_bio', "This author hasn't written a bio yet.")}
                            </p>
                        </div>
                    </div>

                    {shouldShowAd(adMobileTop) && (
                        <div className="lg:hidden mb-8 flex justify-center">
                            <AdSlot ad={adMobileTop} className="w-full max-w-[320px]" />
                        </div>
                    )}

                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-12 mt-8">
                        
                        <main className="lg:col-span-8">
                            <div className="flex items-center gap-2 mb-4">
                                <h3 className="font-bold text-xl border-b-2 border-primary pb-1">
                                    {t('_latest_articles', 'Latest Articles')}
                                </h3>
                            </div>

                            <div className="grid gap-0">
                                {posts.length > 0 ? (
                                    posts.map((post) => (
                                        <FeedItem key={post.id} post={post} auth={auth} />
                                    ))
                                ) : (
                                    <div className="py-20 text-center bg-muted/30 rounded-lg flex flex-col items-center">
                                        <Layers className="w-10 h-10 opacity-20 mb-2" />
                                        <p className="text-muted-foreground">{t('_no_articles_published', 'No articles published yet.')}</p>
                                    </div>
                                )}
                            </div>

                            <div ref={observerTarget} className="py-8">
                                {loading && (
                                    <div className="mt-2">
                                        <FeedSkeleton />
                                        <FeedSkeleton />
                                    </div>
                                )}
                                {!loading && !nextPageUrl && posts.length > 0 && (
                                    <div className="text-center pt-8">
                                        <p className="text-xs text-muted-foreground uppercase tracking-widest italic">{t('_end_of_list', 'End of list.')}</p>
                                    </div>
                                )}
                            </div>
                        </main>

                        <aside className="hidden lg:block lg:col-span-4 space-y-8 ps-6 border-s border-border">
                            <div className="sticky top-24 space-y-8">
                                {shouldShowAd(adSidebar1) && (
                                    <div className="bg-card border rounded-lg shadow-sm p-4">
                                        <h3 className="text-[10px] font-bold text-muted-foreground uppercase mb-2 text-center">{t('_advertisement', 'Advertisement')}</h3>
                                        <AdSlot ad={adSidebar1} className="w-full" />
                                    </div>
                                )}

                                {shouldShowAd(adSidebar2) && (
                                    <div className="bg-card border rounded-lg shadow-sm p-4">
                                        <h3 className="text-[10px] font-bold text-muted-foreground uppercase mb-2 text-center">{t('_advertisement', 'Advertisement')}</h3>
                                        <AdSlot ad={adSidebar2} className="w-full" />
                                    </div>
                                )}
                            </div>
                        </aside>

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