const OFFER_CONTEXT_STORAGE_KEY = 'bent.public.offer.slug'

function normalizeOfferSlug(value) {
  return String(value || '').trim()
}

export function usePublicOfferContext() {
  const route = useRoute()
  const persistedOfferSlug = useState('public-offer-context-slug', () => '')

  function syncFromStorage() {
    if (!import.meta.client || persistedOfferSlug.value) {
      return
    }

    const storedValue = window.sessionStorage.getItem(OFFER_CONTEXT_STORAGE_KEY)

    if (storedValue) {
      persistedOfferSlug.value = normalizeOfferSlug(storedValue)
    }
  }

  function persistOfferSlug(value) {
    const normalizedValue = normalizeOfferSlug(value)

    persistedOfferSlug.value = normalizedValue

    if (import.meta.client) {
      if (normalizedValue) {
        window.sessionStorage.setItem(OFFER_CONTEXT_STORAGE_KEY, normalizedValue)
      } else {
        window.sessionStorage.removeItem(OFFER_CONTEXT_STORAGE_KEY)
      }
    }

    return normalizedValue
  }

  watch(
    () => route.query.offerSlug,
    (value) => {
      const normalizedValue = normalizeOfferSlug(value)

      if (normalizedValue) {
        persistOfferSlug(normalizedValue)
        return
      }

      syncFromStorage()
    },
    { immediate: true },
  )

  const activeOfferSlug = computed(() => {
    return normalizeOfferSlug(route.query.offerSlug) || normalizeOfferSlug(persistedOfferSlug.value)
  })

  return {
    activeOfferSlug,
    persistOfferSlug,
  }
}
