export const throttle = (
  func: (...args: unknown[]) => void,
  limit: number,
): ((...args: unknown[]) => void) => {
  let lastFunc: ReturnType<typeof setTimeout> | null = null;
  let lastRan: number | null = null;

  return function (this: unknown, ...args: unknown[]) {
    if (lastRan === null) {
      func.apply(this, args);
      lastRan = Date.now();
    } else {
      if (lastFunc !== null) {
        clearTimeout(lastFunc);
      }
      lastFunc = setTimeout(
        () => {
          if (Date.now() - (lastRan as number) >= limit) {
            func.apply(this, args);
            lastRan = Date.now();
          }
        },
        limit - (Date.now() - (lastRan as number)),
      );
    }
  };
};

export function debounce<T extends (...args: unknown[]) => unknown>(
  func: T,
  wait: number,
): (...args: Parameters<T>) => void {
  let timeout: ReturnType<typeof setTimeout> | null = null;

  return function (...args: Parameters<T>): void {
    if (timeout) {
      clearTimeout(timeout);
    }

    timeout = setTimeout(() => {
      func(...args);
    }, wait);
  };
}

export function uid(): string {
  return (Date.now() + Math.floor(Math.random() * 1000)).toString();
}

export function getInitials(
  name: string | null | undefined,
  count?: number,
): string {
  if (!name || typeof name !== 'string') {
    return '';
  }

  const initials = name
    .split(' ')
    .filter(Boolean)
    .map((part) => part[0].toUpperCase());

  return count && count > 0
    ? initials.slice(0, count).join('')
    : initials.join('');
}

export function toAbsoluteUrl(pathname: string): string {
  const baseUrl = import.meta.env.VITE_BASE_PATH;

  if (baseUrl && baseUrl !== '/') {
    return import.meta.env.VITE_BASE_PATH + pathname;
  } else {
    return pathname;
  }
}

/**
 * The language and timezone dates are shown in: the server's (the user's, else the
 * organization's), kept current by the i18n provider.
 */
const display: { locale?: string; timeZone?: string } = {};

export function setDisplayLocalization(locale?: string, timeZone?: string) {
  display.locale = locale?.replace('_', '-');
  display.timeZone = timeZone;
}

/**
 * A date from the server. Database timestamps without a zone ("2026-11-11 07:55:00") are stored in the
 * application's timezone, UTC, so they are read as UTC rather than as the browser's local time.
 */
function toDate(input: Date | string | number): Date {
  if (
    typeof input === 'string' &&
    /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(input)
  ) {
    return new Date(`${input.replace(' ', 'T')}Z`);
  }

  return new Date(input);
}

export function timeAgo(date: Date | string): string {
  const inputDate = toDate(date);
  const seconds = Math.round((inputDate.getTime() - Date.now()) / 1000);
  const format = new Intl.RelativeTimeFormat(display.locale ?? 'en-US', {
    numeric: 'auto',
  });
  const units: [Intl.RelativeTimeFormatUnit, number][] = [
    ['year', 31536000],
    ['month', 2592000],
    ['week', 604800],
    ['day', 86400],
    ['hour', 3600],
    ['minute', 60],
  ];

  for (const [unit, size] of units) {
    if (Math.abs(seconds) >= size) {
      return format.format(Math.trunc(seconds / size), unit);
    }
  }

  return format.format(0, 'second');
}

export function formatDate(input: Date | string | number): string {
  return toDate(input).toLocaleDateString(display.locale ?? 'en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
    timeZone: display.timeZone,
  });
}

export function formatDateTime(input: Date | string | number): string {
  return toDate(input).toLocaleString(display.locale ?? 'en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    timeZone: display.timeZone,
  });
}
