'use client';

const DEFAULT_CLASS = 'text-xs text-neutral-400 dark:text-gray-500 font-ibm-plex-mono';

function getRelativeTime(date) {
    if (!date) return null;
    const d = date instanceof Date ? date : new Date(date);
    if (isNaN(d.getTime())) return null;

    const rtf = new Intl.RelativeTimeFormat('fr', { numeric: 'auto' });
    const diffMs = d.getTime() - Date.now();
    const diffSec = Math.round(diffMs / 1000);
    const absMin = Math.abs(Math.round(diffSec / 60));
    const absH = Math.abs(Math.round(diffSec / 3600));
    const absDays = Math.abs(Math.round(diffSec / 86400));

    if (Math.abs(diffSec) < 60) return rtf.format(diffSec, 'second');
    if (absMin < 60) return rtf.format(Math.round(diffSec / 60), 'minute');
    if (absH < 24) return rtf.format(Math.round(diffSec / 3600), 'hour');
    if (absDays < 7) return rtf.format(Math.round(diffSec / 86400), 'day');
    if (absDays < 30) return rtf.format(Math.round(diffSec / 604800), 'week');
    if (absDays < 365) return rtf.format(Math.round(diffSec / 2592000), 'month');
    return rtf.format(Math.round(diffSec / 31536000), 'year');
}

const RelativeDate = ({ date, className = DEFAULT_CLASS, ...props }) => {
    const text = getRelativeTime(date);
    if (!text) return null;

    const d = date instanceof Date ? date : new Date(date);

    return (
        <time dateTime={d.toISOString()} className={className} title={d.toLocaleString('fr-FR')} {...props}>
            {text}
        </time>
    );
};

export default RelativeDate;
