const ADMIN_HASH = 'fa4fec80e90189885dc6a389324bd3beaae9be020641dd37c89f440bf9515e4d'
const SALT = 'protoc_salt_2025'
const STORAGE_KEY = 'admin_auth'
const SESSION_DURATION_MS = 24 * 60 * 60 * 1000 // 24 часа

interface AuthData {
  hash: string
  expiresAt: number
}

async function sha256(message: string): Promise<string> {
  const encoder = new TextEncoder()
  const data = encoder.encode(message)
  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 login(password: string): Promise<boolean> {
  const hash = await sha256(`${SALT}::${password}`)

  if (hash !== ADMIN_HASH) {
    return false
  }

  const authData: AuthData = {
    hash,
    expiresAt: Date.now() + SESSION_DURATION_MS,
  }

  localStorage.setItem(STORAGE_KEY, JSON.stringify(authData))
  return true
}

export function isAuthenticated(): boolean {
  const raw = localStorage.getItem(STORAGE_KEY)
  if (!raw) return false

  try {
    const authData: AuthData = JSON.parse(raw)

    if (authData.hash !== ADMIN_HASH) return false
    if (Date.now() > authData.expiresAt) {
      localStorage.removeItem(STORAGE_KEY)
      return false
    }

    return true
  } catch {
    localStorage.removeItem(STORAGE_KEY)
    return false
  }
}

export function logout(): void {
  localStorage.removeItem(STORAGE_KEY)
}
