// frontend/src/lib/melodyUtils.js
// Pure utility functions for melody pages. Ported from _archive/melodies/melodyUtils.js.

export function formatDuration(seconds) {
  if (seconds === 0) return 'Single Run'
  const min = Math.floor(seconds / 60)
  const sec = seconds % 60
  return `${min}:${sec.toString().padStart(2, '0')}`
}

export function parseLocalizedString(value) {
  if (!value) return {}
  if (typeof value === 'object') return value
  try {
    const parsed = JSON.parse(value)
    if (typeof parsed === 'object' && parsed !== null) return parsed
  } catch {
    return { en: value }
  }
  return {}
}

export function serializeLocalizedString(dict) {
  if (!dict || typeof dict !== 'object') return ''
  return JSON.stringify(dict)
}

export function getLocalizedValue(value, lang, fallback = '') {
  const dict = parseLocalizedString(value)
  return dict[lang] || dict['en'] || Object.values(dict)[0] || fallback
}

export function normalizeColor(val) {
  if (!val) return '#888888'
  if (val.startsWith('0x') || val.startsWith('0X')) {
    const hex = val.slice(2)
    return `#${hex.length === 8 ? hex.slice(2) : hex}`
  }
  if (val.startsWith('#')) return val
  return `#${val}`
}

export function getLanguageName(code) {
  return LANGUAGE_MASTER_LIST.find((l) => l.code === code)?.name ?? code.toUpperCase()
}

export const LANGUAGE_MASTER_LIST = [
  { code: 'en', name: 'English' },
  { code: 'el', name: 'Greek' },
  { code: 'sr', name: 'Serbian' },
  { code: 'bg', name: 'Bulgarian' },
  { code: 'ro', name: 'Romanian' },
  { code: 'ru', name: 'Russian' },
  { code: 'uk', name: 'Ukrainian' },
  { code: 'ka', name: 'Georgian' },
  { code: 'ar', name: 'Arabic' },
  { code: 'de', name: 'German' },
  { code: 'fr', name: 'French' },
  { code: 'es', name: 'Spanish' },
  { code: 'it', name: 'Italian' },
  { code: 'pt', name: 'Portuguese' },
  { code: 'nl', name: 'Dutch' },
  { code: 'pl', name: 'Polish' },
  { code: 'cs', name: 'Czech' },
  { code: 'sk', name: 'Slovak' },
  { code: 'hu', name: 'Hungarian' },
  { code: 'hr', name: 'Croatian' },
  { code: 'sl', name: 'Slovenian' },
  { code: 'mk', name: 'Macedonian' },
  { code: 'sq', name: 'Albanian' },
  { code: 'tr', name: 'Turkish' },
  { code: 'ja', name: 'Japanese' },
  { code: 'zh', name: 'Chinese' },
  { code: 'ko', name: 'Korean' },
  { code: 'hi', name: 'Hindi' },
  { code: 'he', name: 'Hebrew' },
  { code: 'fi', name: 'Finnish' },
  { code: 'sv', name: 'Swedish' },
  { code: 'da', name: 'Danish' },
  { code: 'no', name: 'Norwegian' },
]
