import { shuffledDeck } from "./engine";

/** 32-bit string hash (cyrb53-lite) so any text works as a seed. */
export function hashSeed(seed: string): number {
  let hash = 2166136261;
  for (let index = 0; index < seed.length; index += 1) {
    hash ^= seed.charCodeAt(index);
    hash = Math.imul(hash, 16777619);
  }
  return hash >>> 0;
}

/** Deterministic PRNG; the same seed always yields the same stream. */
export function mulberry32(seed: number): () => number {
  let state = seed >>> 0;
  return () => {
    state = (state + 0x6d2b79f5) >>> 0;
    let value = Math.imul(state ^ (state >>> 15), 1 | state);
    value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value;
    return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
  };
}

export function deckOrderFromSeed(seed: string): number[] {
  return shuffledDeck(mulberry32(hashSeed(seed)));
}

/** A fresh shareable seed, e.g. "k3f9qa". */
export function randomSeed(): string {
  return Math.floor(Math.random() * 36 ** 6).toString(36).padStart(6, "0");
}

export function normalizeSeed(raw: string): string {
  return raw.trim().slice(0, 32);
}
