import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { SpecSection, SpecFrontmatter } from '@/api/types'

export type EditorMode = 'source' | 'structured'

export interface ConflictState {
  serverContent: string
  serverSha: string
}

const DEFAULT_FRONTMATTER: SpecFrontmatter = {
  title: '',
  status: 'draft',
  owner: '',
  team: '',
  tags: [],
}

export const useEditorStore = defineStore('editor', () => {
  const mode = ref<EditorMode>('source')
  const filePath = ref('')
  const sha = ref('')
  const frontmatter = ref<SpecFrontmatter>({ ...DEFAULT_FRONTMATTER })
  const sourceContent = ref('')
  const sections = ref<SpecSection[]>([])
  const conflict = ref<ConflictState | null>(null)
  const saving = ref(false)
  const dirty = ref(false)
  const originalContent = ref('')

  const isNew = computed(() => !sha.value)

  function reset() {
    mode.value = 'source'
    filePath.value = ''
    sha.value = ''
    frontmatter.value = { ...DEFAULT_FRONTMATTER }
    sourceContent.value = ''
    sections.value = []
    conflict.value = null
    saving.value = false
    dirty.value = false
    originalContent.value = ''
  }

  function loadFile(content: string, fileSha: string, path: string) {
    sourceContent.value = content
    originalContent.value = content
    sha.value = fileSha
    filePath.value = path
    dirty.value = false
  }

  function markDirty() {
    dirty.value = true
  }

  function markSaved(newSha: string) {
    sha.value = newSha
    originalContent.value = sourceContent.value
    dirty.value = false
    saving.value = false
  }

  function setConflict(serverContent: string, serverSha: string) {
    conflict.value = { serverContent, serverSha }
  }

  function resolveConflict() {
    conflict.value = null
  }

  return {
    mode,
    filePath,
    sha,
    frontmatter,
    sourceContent,
    sections,
    conflict,
    saving,
    dirty,
    originalContent,
    isNew,
    reset,
    loadFile,
    markDirty,
    markSaved,
    setConflict,
    resolveConflict,
  }
})
