'use client'
/**
 * Assessment-domain i18n helpers.
 *
 * Lives in the assessment module (not under `lib/i18n/`) because every helper
 * here is assessment-shape-specific. Generic, cross-domain locale plumbing
 * stays in `lib/i18n/`. See ADR 015 layer map.
 */

import { useState, useEffect } from 'react'
import type { AssessmentLang, AssessmentMainCategory, AssessmentSubCategory, AssessmentQuestion } from '@/lib/assessment-types'

const STORAGE_KEY = 'assessment_lang'

export function useLang(): [AssessmentLang, (l: AssessmentLang) => void] {
  const [lang, setLangState] = useState<AssessmentLang>('de')

  useEffect(() => {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored === 'de' || stored === 'en') setLangState(stored)
  }, [])

  function setLang(l: AssessmentLang) {
    setLangState(l)
    localStorage.setItem(STORAGE_KEY, l)
  }

  return [lang, setLang]
}

/** Generic helper: returns item[field + '_' + lang] if non-null, else item[field] */
export function getAssessmentText(
  item: Record<string, string | null | undefined>,
  field: string,
  lang: AssessmentLang,
): string {
  const localized = item[`${field}_${lang}`]
  if (localized != null && localized !== '') return localized
  return item[field] ?? ''
}

export function mainCatLabel(cat: AssessmentMainCategory, lang: AssessmentLang): string {
  return getAssessmentText(cat as unknown as Record<string, string | null | undefined>, 'label', lang)
}

export function subCatLabel(cat: AssessmentSubCategory, lang: AssessmentLang): string {
  return getAssessmentText(cat as unknown as Record<string, string | null | undefined>, 'label', lang)
}

export function questionText(q: AssessmentQuestion, lang: AssessmentLang): string {
  return getAssessmentText(q as unknown as Record<string, string | null | undefined>, 'question_text', lang)
}

/**
 * Returns answer texts for ratings 1–4.
 * Value is null when both the localized and base columns are null/empty
 * (e.g. CORP questions with only 2 criteria levels).
 * The UI should skip rendering the button for null entries.
 */
export function answerTexts(q: AssessmentQuestion, lang: AssessmentLang): Record<number, string | null> {
  const row = q as unknown as Record<string, string | null | undefined>
  function get(n: number): string | null {
    const localized = row[`answer_text_${n}_${lang}`]
    if (localized != null && localized !== '') return localized
    const base = row[`answer_text_${n}`]
    if (base != null && base !== '') return base
    return null
  }
  return { 1: get(1), 2: get(2), 3: get(3), 4: get(4) }
}
