import { defineStore } from 'pinia'

export interface RecentNavigation {
  screenId: string
  path: string
  visitedAt: string
}

const STORAGE_KEY = 'ks.shell.screenPreference.v1'
const MAX_RECENTS = 10
const MAX_FAVORITES = 20

interface PersistedShape {
  favoriteScreenIds: string[]
  recents: RecentNavigation[]
  collapsedSectionModules: string[]
}

function readPersisted(): PersistedShape {
  if (typeof window === 'undefined') return { favoriteScreenIds: [], recents: [], collapsedSectionModules: [] }
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY)
    if (!raw) return { favoriteScreenIds: [], recents: [], collapsedSectionModules: [] }
    const parsed = JSON.parse(raw) as Partial<PersistedShape>
    return {
      favoriteScreenIds: Array.isArray(parsed.favoriteScreenIds) ? parsed.favoriteScreenIds.slice(0, MAX_FAVORITES) : [],
      recents: Array.isArray(parsed.recents) ? parsed.recents.slice(0, MAX_RECENTS) : [],
      collapsedSectionModules: Array.isArray(parsed.collapsedSectionModules)
        ? parsed.collapsedSectionModules.filter((module): module is string => typeof module === 'string')
        : []
    }
  } catch {
    return { favoriteScreenIds: [], recents: [], collapsedSectionModules: [] }
  }
}

export const useScreenPreferenceStore = defineStore('ks-screen-preference', {
  state: () => readPersisted(),
  actions: {
    persist() {
      if (typeof window === 'undefined') return
      window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ favoriteScreenIds: this.favoriteScreenIds, recents: this.recents, collapsedSectionModules: this.collapsedSectionModules }))
    },
    toggleFavorite(screenId: string) {
      const index = this.favoriteScreenIds.indexOf(screenId)
      if (index >= 0) this.favoriteScreenIds.splice(index, 1)
      else this.favoriteScreenIds = [screenId, ...this.favoriteScreenIds].slice(0, MAX_FAVORITES)
      this.persist()
    },
    isFavorite(screenId: string): boolean {
      return this.favoriteScreenIds.includes(screenId)
    },
    recordVisit(screenId: string, path: string) {
      const withoutCurrent = this.recents.filter(entry => entry.screenId !== screenId)
      this.recents = [{ screenId, path, visitedAt: new Date().toISOString() }, ...withoutCurrent].slice(0, MAX_RECENTS)
      this.persist()
    },
    toggleSection(module: string) {
      const index = this.collapsedSectionModules.indexOf(module)
      if (index >= 0) this.collapsedSectionModules.splice(index, 1)
      else this.collapsedSectionModules.push(module)
      this.persist()
    },
    isSectionCollapsed(module: string): boolean {
      return this.collapsedSectionModules.includes(module)
    }
  }
})
