import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'TimeAgo',
  standalone: true
})
export class TimeAgoPipe implements PipeTransform {
  transform(value: Date | string | number | null, short?: boolean): string {
    if (!value) {
      return '';
    }

    const date = new Date(value);
    const now = new Date();

    const seconds = Math.floor((now.getTime() - date.getTime()) / 1000);

    if (seconds < 60) {
      return 'just now';
    }

    let returnText = 'ago';

    const allMinutes = Math.floor(seconds / 60);
    const minutes = allMinutes % 60;
    if (short) {
      returnText = `${minutes}m ${returnText}`
    } else {
      returnText = `${minutes} ${minutes === 1 ? 'minute' : 'minutes'} ${returnText}`
    }
    if (allMinutes < 60) {
      return returnText
    }


    const allHours = Math.floor(allMinutes / 60);
    const hours = allHours % 24;
    if (short) {
      returnText = `${hours}h ${returnText}`
    } else {
      returnText = `${hours} ${hours === 1 ? 'hour' : 'hours'} ${returnText}`
    }
    if (allHours < 24) {
      return returnText
    }

    const days = Math.floor(allHours / 24);
    if (short) {
      returnText = `${days}d ${returnText}`
    } else {
      returnText = `${days} ${days === 1 ? 'day' : 'days'} ${returnText}`
    }
    return returnText
  }
}
