/**
 * Reading progress math (pure): 0 at the start of the tracked area, 1 when its end reaches the bottom of the
 * viewport. Without a target the tracked area is the whole document.
 */
export interface ProgressInput {
  scrollY: number;
  viewport: number;
  /** Document y of the tracked area's top (0 for the page). */
  top: number;
  /** Height of the tracked area (the document height for the page). */
  height: number;
}

export function readingProgress({ scrollY, viewport, top, height }: ProgressInput): number {
  const start = top;
  const end = top + height - viewport;
  if (end <= start) return scrollY >= start ? 1 : 0; // shorter than the viewport
  const p = (scrollY - start) / (end - start);
  return Math.min(1, Math.max(0, p));
}

/** Whole percent for aria-valuenow / the label. */
export function percent(p: number): number {
  return Math.round(Math.min(1, Math.max(0, p)) * 100);
}
