type BadgingNavigator = Navigator & {
  setAppBadge?: (contents?: number) => Promise<void> | void;
  clearAppBadge?: () => Promise<void> | void;
};

function getNavigator(): BadgingNavigator | null {
  if (typeof navigator === 'undefined') {
    return null;
  }
  return navigator as BadgingNavigator;
}

export function supportsBadging(): boolean {
  const nav = getNavigator();
  return Boolean(nav && (typeof nav.setAppBadge === 'function' || typeof nav.clearAppBadge === 'function'));
}

export async function updateAppBadge(count: number): Promise<void> {
  const nav = getNavigator();
  if (!nav) {
    return;
  }

  const safeCount = Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0;
  if (!supportsBadging()) {
    return;
  }

  try {
    if (safeCount > 0 && nav.setAppBadge) {
      await nav.setAppBadge(safeCount);
      return;
    }

    if (nav.clearAppBadge) {
      await nav.clearAppBadge();
      return;
    }

    if (nav.setAppBadge) {
      await nav.setAppBadge(0);
    }
  } catch (error) {
    console.warn('Updating app badge failed', error);
  }
}
