import { reactive, watch } from 'vue'
import type { DisplaySettings } from '../types'

const STORAGE_KEY = 'search:displaySettings'

const defaults: DisplaySettings = {
  showAuthors: true,
  showAffiliation: true,
  showJournal: true,
  showPmid: true,
  showDoi: true,
  showAbstract: true,
  showStudyTypes: true,
  showTags: true,
  showCitedBy: true,
  showAiSummary: true,
  showActions: true,
  showBadges: true,
  showSummary: true,
  showPubmed: true,
}

function loadSettings(): DisplaySettings {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (raw) {
      const parsed = JSON.parse(raw)
      return { ...defaults, ...parsed }
    }
  } catch { /* ignore */ }
  return { ...defaults }
}

const settings = reactive<DisplaySettings>(loadSettings())

watch(
  () => ({ ...settings }),
  (val) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(val))
  },
  { deep: true },
)

export function useDisplaySettings() {
  return settings
}
