Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

11.1 KB
Raw Blame
import type { TFunction } from 'i18next'
import { ArrowUpIcon } from '@phosphor-icons/react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import { useFetcher, useLoaderData, useNavigate } from 'react-router'
import { toast } from 'sonner'

import {
  PricingInternal,
  type MarketingPricingContext,
  type MarketingPricingSelection,
} from '~/components/pricing/MarketingPricing'
import { usePaddle } from '~/hooks/usePaddle'
import { paddleLanguageMapping, TRIAL_DAYS } from '~/lib/constants'
import {
  EVENT_TIERS,
  getPlanPrice,
  type PlanTypeCode,
} from '~/lib/pricing/catalog'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import type { SubscribeLoaderData } from '~/routes/subscribe'
import type { UserSettingsActionData } from '~/routes/user-settings'
import Alert from '~/ui/Alert'
import Button from '~/ui/Button'
import { FAQ } from '~/ui/FAQ'
import { Text } from '~/ui/Text'
import { getRevenueAttribution, trackCustom } from '~/utils/analytics'
import routes from '~/utils/routes'

import { SubscribeFeatures } from './SubscribeFeatures'
import { SubscribeIncluded } from './SubscribeIncluded'
import { SubscribeProof } from './SubscribeProof'
import { SubscribeRating } from './SubscribeRating'
import { TrialTimeline } from './TrialTimeline'

type PayLinkResponse = {
  url?: string
}

const formatEventsLong = (value: number): string =>
  value.toLocaleString('en-US')

const getPlanName = (planType: PlanTypeCode, t: TFunction) =>
  t(`pricing.planTypes.${planType}.name`)

const getCheckoutErrorMessage = (error: string | undefined, t: TFunction) => {
  if (error?.startsWith('billing.')) {
    return t(error)
  }

  return error || t('billing.checkoutPreparationError')
}

