import { ISLANDER_UNLOCK_CODE } from '../easterEggCatalog'

export { ISLANDER_UNLOCK_CODE }
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
  }
  window.dispatchEvent(
    new CustomEvent(ISLANDER_UNLOCK_EVENT, { detail: { unlocked } }),
  )
}

export function isTypingTarget(target: EventTarget | null): boolean {
  if (!(target instanceof HTMLElement)) return false
  if (target.isContentEditable) return true
  const tag = target.tagName
  return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT'
}

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

/** Append one key to the rolling buffer; returns true when the unlock code matches. */
export function appendIslanderUnlockKey(buffer: string, key: string): { buffer: string; matched: boolean } {
  const code = ISLANDER_UNLOCK_CODE

  if (key === 'Backspace') {
    return { buffer: buffer.slice(0, -1), matched: false }
  }

  if (key.length !== 1) {
    return { buffer, matched: false }
  }

  const next = (buffer + key.toLowerCase()).slice(-code.length)
  return { buffer: next, matched: next === code }
}