// Shared utility functions

// Escape HTML to prevent XSS
export function escapeHtml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;')
}

// Escape for HTML attributes (same as escapeHtml)
export function escapeAttr(text: string): string {
  return escapeHtml(text)
}

// Format date as yyyy/mm/dd
export function formatDate(dateStr: string): string {
  const d = new Date(dateStr)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}/${month}/${day}`
}

// Format date/time as mm/dd hh:mm
export function formatDateTime(dateStr: string): string {
  const d = new Date(dateStr)
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const min = String(d.getMinutes()).padStart(2, '0')
  return `${month}/${day} ${hour}:${min}`
}

// Format date in ja-JP locale
export function formatDateJa(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('ja-JP', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  })
}

// Get current language preference
export function getLang(): string {
  return localStorage.getItem('preferred-lang') || 'ja'
}

// Get localized text from a {ja, en} object
export function getLocalizedText(obj: { ja: string; en: string } | undefined): string {
  if (!obj) return ''
  const lang = getLang()
  return obj[lang as 'ja' | 'en'] || obj.ja || obj.en || ''
}

// Get translated content from a record with translations field
export function getTranslatedContent(
  originalText: string,
  translations: Record<string, { content: string | { text: string } }> | undefined,
  originalLang: string = 'ja'
): string {
  const currentLang = getLang()
  if (translations && currentLang !== originalLang && translations[currentLang]) {
    const translated = translations[currentLang].content
    if (typeof translated === 'string') return translated
    if (translated && typeof translated === 'object' && 'text' in translated) return translated.text
  }
  return originalText
}

// Extract rkey from AT URI
export function getRkeyFromUri(uri: string): string {
  return uri.split('/').pop() || ''
}

// Extract authority (DID) from AT URI
export function getAuthorityFromUri(uri: string): string {
  return uri.replace('at://', '').split('/')[0]
}

// Async button helper: find button by ID, add click handler with loading state
export function setupAsyncButton(
  id: string,
  loadingText: string,
  handler: (btn: HTMLButtonElement) => Promise<void>
): void {
  const btn = document.getElementById(id) as HTMLButtonElement | null
  if (!btn) return
  const originalText = btn.textContent || ''
  btn.addEventListener('click', async () => {
    btn.textContent = loadingText
    btn.disabled = true
    try {
      await handler(btn)
    } catch (err) {
      console.error(`${id} failed:`, err)
      alert(`Failed: ${err}`)
      btn.textContent = originalText
      btn.disabled = false
    }
  })
}
