import { TSurveyRunnable } from "./types";

export function randInt(min: number, max: number): number {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

export async function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export function getRelevantRunnables(
  surveyRunnables: TSurveyRunnable[],
  currentProject: string,
): TSurveyRunnable[] {
  const resultRunnables: TSurveyRunnable[] = [];

  for (const runnable of surveyRunnables) {
    if (!runnable.regex.test(currentProject)) {
      console.warn(
        `Runnable '${runnable.runnableName}' not loaded: Required Project regex`,
        runnable.regex,
        `not matched. Current project title '${currentProject}'`,
      );
      continue;
    }

    resultRunnables.push(runnable);
  }

  return resultRunnables;
}

export function scrollToElementWithOffset(el: HTMLElement, offsetPx = 40) {
  const rect = el.getBoundingClientRect();
  const scrollTop = window.scrollY || document.documentElement.scrollTop;
  const targetY = rect.top + scrollTop - offsetPx;

  window.scrollTo({
    top: targetY,
    behavior: "smooth",
  });
}

export function validateUpc(upc: string): boolean {
  if (!/^\d{12}$/.test(upc)) {
    return false;
  }

  const digits = upc.split("").map(Number);
  const checkDigit = digits.pop()!;

  const sum = digits.reduce((total, digit, idx) => {
    const weight = idx % 2 === 0 ? 3 : 1;
    return total + digit * weight;
  }, 0);

  const computedCheckDigit = (10 - (sum % 10)) % 10;

  return computedCheckDigit === checkDigit;
}

export function slugify(input: string): string {
  return input
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9\s-]/g, "")
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-")
    .replace(/^-|-$/g, "");
}
