const SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$|^[a-z0-9]{3}$/

function simpleHash(str) {
  let h = 0
  for (let i = 0; i < str.length; i++) {
    h = ((h << 5) - h) + str.charCodeAt(i)
    h |= 0
  }
  return Math.abs(h).toString(36)
}

export function slugify(title) {
  let base = String(title || '').trim().toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/[^a-z0-9-]/g, '')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '')

  if (base.length < 3) {
    base = 'article-' + simpleHash(String(title || Date.now()))
  }
  return base.slice(0, 58)
}

export function isValidSlug(slug) {
  return SLUG_PATTERN.test(String(slug || ''))
}