const Subscribe = () => {
  const {
    t,
    i18n: { language },
  } = useTranslation('common')
  const { theme } = useTheme()
  const { user, loadUser } = useAuth()
  const navigate = useNavigate()
  const { metainfo, stats } = useLoaderData<SubscribeLoaderData>()

  const [selectionLoading, setSelectionLoading] =
    useState<MarketingPricingSelection | null>(null)
  const [pricingContext, setPricingContext] =
    useState<MarketingPricingContext | null>(null)
  const [hasCompletedCheckout, setHasCompletedCheckout] = useState(false)
  const checkoutInProgressRef = useRef(false)

  const onPaddleEvent = useCallback((eventData: any) => {
    if (eventData?.event === 'Checkout.Complete') {
      checkoutInProgressRef.current = false
      setHasCompletedCheckout(true)
      setSelectionLoading(null)
      return
    }

    if (eventData?.event === 'Checkout.Close') {
      checkoutInProgressRef.current = false
      setSelectionLoading(null)
    }
  }, [])

  const { isPaddleLoaded, paddleLoadError, openCheckout } = usePaddle({
    onEvent: onPaddleEvent,
  })

  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)

  useEffect(() => {
    if (!hasCompletedCheckout) return

    let attempts = 0
    const maxPollAttempts = 30

    pollRef.current = setInterval(async () => {
      attempts += 1

      try {
        const freshUser = await loadUser()

        if (freshUser?.planCode && freshUser.planCode !== 'none') {
          if (pollRef.current) clearInterval(pollRef.current)
          navigate(routes.dashboard)
          return
        }
      } catch (error) {
        void error
      }

      if (attempts >= maxPollAttempts) {
        if (pollRef.current) clearInterval(pollRef.current)
        navigate(routes.dashboard)
      }
    }, 2000)

    return () => {
      if (pollRef.current) clearInterval(pollRef.current)
    }
  }, [hasCompletedCheckout, navigate, loadUser])

  const generatePayLinkFetcher = useFetcher<UserSettingsActionData>()
  const handledPayLinkDataRef = useRef<UserSettingsActionData | null>(null)

  useEffect(() => {
    const fetcherData = generatePayLinkFetcher.data

    if (!fetcherData || handledPayLinkDataRef.current === fetcherData) {
      return
    }

    handledPayLinkDataRef.current = fetcherData

    if (fetcherData.success && fetcherData.data) {
      const url = (fetcherData.data as PayLinkResponse).url

      if (!url) {
        toast.error(t('billing.checkoutPreparationError'))
        checkoutInProgressRef.current = false
        setSelectionLoading(null)
        return
      }

      const opened = openCheckout({
        override: url,
        locale: paddleLanguageMapping[language] || language,
        title: selectionLoading
          ? t('pricing.selectedPlanWithEvents', {
              plan: getPlanName(selectionLoading.planType, t),
              events: formatEventsLong(
                EVENT_TIERS[selectionLoading.eventTier].monthlyEvents,
              ),
            })
          : t('checkout.title'),
        message: t('billing.checkoutVatMessage'),
        email: user?.email,
        displayModeTheme: theme,
        country: metainfo.country,
        hideTaxLink: false,
      })

      if (!opened) {
        toast.error(t('billing.checkoutPreparationError'))
        checkoutInProgressRef.current = false
        setSelectionLoading(null)
      }

      return
    }

    if (fetcherData.error) {
      toast.error(getCheckoutErrorMessage(fetcherData.error, t))
      checkoutInProgressRef.current = false
      setSelectionLoading(null)
    }
  }, [
    generatePayLinkFetcher.data,
    language,
    metainfo.country,
    openCheckout,
    selectionLoading,
    t,
    theme,
    user?.email,
  ])

  const handlePlanSelection = async (selection: MarketingPricingSelection) => {
    if (
      checkoutInProgressRef.current ||
      selectionLoading ||
      hasCompletedCheckout
    ) {
      return
    }

    checkoutInProgressRef.current = true

    const selectedPrice = getPlanPrice(
      selection.planType,
      selection.eventTier,
      selection.billingFrequency,
      selection.currency,
    )

    trackCustom('SUBSCRIBE_START_CHECKOUT', {
      planType: selection.planType,
      eventTier: selection.eventTier,
      billingFrequency: selection.billingFrequency,
      currency: selection.currency,
      paddleLoadError,
      isPaddleLoaded,
      paddleWindowExists: !!(window as any).Paddle,
    })

    if (!selectedPrice?.paddlePlanId) {
      toast.error(t('billing.planNotConfiguredForCheckout'))
      checkoutInProgressRef.current = false
      return
    }

    setSelectionLoading(selection)
    const attribution = await getRevenueAttribution()

    generatePayLinkFetcher.submit(
      {
        intent: 'generate-pay-link',
        planType: selection.planType,
        eventTier: selection.eventTier,
        billingFrequency: selection.billingFrequency,
        currency: selection.currency,
        ...attribution,
      },
      { method: 'POST', action: '/user-settings' },
    )
  }

  const faqItems = useMemo(() => {
    return Array.from({ length: 7 }, (_, index) => ({
      question: (
        <Trans
          t={t}
          i18nKey={`checkout.faq.items.${index}.q`}
          values={{ days: TRIAL_DAYS }}
        />
      ),
      answer: (
        <Trans
          t={t}
          i18nKey={`checkout.faq.items.${index}.a`}
          values={{ days: TRIAL_DAYS }}
        />
      ),
    }))
  }, [t])

  const scrollToPricing = () => {
    trackCustom('SUBSCRIBE_BOTTOM_CTA')
    const pricing = document.getElementById('start-trial')

    if (!pricing) return

    pricing.focus({ preventScroll: true })
    pricing.scrollIntoView({
      behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches
        ? 'auto'
        : 'smooth',
      block: 'start',
    })
  }

  return (
    <>
      <main className='min-h-min-footer bg-gray-50 pb-16 dark:bg-slate-950'>
        <div className='mx-auto max-w-3xl px-4 pt-10 text-center sm:px-6 lg:px-8'>
          <Text
            as='h1'
            size='4xl'
            weight='bold'
            colour='primary'
            className='text-balance'
          >
            {t('checkout.title')}
          </Text>
          <Text
            as='p'
            size='lg'
            colour='secondary'
            className='mx-auto mt-4 max-w-xl text-pretty'
          >
            {t('checkout.subtitle', { days: TRIAL_DAYS })}
          </Text>
        </div>

        {hasCompletedCheckout ? (
          <div className='mx-auto mt-6 w-full max-w-xl px-4 sm:px-6 lg:px-8'>
            <Alert variant='success'>{t('checkout.successRedirect')}</Alert>
          </div>
        ) : null}

        <div
          id='start-trial'
          tabIndex={-1}
          className='scroll-mt-6 outline-none focus-visible:ring-2 focus-visible:ring-slate-900 dark:focus-visible:ring-slate-300'
        >
          <PricingInternal
            metainfo={metainfo}
            onSelectPlan={handlePlanSelection}
            onSelectionChange={setPricingContext}
            loadingPlanType={selectionLoading?.planType ?? null}
            disabled={Boolean(selectionLoading) || hasCompletedCheckout}
            showVatNote
          />
        </div>

        <SubscribeRating websiteCount={stats?.projects} />

        <TrialTimeline />

        <div className='mx-auto w-full max-w-4xl space-y-16 px-4 pt-16 sm:px-6 sm:pt-20 lg:px-8'>
          <SubscribeFeatures />

          <SubscribeIncluded
            monthlyEvents={
              pricingContext?.monthlyEvents ?? EVENT_TIERS['100k'].monthlyEvents
            }
            isCustomEventTier={pricingContext?.isCustomEventTier ?? false}
          />

          <SubscribeProof websiteCount={stats?.projects} />

          <section className='mx-auto max-w-4xl'>
            <div className='mx-auto max-w-2xl text-center'>
              <Text as='h2' size='2xl' weight='bold' tracking='tight'>
                {t('checkout.faq.title')}
              </Text>
              <Text
                as='p'
                size='base'
                colour='secondary'
                className='mx-auto mt-2 leading-relaxed text-pretty'
              >
                {t('checkout.faq.subtitle')}
              </Text>
            </div>
            <FAQ items={faqItems} className='mt-5' defaultOpenFirst />
          </section>

          <section className='rounded-2xl bg-white px-5 py-8 text-center ring-1 ring-gray-200 sm:px-8 sm:py-10 dark:bg-slate-900 dark:ring-white/10'>
            <Text
              as='h2'
              size='2xl'
              weight='bold'
              tracking='tight'
              className='text-balance'
            >
              {t('checkout.finalCta.title')}
            </Text>
            <Text
              as='p'
              size='sm'
              colour='secondary'
              className='mx-auto mt-2 max-w-xl leading-relaxed text-pretty'
            >
              {t('checkout.finalCta.subtitle', { days: TRIAL_DAYS })}
            </Text>
            <Button
              type='button'
              size='lg'
              onClick={scrollToPricing}
              className='mt-6 justify-center gap-2'
            >
              {t('checkout.finalCta.button')}
              <ArrowUpIcon weight='bold' className='size-4' />
            </Button>
          </section>
        </div>
      </main>

      <div className='checkout-container' id='checkout-container' />
    </>
  )
}

export default Subscribe