import { defineStore } from 'pinia'
import { reactive, ref } from 'vue'
import type { ArticleReadingConfig, ArticleReadingTask } from '@/types/articleReading'
import type { ArticlePreviewStage } from '@/views/Editor/EnglishSpeaking/composables/useArticleReadingEngine'
import { buildArticleConfig, buildEmptyArticleConfig } from '@/views/Editor/EnglishSpeaking/preview/articleReadingModel'

/** 只持有文章朗读的表单状态，绝不混入话题讨论字段。 */
export const useArticleReadingStore = defineStore('articleReading', () => {
  const config = reactive<ArticleReadingConfig>(buildEmptyArticleConfig('五年级'))
  const activeConfigId = ref('')
  const openConfigSignal = ref(0)
  const resetSignal = ref(0)
  // 预览当前阶段（由 ArticleReadingPreview 同步）。CanvasTool 据此决定「重置预览」显不显示
  // —— 与话题讨论的 speakingStore.previewState 同一套做法：停在起始页时没什么可重置的。
  const previewStage = ref<ArticlePreviewStage>('ready')

  function replaceConfig(next: ArticleReadingConfig) {
    Object.assign(config, next)
  }

  function prefillFromTask(task: ArticleReadingTask, grade: string) {
    replaceConfig(buildArticleConfig(task, grade))
  }

  function resetConfigEmpty(grade: string) {
    replaceConfig(buildEmptyArticleConfig(grade))
  }

  function setActiveConfigId(configId: string) {
    activeConfigId.value = configId
  }

  function setPreviewStage(stage: ArticlePreviewStage) {
    previewStage.value = stage
  }

  function openConfigPanel(configId: string) {
    activeConfigId.value = configId
    openConfigSignal.value += 1
  }

  function requestResetPreview() {
    resetSignal.value += 1
  }

  return {
    config,
    activeConfigId,
    openConfigSignal,
    resetSignal,
    previewStage,
    replaceConfig,
    prefillFromTask,
    resetConfigEmpty,
    setActiveConfigId,
    setPreviewStage,
    openConfigPanel,
    requestResetPreview,
  }
})
