import React, { useState, useEffect, useRef } from 'react';
import { Link, usePage } from '@inertiajs/react';
import Autoplay from "embla-carousel-autoplay";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
} from "@/Components/ui/carousel";
import { Badge } from '@/Components/ui/badge';
import { ChevronLeft, ChevronRight, Clock } from 'lucide-react';
import { cn } from "@/lib/utils";
import useTranslation from '@/hooks/useTranslation';

export default function HeroSlider({ posts }) {
    const { t } = useTranslation();
    const { locale } = usePage().props;

    const [api, setApi] = useState(null);
    const [current, setCurrent] = useState(0);
    const [count, setCount] = useState(0);

    const plugin = useRef(
        Autoplay({ delay: 6000, stopOnInteraction: true })
    );

    const getPlaceholder = (title) => {
        return `https://ui-avatars.com/api/?name=${encodeURIComponent(title)}&background=random&color=fff&size=1024&font-size=0.3`;
    };

    useEffect(() => {
        if (!api) return;
        setCount(api.scrollSnapList().length);
        setCurrent(api.selectedScrollSnap());
        api.on("select", () => {
            setCurrent(api.selectedScrollSnap());
        });
    }, [api]);

    const getTimeAgo = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        const safeLocale = locale ? locale.replace('_', '-') : 'en-US';
        const rtf = new Intl.RelativeTimeFormat(safeLocale, { numeric: 'auto', style: 'short' });
        const diffInSeconds = Math.floor((new Date() - date) / 1000);

        if (diffInSeconds < 60) return t('_just_now', 'Just now');
        const minutes = Math.floor(diffInSeconds / 60);
        const hours = Math.floor(minutes / 60);
        const days = Math.floor(hours / 24);

        if (minutes < 60) return rtf.format(-minutes, 'minute');
        if (hours < 24) return rtf.format(-hours, 'hour');
        if (days < 7) return rtf.format(-days, 'day');
        return new Intl.DateTimeFormat(safeLocale, { month: 'short', day: 'numeric', year: 'numeric' }).format(date);
    };

    if (!posts || posts.length === 0) return null;

    return (
        <div className="relative w-full rounded-xl overflow-hidden border border-border bg-card shadow-md">
            <Carousel
                setApi={setApi}
                plugins={[plugin.current]}
                className="w-full"
                opts={{ loop: true }}
            >
                <CarouselContent>
                    {posts.map((post) => (
                        <CarouselItem key={post.id} className="relative h-[350px] md:h-[480px] w-full">
                            <Link href={post.route_url} className="absolute inset-0 block">
                                <img 
                                    src={post.image_path || getPlaceholder(post.title)} 
                                    alt={post.title}
                                    className="w-full h-full object-cover transition-none" 
                                />
                                <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/30 to-transparent" />
                            </Link>

                            <div className="absolute inset-0 flex flex-col justify-end p-6 md:p-10 pb-20 md:pb-24 pointer-events-none">
                                <div className="max-w-3xl space-y-3 pointer-events-auto">
                                    
                                    {post.category && (
                                        <Badge variant="secondary" className="bg-primary text-primary-foreground border-none px-2.5 py-0.5 text-[10px] font-bold uppercase tracking-wider rounded-md">
                                            {post.category.name}
                                        </Badge>
                                    )}

                                    <Link href={post.route_url}>
                                        <h2 className="text-xl md:text-3xl font-bold text-white leading-tight font-serif hover:text-white/90 transition-colors drop-shadow-sm">
                                            {post.title}
                                        </h2>
                                    </Link>
                                </div>
                            </div>
                        </CarouselItem>
                    ))}
                </CarouselContent>
            </Carousel>

            {/* --- NEW MODERN BOTTOM CONTROL BAR --- */}
            <div className="absolute bottom-5 left-6 right-6 flex items-center justify-between z-20 pointer-events-none">
                
                {/* Time Display (Bottom Left) */}
                <div className="flex items-center gap-1.5 text-white/90 text-[11px] font-medium backdrop-blur-md bg-black/30 px-3 py-1.5 rounded-md border border-white/10 shadow-sm animate-in fade-in slide-in-from-left-2 duration-500 pointer-events-auto">
                    <Clock className="w-3.5 h-3.5" />
                    {getTimeAgo(posts[current]?.created_at)}
                </div>

                {/* Navigation (Bottom Right) */}
                <div className="flex items-center gap-2 pointer-events-auto">
                    <button 
                        onClick={() => api?.scrollPrev()} 
                        className="h-8 w-8 rounded-md bg-white/10 hover:bg-white/20 backdrop-blur-md text-white flex items-center justify-center transition-all active:scale-95 border border-white/10 rtl:rotate-180"
                    >
                        <ChevronLeft className="w-4 h-4" />
                    </button>

                    <div className="flex gap-1.5 px-1">
                        {Array.from({ length: count }).map((_, index) => (
                            <div
                                key={index}
                                className={cn(
                                    "h-1 rounded-full transition-all duration-300",
                                    current === index ? "w-6 bg-white" : "w-1.5 bg-white/30"
                                )}
                            />
                        ))}
                    </div>

                    <button 
                        onClick={() => api?.scrollNext()} 
                        className="h-8 w-8 rounded-md bg-white/10 hover:bg-white/20 backdrop-blur-md text-white flex items-center justify-center transition-all active:scale-95 border border-white/10 rtl:rotate-180"
                    >
                        <ChevronRight className="w-4 h-4" />
                    </button>
                </div>
            </div>
        </div>
    );
}