import React from 'react';
import { Link, usePage } from '@inertiajs/react';
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { AspectRatio } from "@/components/ui/aspect-ratio";
import { Rss } from 'lucide-react';
import useTranslation from '@/hooks/useTranslation';

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

    const placeholderImage = `https://ui-avatars.com/api/?name=${post.title.replace(/\s/g, '+')}&background=1a202c&color=fff&size=800&font-size=0.3`;
    
    const showFeedAuthor = post.rss_feed && post.rss_feed.show_author === false;
    const authorName = showFeedAuthor ? post.rss_feed.name : (post.user?.name || 'Unknown');

    const formatDate = (dateString) => {
        if (!dateString) return '';
        const safeLocale = locale ? locale.replace('_', '-') : 'en-US';
        return new Intl.DateTimeFormat(safeLocale, { 
            year: 'numeric', 
            month: 'short', 
            day: 'numeric' 
        }).format(new Date(dateString));
    };

    return (
        <Card className="overflow-hidden group transition-all duration-300 shadow-sm hover:shadow-xl">
            <Link href={post.route_url}>
                <AspectRatio ratio={16 / 9} className="bg-muted">
                    <img
                        src={post.image_path || placeholderImage}
                        alt={post.title}
                        className="object-cover w-full h-full"
                    />
                </AspectRatio>
                <CardContent className="p-4 space-y-2">
                    {post.category && (
                        <Badge variant="outline">{post.category.name}</Badge>
                    )}
                    <h3 className="text-lg font-bold leading-tight group-hover:text-primary transition-colors line-clamp-2">
                        {post.title}
                    </h3>
                    <div className="flex items-center text-xs text-muted-foreground pt-2 gap-1.5">
                        
                        {showFeedAuthor && post.rss_feed?.feed_logo ? (
                            <img src={post.rss_feed.feed_logo} className="w-4 h-4 rounded-full" />
                        ) : showFeedAuthor ? (
                            <Rss className="w-3 h-3" />
                        ) : null}

                        <span>{t('_by', 'By')} {authorName}</span>
                        <span className="mx-1">•</span>
                        <span>{formatDate(post.created_at)}</span>
                    </div>
                </CardContent>
            </Link>
        </Card>
    );
}