import { defaultIslanderPosition, ISLANDER_POSITION_KEY } from './useIslanderPosition'

export const ISLANDER_UNLOCK_KEY = 'haixun.islander.unlocked'
export const ISLANDER_UNLOCK_EVENT = 'haixun.islander-unlock-changed'

export function readIslanderUnlocked(): boolean {
  try {
    return sessionStorage.getItem(ISLANDER_UNLOCK_KEY) === '1'
  } catch {
    return false
  }
}

export function writeIslanderUnlocked(unlocked: boolean) {
  try {
    sessionStorage.setItem(ISLANDER_UNLOCK_KEY, unlocked ? '1' : '0')
  } catch {
    // ignore
  }

  if (unlocked) {
    try {
      localStorage.setItem(ISLANDER_POSITION_KEY, JSON.stringify(defaultIslanderPosition()))
    } catch {
      // ignore
    }
  }

  window.dispatchEvent(
    new CustomEvent(ISLANDER_UNLOCK_EVENT, { detail: { unlocked } }),
  )
}

export function toggleIslanderUnlocked(): boolean {
  const next = !readIslanderUnlocked()
  writeIslanderUnlocked(next)
  return next
}

export function subscribeIslanderUnlocked(onStoreChange: () => void) {
  window.addEventListener(ISLANDER_UNLOCK_EVENT, onStoreChange)
  return () => window.removeEventListener(ISLANDER_UNLOCK_EVENT, onStoreChange)
}