const STORAGE_KEY = 'platform_vehicle_display_settings_v2'

function safeParseJSON(value, fallback) {
  if (!value) return fallback
  try {
    return JSON.parse(value)
  } catch (e) {
    return fallback
  }
}

const useVehicleDisplayStore = defineStore('vehicleDisplay', {
  state: () => {
    const saved = typeof window !== 'undefined'
      ? safeParseJSON(window.localStorage?.getItem(STORAGE_KEY), {})
      : {}

    const enabledVehicleIds = saved && typeof saved === 'object' && saved.enabledVehicleIds && typeof saved.enabledVehicleIds === 'object'
      ? saved.enabledVehicleIds
      : {}

    const vehicleTypeOverrides = saved && typeof saved === 'object' && saved.vehicleTypeOverrides && typeof saved.vehicleTypeOverrides === 'object'
      ? saved.vehicleTypeOverrides
      : {}

    const vehicleRouteAssignments = saved && typeof saved === 'object' && saved.vehicleRouteAssignments && typeof saved.vehicleRouteAssignments === 'object'
      ? saved.vehicleRouteAssignments
      : {}

    return {
      enabledVehicleIds,
      vehicleTypeOverrides,
      vehicleRouteAssignments
    }
  },
  getters: {
    isVehicleEnabled: (state) => (vehicleId) => {
      if (!vehicleId) return false
      return state.enabledVehicleIds?.[vehicleId] === true
    },
    getVehicleTypeOverride: (state) => (vehicleId) => {
      if (!vehicleId) return undefined
      return state.vehicleTypeOverrides?.[vehicleId]
    },
    getVehicleRouteAssignment: (state) => (vehicleId) => {
      if (!vehicleId) return undefined
      return state.vehicleRouteAssignments?.[vehicleId]
    }
  },
  actions: {
    persist() {
      if (typeof window === 'undefined' || !window.localStorage) return
      window.localStorage.setItem(
        STORAGE_KEY,
        JSON.stringify({
          enabledVehicleIds: this.enabledVehicleIds || {},
          vehicleTypeOverrides: this.vehicleTypeOverrides || {},
          vehicleRouteAssignments: this.vehicleRouteAssignments || {}
        })
      )
    },
    setVehicleEnabled(vehicleId, enabled) {
      if (!vehicleId) return
      this.enabledVehicleIds = { ...(this.enabledVehicleIds || {}), [vehicleId]: enabled === true }
      this.persist()
    },
    setVehicleTypeOverride(vehicleId, vehicleType) {
      if (!vehicleId) return
      const next = { ...(this.vehicleTypeOverrides || {}) }
      if (!vehicleType) {
        delete next[vehicleId]
      } else {
        next[vehicleId] = vehicleType
      }
      this.vehicleTypeOverrides = next
      this.persist()
    },
    setVehicleRouteAssignment(vehicleId, routeName) {
      if (!vehicleId) return
      const next = { ...(this.vehicleRouteAssignments || {}) }
      const v = String(routeName || '').trim()
      if (!v) {
        delete next[vehicleId]
      } else {
        next[vehicleId] = v
      }
      this.vehicleRouteAssignments = next
      this.persist()
    },
    setBulk(vehicles) {
      const nextEnabled = {}
      const nextType = { ...(this.vehicleTypeOverrides || {}) }

      ;(vehicles || []).forEach((v) => {
        const id = v?.id
        if (!id) return
        if (v?.enabled === true) nextEnabled[id] = true
        if (v?.type !== undefined) {
          if (!v.type) delete nextType[id]
          else nextType[id] = v.type
        }
      })

      this.enabledVehicleIds = nextEnabled
      this.vehicleTypeOverrides = nextType
      this.persist()
    }
  }
})

export default useVehicleDisplayStore
