const STORAGE_KEY = 'skinbase:hidden_homepage_announcements'

function readHiddenAnnouncements() {
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY)
    const parsed = raw ? JSON.parse(raw) : {}
    return parsed && typeof parsed === 'object' ? parsed : {}
  } catch {
    return {}
  }
}

function writeHiddenAnnouncements(payload) {
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(payload))
}

function initAnnouncement() {
  const announcement = document.querySelector('[data-home-announcement]')
  const restoreButton = document.querySelector('[data-home-announcement-restore]')

  if (!announcement || !restoreButton) {
    return
  }

  const announcementId = announcement.getAttribute('data-announcement-id')
  const dismissVersion = Number(announcement.getAttribute('data-dismiss-version') || '1')

  if (!announcementId) {
    return
  }

  const syncVisibility = () => {
    const hiddenAnnouncements = readHiddenAnnouncements()
    const isHidden = Number(hiddenAnnouncements[String(announcementId)] || 0) === dismissVersion

    announcement.classList.toggle('hidden', isHidden)
    restoreButton.classList.toggle('hidden', !isHidden)
    restoreButton.classList.toggle('inline-flex', isHidden)
  }

  announcement.querySelector('[data-home-announcement-dismiss]')?.addEventListener('click', () => {
    const hiddenAnnouncements = readHiddenAnnouncements()
    hiddenAnnouncements[String(announcementId)] = dismissVersion
    writeHiddenAnnouncements(hiddenAnnouncements)
    syncVisibility()
  })

  restoreButton.addEventListener('click', () => {
    const hiddenAnnouncements = readHiddenAnnouncements()
    delete hiddenAnnouncements[String(announcementId)]
    writeHiddenAnnouncements(hiddenAnnouncements)
    syncVisibility()
  })

  syncVisibility()
}

function initMatureReveal() {
  document.querySelectorAll('[data-home-mature-toggle]').forEach((button) => {
    button.addEventListener('click', () => {
      const targetId = button.getAttribute('data-home-mature-toggle')
      const image = targetId ? document.getElementById(targetId) : null
      const overlay = button.closest('[data-home-mature-overlay]')

      if (!image || !overlay) {
        return
      }

      image.classList.remove('blur-2xl', 'scale-[1.03]')
      overlay.remove()
    })
  })
}

if (typeof document !== 'undefined') {
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      initAnnouncement()
      initMatureReveal()
    }, { once: true })
  } else {
    initAnnouncement()
    initMatureReveal()
  }
}