import React, { useState, useEffect } from 'react';
import { Head, Link, usePage } from '@inertiajs/react';
import axios from 'axios';
import GuestLayout from '@/Layouts/GuestLayout';
import { Separator } from '@/Components/ui/separator';
import { Skeleton } from '@/Components/ui/skeleton';
import { TrendingUp } from 'lucide-react'; 
import AdSlot from '@/Components/AdSlot';
import TimeDisplay from '@/Components/TimeDisplay'; 
import RightSidebarFooter from '@/Components/RightSidebarFooter';
import useTranslation from '@/hooks/useTranslation';

import HeroSlider from './Welcome/Partials/HeroSlider';
import GridItem from './Welcome/Partials/GridItem';
import HighlightedFeedTabs from './Welcome/Partials/HighlightedFeedTabs'; 

export default function Welcome({ auth, heroSlider, subHeroPosts, ads }) { 
    const { t } = useTranslation();
    const { site_settings } = usePage().props;
    
    const siteName = site_settings?.site_name || 'Titan News';
    const pageTitle = site_settings?.og_title || `${siteName} - Global Perspectives`;

    const [initialLatestData, setInitialLatestData] = useState(null); 
    const [trendingPosts, setTrendingPosts] = useState([]);
    const [tabCounts, setTabCounts] = useState({ featured: 0, editor_picks: 0, hot_news: 0 });
    const [initialLoading, setInitialLoading] = useState(true);
    
    useEffect(() => {
        const fetchData = async () => {
            try {
                const res = await axios.get('/api/home-data');
                setInitialLatestData(res.data.latest); 
                setTrendingPosts(res.data.trending);
                setTabCounts(res.data.tab_counts); 
            } catch (error) {
                console.error("Failed to load home data");
            } finally {
                setInitialLoading(false);
            }
        };
        fetchData();
    }, []);

    const adMobile = ads?.['home_mobile_top'];
    const adSidebarTop = ads?.['home_sidebar_top'];
    const adSidebarBottom = ads?.['home_sidebar_bottom'];
    const shouldShowAd = (ad) => ad && ad.is_active;

    return (
        <>
            <Head title={pageTitle} />

            <div className="bg-background min-h-screen pb-12">
                <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-6 max-w-[1280px]">
                    
                    {shouldShowAd(adMobile) && (
                        <div className="lg:hidden mb-6 flex justify-center">
                            <AdSlot ad={adMobile} className="w-full max-w-[320px]" />
                        </div>
                    )}

                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
                        
                        <div className="lg:col-span-9 space-y-8">
                            {heroSlider && heroSlider.length > 0 ? (
                                <HeroSlider posts={heroSlider} />
                            ) : (
                                <div className="h-[450px] w-full rounded-xl bg-muted animate-pulse" />
                            )}

                            {subHeroPosts.length > 0 ? (
                                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                    {subHeroPosts.map((post) => (
                                        <GridItem key={post.id} post={post} />
                                    ))}
                                </div>
                            ) : (
                                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                    {[1, 2, 3, 4].map((i) => (
                                        <div key={i} className="aspect-[4/3] rounded-md bg-muted animate-pulse" />
                                    ))}
                                </div>
                            )}

                            <Separator className="my-6" />

                            <div className="space-y-6">
                                <HighlightedFeedTabs 
                                    initialLatestData={initialLatestData} 
                                    auth={auth} 
                                    tabCounts={tabCounts} 
                                />
                            </div>

                        </div>

                        <aside className="lg:col-span-3 hidden lg:block h-full ps-6 border-s border-border relative">
                            <div className="space-y-8 mb-8">
                                {shouldShowAd(adSidebarTop) && (
                                    <div className="flex justify-center bg-card border rounded-md p-4 shadow-sm">
                                        <div className="w-full">
                                            <p className="text-[10px] text-muted-foreground text-center mb-2 uppercase tracking-widest">
                                                {t('_advertisement', 'Advertisement')}
                                            </p>
                                            <AdSlot ad={adSidebarTop} className="w-full" />
                                        </div>
                                    </div>
                                )}

                                {(initialLoading || trendingPosts.length > 0) && (
                                    <div>
                                        <div className="flex items-center gap-2 mb-4">
                                            <TrendingUp className="w-5 h-5 text-primary" /> 
                                            <h3 className="font-bold text-lg">{t('_trending_now', 'Trending Now')}</h3>
                                        </div>
                                        <div className="space-y-4">
                                            {initialLoading ? (
                                                <>
                                                    {[1, 2, 3, 4, 5].map((i) => (
                                                        <div key={i} className="flex gap-3 pl-8 relative">
                                                            <Skeleton className="absolute left-0 top-0 w-6 h-6" />
                                                            <div className="w-full space-y-2">
                                                                <Skeleton className="h-4 w-full" />
                                                                <Skeleton className="h-3 w-16" />
                                                            </div>
                                                        </div>
                                                    ))}
                                                </>
                                            ) : (
                                                trendingPosts.map((post, index) => (
                                                    <div key={post.id} className="group relative ps-8">
                                                        <span className="absolute start-0 top-0 text-2xl font-bold text-muted-foreground/40 leading-none">
                                                            {index + 1}
                                                        </span>
                                                        <Link href={post.route_url} className="block" prefetch="true">
                                                            <h4 className="text-sm font-semibold leading-snug group-hover:text-primary transition-colors line-clamp-2"> 
                                                                {post.title}
                                                            </h4>
                                                            <div className="mt-1">
                                                                <TimeDisplay date={post.created_at} />
                                                            </div>
                                                        </Link>
                                                    </div>
                                                ))
                                            )}
                                        </div>
                                    </div>
                                )}
                            </div>

                            <div className="space-y-6 pb-6 pt-6 mt-auto bg-gradient-to-t from-background via-background to-background/95 backdrop-blur-sm border-t border-border/50">
                                {shouldShowAd(adSidebarBottom) && (
                                    <div className="bg-card border rounded-lg p-2 shadow-sm">
                                        <p className="text-[10px] text-muted-foreground text-center mb-1 uppercase tracking-widest">
                                            {t('_advertisement', 'Advertisement')}
                                        </p>
                                        <AdSlot ad={adSidebarBottom} className="w-full" />
                                    </div>
                                )}
                                <div className="-mt-6"> 
                                    <RightSidebarFooter />
                                </div>
                            </div>
                        </aside>
                    </div>
                </div>
            </div>
        </>
    );
}

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