// components/TimeAgo.tsx
import React from "react";
import { useSelector } from "react-redux";
import { RootState } from "../store";
import { DateTime } from "luxon";
import { formatDistanceToNow } from "date-fns";

type TimeAgoProps = {
  timestamp: string;
  className?: string;   
};

const TimeAgo: React.FC<TimeAgoProps> = ({ timestamp, className }) => {
  // Get user time zone from Redux
  const { homedata } = useSelector((state: RootState) => state.HomeContentReducer);
  const settings = homedata?.data?.settings;
  const userTimeZone = settings?.default_timezone || "UTC";

  // Format time ago
  if (!timestamp) return null;

  const zonedTime = DateTime.fromISO(timestamp.replace(" ", "T"), {
    zone: userTimeZone,
  });

  if (!zonedTime.isValid) return null;

  const nativeDate = new Date(zonedTime.toISO());
  const timeAgo = formatDistanceToNow(nativeDate, { addSuffix: true }).replace("about ", "");

  return <span className={className}>{timeAgo}</span>;
};

export default TimeAgo;
