export type PracticeResult = 'pending' | 'correct' | 'wrong'

const IDS_KEY = 'wordloop_practice_word_ids'
const GRAPH_IDS_KEY = 'wordloop_practice_graph_ids'
const RESULTS_KEY = 'wordloop_graph_practice_results'

/** @param graphNodeIds 图上展示的节点（可多于待练词，例如单词练习时展示关联子图） */
export function startGraphPractice(wordIds: string[], graphNodeIds?: string[]) {
  sessionStorage.setItem(IDS_KEY, JSON.stringify(wordIds))
  const display = graphNodeIds?.length ? graphNodeIds : wordIds
  sessionStorage.setItem(GRAPH_IDS_KEY, JSON.stringify(display))
  const results: Record<string, PracticeResult> = {}
  for (const id of wordIds) results[id] = 'pending'
  sessionStorage.setItem(RESULTS_KEY, JSON.stringify(results))
}

export function getGraphPracticeDisplayIds(): string[] {
  try {
    const raw = sessionStorage.getItem(GRAPH_IDS_KEY)
    if (!raw) return getGraphPracticeWordIds()
    const ids = JSON.parse(raw) as string[]
    return Array.isArray(ids) && ids.length ? ids : getGraphPracticeWordIds()
  } catch {
    return getGraphPracticeWordIds()
  }
}

export function getGraphPracticeWordIds(): string[] {
  try {
    const raw = sessionStorage.getItem(IDS_KEY)
    if (!raw) return []
    const ids = JSON.parse(raw) as string[]
    return Array.isArray(ids) ? ids : []
  } catch {
    return []
  }
}

export function loadPracticeResults(): Record<string, PracticeResult> {
  try {
    const raw = sessionStorage.getItem(RESULTS_KEY)
    if (!raw) return {}
    return JSON.parse(raw) as Record<string, PracticeResult>
  } catch {
    return {}
  }
}

export function savePracticeResult(wordId: string, result: 'correct' | 'wrong') {
  const all = loadPracticeResults()
  all[wordId] = result
  sessionStorage.setItem(RESULTS_KEY, JSON.stringify(all))
}

export function isPracticeSessionComplete(
  wordIds: string[],
  results: Record<string, PracticeResult>
): boolean {
  if (!wordIds.length) return false
  return wordIds.every((id) => {
    const r = results[id]
    return r === 'correct' || r === 'wrong'
  })
}

export function clearGraphPracticeSession() {
  sessionStorage.removeItem(IDS_KEY)
  sessionStorage.removeItem(GRAPH_IDS_KEY)
  sessionStorage.removeItem(RESULTS_KEY)
}
