// PostCard.jsx
import React from 'react';
import { Button } from '@progress/kendo-react-buttons';
import { Card, CardImage, CardBody } from '@progress/kendo-react-layout';

// Import all header images so Vite processes them
const headerImages = import.meta.glob('../../assets/header/*', { eager: true });

const PostCard = ({ post, onEdit }) => {
    const dataPath = post.header.image;
    const imageUrl = headerImages[`../../${dataPath}`]?.default || dataPath;

    const formatDate = (utcString) => {
        if (!utcString) return '';
        
        const date = new Date(utcString);
        
        const dateOptions = {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: 'numeric',
            minute: '2-digit',
            hour12: true,
            timeZoneName: undefined
        };

        const formattedDate = date.toLocaleDateString(undefined, dateOptions);

        // Split formatted date to check if time component exists
        const parts = formattedDate.split(',');
        if (parts.length > 1) {
            // Reconstruct with separate date and time formatting for consistency
            const timePart = date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit', hour12: true });
            const datePart = date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
            return `${datePart}, ${timePart}`;
        }
        
        return formattedDate;
    };

    return (
        <Card key={post.slug} style={{ width: 'calc(100% - 50px)', textAlign: 'center', display: 'flex' }}>
            
            {/* 1. Thumbnail Image */}
                <CardImage 
                    src={imageUrl} 
                    alt={post.title} 
                    style={{ width: '100%', height: '100px', objectFit: 'cover' }} 
                />

            {/* 2. Title, Date, and Button Container */}
            <CardBody style={{ flexGrow: 1, padding: '10px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                
                {/* Title Link */}
                <div style={{ marginBottom: '5px' }}>
                    <a className="k-link" href={post.canonical_url} target="_blank" rel="noreferrer" style={{ fontWeight: 'bold' }}>
                        {post.title}
                    </a>
                </div>
                
                {/* Date and Edit Button */}
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: '0.85em' }}>
                    <span>{formatDate(post.date)}</span>
                    <Button 
                        look="flat" 
                        themeColor="primary" 
                        onClick={() => onEdit(post.slug)}
                    >
                        Edit
                    </Button>
                </div>

            </CardBody>
        </Card>
    );
};

export default PostCard;