// Shared password hash (SHA-256 of the password)
// To change the password:
//   1. Run: printf 'newpassword' | sha256sum
//   2. Replace VALID_HASH below with the output
//
// Current password: higgy2024
const VALID_HASH =
  "4e58a7a86830a9ae2aae7fc8253c290a4773b1dbbc4e71ffa3eb4afbec3acb25"

const STORAGE_KEY = "higgys_auth"

export async function hashPassword(password: string): Promise<string> {
  const encoder = new TextEncoder()
  const data = encoder.encode(password)
  const hashBuffer = await crypto.subtle.digest("SHA-256", data)
  const hashArray = Array.from(new Uint8Array(hashBuffer))
  return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("")
}

export async function checkPassword(password: string): Promise<boolean> {
  const hash = await hashPassword(password)
  return hash === VALID_HASH
}

export function isAuthenticated(): boolean {
  if (typeof window === "undefined") return false
  return localStorage.getItem(STORAGE_KEY) === "true"
}

export function setAuthenticated(value: boolean) {
  if (typeof window === "undefined") return
  if (value) {
    localStorage.setItem(STORAGE_KEY, "true")
  } else {
    localStorage.removeItem(STORAGE_KEY)
  }
}
