import { m } from '@paraglide/messages';

export function jsonSupport(jsonSTR: string) {
  try {
    const data = JSON.parse(jsonSTR);

    return JSON.stringify(data, undefined, 2);
  } catch {
    return jsonSTR;
  }
}

type AnyRecord = Record<string, unknown>;

export function extractDiffObjects<T extends AnyRecord>(
  a: T,
  b: T,
): [Partial<T>, Partial<T>] {
  return (Object.keys(a) as (keyof T)[]).reduce(
    ([accA, accB], key) => {
      if (a[key] !== b[key]) {
        accA[key] = a[key];
        accB[key] = b[key];
      }
      return [accA, accB];
    },
    [{}, {}] as [Partial<T>, Partial<T>],
  );
}

export function slugify(text: string) {
  return text
    .toLowerCase()
    .normalize('NFD') // tách chữ và dấu
    .replace(/[\u0300-\u036f]/g, '') // xóa dấu
    .replace(/đ/g, 'd') // riêng chữ đ
    .replace(/[^a-z0-9\s-]/g, '') // xóa ký tự đặc biệt
    .trim()
    .replace(/\s+/g, '-');
}

const UNITS = [
  { limit: 60, divisor: 1, key: 'common_time_ago_second' },
  { limit: 60, divisor: 60, key: 'common_time_ago_minute' },
  { limit: 24, divisor: 60 * 60, key: 'common_time_ago_hour' },
  { limit: 30, divisor: 60 * 60 * 24, key: 'common_time_ago_day' },
  { limit: 12, divisor: 60 * 60 * 24 * 30, key: 'common_time_ago_month' },
  { limit: Infinity, divisor: 60 * 60 * 24 * 365, key: 'common_time_ago_year' },
] as const;

export function formatTimeAgo(input: Date | string): string {
  const date = typeof input === 'string' ? new Date(input) : input;
  const diffSec = Math.floor((Date.now() - date.getTime()) / 1000);

  if (diffSec < 10) return m.common_time_ago_second({ value: 1 });

  for (const unit of UNITS) {
    const value = Math.floor(diffSec / unit.divisor);
    if (value < unit.limit) {
      return m[unit.key]({ value });
    }
  }

  return '';
}
