Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

63.9 KB
Raw Blame
import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import posthog from 'posthog-js'
import React from 'react'

import { LemonDialog, lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'
import type { FeatureFlagKey } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import type { BillingAlertConfig, SwitchPlanPayload, UnsubscribeError } from 'lib/logic/billing/billingLogic'
import { billingProductRowDisplayName } from 'lib/logic/billing/billingProductDisplayName'
import { getHeldCompanions } from 'lib/logic/billing/companionProducts'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'

import {
    BillingPlan,
    BillingPlanType,
    BillingProductV2AddonType,
    BillingProductV2Type,
    BillingType,
    SurveyEventName,
} from '~/types'

import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import { ProductKey } from '../../queries/schema/schema-general'
import {
    calculateFreeTier,
    canHaveBillingLimit,
    createGaugeItems,
    isAddonVisible,
    isProductVariantPrimary,
} from './billing-utils'
import { getBillingLimitConfig } from './billingLimitConfig'
import type { BillingLimitConfig } from './billingLimitConfig'
import { DATA_PIPELINES_CUTOFF_DATE } from './constants'
import { paymentEntryLogic } from './paymentEntryLogic'
import { BillingGaugeItemKind, BillingGaugeItemType } from './types'

const DEFAULT_BILLING_LIMIT: number = 500

// Rounds a dollar amount to the cent the same way humanFriendlyCurrency displays it.
const roundToCents = (amount: number): number =>
    parseFloat(amount.toLocaleString('en-US', { maximumFractionDigits: 2, useGrouping: false }))

type UnsubscribeReason = {
    reason: string
    question: string
}

export const UNSUBSCRIBE_REASONS: UnsubscribeReason[] = [
    { reason: 'Too expensive', question: 'What will you be using instead?' },
    { reason: 'Not getting enough value', question: 'What prevented you from getting more value out of PostHog?' },
    { reason: 'Not using the product', question: 'Why are you not using the product?' },
    { reason: 'Found a better alternative', question: 'What service will you be moving to?' },
    { reason: 'Poor customer support', question: 'Please provide details on your support experience.' },
    { reason: 'Too difficult to use', question: 'What was difficult to use?' },
    { reason: 'Not enough hedgehogs', question: 'How many hedgehogs do you need? (but really why are you leaving)' },
    { reason: 'Shutting down company', question: "We're sorry to hear that ❤️. What was your favorite feature?" },
    { reason: 'Technical issues', question: 'What technical problems did you experience?' },
    { reason: 'Building it ourselves', question: 'What will you build, and what made building it the better option?' },
    { reason: 'Other (let us know below!)', question: 'Why are you leaving?' },
]

export const randomizeReasons = (reasons: UnsubscribeReason[]): UnsubscribeReason[] => {
    const shuffledReasons = reasons.slice(0, -1).sort(() => Math.random() - 0.5)
    shuffledReasons.push(reasons[reasons.length - 1])
    return shuffledReasons
}

export const TRIAL_CANCEL_REASONS: UnsubscribeReason[] = [
    { reason: 'Too expensive', question: 'What budget would make sense?' },
    { reason: 'Trial too short', question: 'How long would be enough to try the add-on features?' },
    { reason: 'Complex setup', question: 'Which part of the setup was challenging?' },
    { reason: 'Found a better alternative', question: 'Which alternative are you going with?' },
    { reason: "Don't need add-on features", question: 'Which features did you not need?' },
    { reason: 'Poor customer support', question: 'Please provide details on your support experience.' },
    { reason: 'Other', question: 'What should we know?' },
]

export const isPlatformAndSupportAddon = (product: BillingProductV2Type | BillingProductV2AddonType): boolean => {
    return (
        product.type === BillingPlan.Boost ||
        product.type === BillingPlan.Teams ||
        product.type === BillingPlan.Scale ||
        product.type === BillingPlan.Enterprise
    )
}

export interface BillingProductLogicProps {
    product: BillingProductV2Type | BillingProductV2AddonType
    productRef?: React.MutableRefObject<HTMLDivElement | null>
    billingLimitInputRef?: React.MutableRefObject<HTMLInputElement | null>
    hogfettiTrigger?: () => void
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface billingProductLogicValues {
    billing: BillingType | null // billingLogic
    currentPlatformAddon: BillingProductV2AddonType | null // billingLogic
    currentPlatformAddonPlan: BillingPlanType | null // billingLogic
    isUnlicensedDebug: boolean // billingLogic
    platformAddons: BillingProductV2AddonType[] // billingLogic
    productAnalyticsFreePlan: BillingPlanType | null // billingLogic
    productAnalyticsPlanAfterPackageDowngrade: BillingPlanType | null // billingLogic
    scrollToProductKey: ProductKey | null // billingLogic
    selfServeBillingNotice: string | null // billingLogic
    timeRemainingInSeconds: number // billingLogic
    timeTotalInSeconds: number // billingLogic
    unsubscribeError: UnsubscribeError | null // billingLogic
    unusedPlatformAddonAmount: number // billingLogic
    featureFlags: FeatureFlagsSet // featureFlagLogic
    amountDueBeforeCredits: number
    amountDueToday: number
    appliedCreditBalance: number
    availableCreditBalance: number
    billingGaugeItems: BillingGaugeItemType[]
    billingLimitAsUsage: number
    billingLimitConfig: BillingLimitConfig
    billingLimitInput: Record<string, any>
    billingLimitInputAllErrors: Record<string, any>
    billingLimitInputChanged: boolean
    billingLimitInputErrors: DeepPartialMap<Record<string, any>, ValidationErrorType>
    billingLimitInputHasErrors: boolean
    billingLimitInputManualErrors: Record<string, any>
    billingLimitInputTouched: boolean
    billingLimitInputTouches: Record<string, boolean>
    billingLimitInputValidationErrors: DeepPartialMap<Record<string, any>, ValidationErrorType>
    billingLimitNextPeriod: number | null
    billingProductLoading: string | null
    combinedMonetaryData: {
        billingLimit: number | null
        currentTotal: number
        discountPercent: number
        projectedTotal: number
        rawCurrentTotal: string
        rawProjectedTotal: string
    }
    combinedMonetaryGaugeItems: BillingGaugeItemType[]
    comparisonModalHighlightedFeatureKey: string | null
    confirmDowngradeModalOpen: boolean
    confirmPurchaseModalOpen: boolean
    confirmUpgradeModalOpen: boolean
    currentAmountTotalActual: string
    currentAndUpgradePlans: {
        currentPlan: BillingPlanType | null
        upgradePlan: BillingPlanType
    }
    customLimitUsd: number | null
    eventsRetentionPlansAfterUnsubscribe: (BillingPlanType | null)[] | null
    freeTier: number
    hasCustomLimitSet: boolean
    hedgehogSatisfied: boolean
    heldCompanions: BillingProductV2Type[]
    isAddonProduct: boolean
    isBillingLimitInputSubmitting: boolean
    isBillingLimitInputValid: boolean
    isDataPipelinesDeprecated: boolean
    isEditingBillingLimit: boolean
    isLowerTierThanCurrentAddon: boolean
    isPlanComparisonModalOpen: boolean
    isPricingModalOpen: boolean
    isProductWithVariants: boolean
    isProrated: boolean
    isSubscribedToAnotherAddon: boolean
    noLimitCompanionAmounts: {
        companion: BillingProductV2Type
        currentAmount: number
        projectedAmount: number
    }[]
    productVariants: Array<{
        displayName: string
        key: string
        product: BillingProductV2AddonType | BillingProductV2Type
    }> | null
    productsToDeactivate: string
    projectedAmountExcludingAddons: string
    proratedAmount: number
    removingBillingLimitNextPeriod: boolean
    showBillingLimitInputErrors: boolean
    showTierBreakdown: boolean
    surveyID: string
    surveyResponse: {
        $survey_response: string
        $survey_response_2: string[]
    }
    totalsIncludingCompanions: {
        currentTotal: number
        projectedTotal: number
    }
    trialCancelReasonQuestions: string
    trialLoading: boolean
    unsubscribeModalStep: number
    unsubscribeReasonQuestions: string
    unsubscribeReasonSurvey: null
    variantExpandedStates: Record<string, boolean>
    visibleAddons: BillingProductV2AddonType[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface billingProductLogicActions {
    deactivateProduct: (key: string) => string // billingLogic
    deactivateProductSuccess: (
        billing: BillingType | null,
        payload?: string | undefined
    ) => {
        billing: BillingType | null
        payload?: string
    } // billingLogic
    loadBilling: () => any // billingLogic
    loadBillingSuccess: (
        billing: BillingType | null,
        payload?: any
    ) => {
        billing: BillingType | null
        payload?: any
    } // billingLogic
    setProductSpecificAlert: (productSpecificAlert: BillingAlertConfig | null) => {
        productSpecificAlert: BillingAlertConfig | null
    } // billingLogic
    setScrollToProductKey: (scrollToProductKey: ProductKey | null) => {
        scrollToProductKey: ProductKey | null
    } // billingLogic
    setSwitchPlanLoading: (productKey: string | null) => {
        productKey: string | null
    } // billingLogic
    switchFlatrateSubscriptionPlan: (data: SwitchPlanPayload) => SwitchPlanPayload // billingLogic
    updateBillingLimits: (limits: { [key: string]: number | null }) => {
        [key: string]: number | null
    } // billingLogic
    updateBillingLimitsSuccess: (
        billing: BillingType | null,
        payload?:
            | {
                  [key: string]: number | null
              }
            | undefined
    ) => {
        billing: BillingType | null
        payload?: {
            [key: string]: number | null
        }
    } // billingLogic
    upgradeProducts: (
        products: string,
        redirectPath: string | null
    ) => {
        products: string
        redirectPath: string | null
    } // paymentEntryLogic
    activateTrial: () => {
        value: true
    }
    billingLoaded: () => {
        value: true
    }
    cancelTrial: () => {
        value: true
    }
    confirmProductDowngrade: () => {
        value: true
    }
    confirmProductPurchase: () => {
        value: true
    }
    confirmProductUpgrade: () => {
        value: true
    }
    handleProductUpgrade: (
        products: string,
        redirectPath?: string
    ) => {
        products: string
        redirectPath: string | undefined
    }
    hideConfirmDowngradeModal: () => {
        value: true
    }
    hideConfirmPurchaseModal: () => {
        value: true
    }
    hideConfirmUpgradeModal: () => {
        value: true
    }
    initiateProductUpgrade: (
        product: BillingProductV2AddonType | BillingProductV2Type,
        plan: BillingPlanType,
        redirectPath?: string
    ) => {
        plan: BillingPlanType
        product: BillingProductV2AddonType | BillingProductV2Type
        redirectPath: string | undefined
    }
    removeBillingLimitNextPeriod: (productType: string) => {
        productType: string
    }
    reportSurveyDismissed: (surveyID: string) => {
        surveyID: string
    }
    reportSurveySent: (
        surveyID: string,
        surveyResponse: Record<string, string | string[]>
    ) => {
        surveyID: string
        surveyResponse: Record<string, string | string[]>
    }
    reportSurveyShown: (
        surveyID: string,
        productType: string
    ) => {
        productType: string
        surveyID: string
    }
    resetBillingLimitInput: (values?: Record<string, any>) => {
        values?: Record<string, any>
    }
    resetUnsubscribeModalStep: () => {
        value: true
    }
    setBillingLimitInput: (billingLimitInput: number | null) => {
        billingLimitInput: number | null
    }
    setBillingLimitInputManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setBillingLimitInputValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setBillingLimitInputValues: (values: DeepPartial<Record<string, any>>) => {
        values: DeepPartial<Record<string, any>>
    }
    setBillingProductLoading: (productKey: string | null) => {
        productKey: string | null
    }
    setHedgehogSatisfied: (satisfied: boolean) => {
        satisfied: boolean
    }
    setIsEditingBillingLimit: (isEditingBillingLimit: boolean) => {
        isEditingBillingLimit: boolean
    }
    setRemovingBillingLimitNextPeriod: (removingBillingLimitNextPeriod: boolean) => {
        removingBillingLimitNextPeriod: boolean
    }
    setShowTierBreakdown: (showTierBreakdown: boolean) => {
        showTierBreakdown: boolean
    }
    setSurveyID: (surveyID: string) => {
        surveyID: string
    }
    setSurveyResponse: (
        key: string,
        value: string | string[]
    ) => {
        key: string
        value: string | string[]
    }
    setTrialLoading: (loading: boolean) => {
        loading: boolean
    }
    setUnsubscribeModalStep: (step: number) => {
        step: number
    }
    showConfirmDowngradeModal: () => {
        value: true
    }
    showConfirmPurchaseModal: () => {
        value: true
    }
    showConfirmUpgradeModal: () => {
        value: true
    }
    submitBillingLimitInput: () => {
        value: boolean
    }
    submitBillingLimitInputFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitBillingLimitInputRequest: (billingLimitInput: Record<string, any>) => {
        billingLimitInput: Record<string, any>
    }
    submitBillingLimitInputSuccess: (billingLimitInput: Record<string, any>) => {
        billingLimitInput: Record<string, any>
    }
    toggleIsPlanComparisonModalOpen: (highlightedFeatureKey?: string) => {
        highlightedFeatureKey: string | undefined
    }
    toggleIsPricingModalOpen: () => {
        value: true
    }
    toggleSurveyReason: (reason: string) => {
        reason: string
    }
    toggleVariantExpanded: (variantKey: string) => {
        variantKey: string
    }
    touchBillingLimitInputField: (key: string) => {
        key: string
    }
    triggerMoreHedgehogs: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface billingProductLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        proratedAmount: (
            currentAndUpgradePlans: {
                currentPlan: BillingPlanType | null
                upgradePlan: BillingPlanType
            },
            timeRemainingInSeconds: number,
            timeTotalInSeconds: number
        ) => number
        isProrated: (
            billing: BillingType | null,
            currentAndUpgradePlans: {
                currentPlan: BillingPlanType | null
                upgradePlan: BillingPlanType
            },
            proratedAmount: number
        ) => boolean
        isLowerTierThanCurrentAddon: (
            product: BillingProductV2AddonType | BillingProductV2Type,
            currentPlatformAddon: BillingProductV2AddonType | null,
            platformAddons: BillingProductV2AddonType[]
        ) => boolean
        isSubscribedToAnotherAddon: (
            billing: BillingType | null,
            product: BillingProductV2AddonType | BillingProductV2Type
        ) => boolean
        availableCreditBalance: (billing: BillingType | null) => number
        amountDueBeforeCredits: (
            proratedAmount: number,
            unusedPlatformAddonAmount: number,
            isSubscribedToAnotherAddon: boolean
        ) => number
        appliedCreditBalance: (amountDueBeforeCredits: number, availableCreditBalance: number) => number
        amountDueToday: (amountDueBeforeCredits: number, appliedCreditBalance: number) => number
        customLimitUsd: (
            billing: BillingType | null,
            product: BillingProductV2AddonType | BillingProductV2Type
        ) => number | null
        visibleAddons: (
            featureFlags: FeatureFlagsSet,
            product: BillingProductV2AddonType | BillingProductV2Type
        ) => BillingProductV2AddonType[]
        hasCustomLimitSet: (customLimitUsd: number | null) => boolean
        isDataPipelinesDeprecated: (product: BillingProductV2AddonType | BillingProductV2Type) => boolean
        currentAndUpgradePlans: (product: BillingProductV2AddonType | BillingProductV2Type) => {
            currentPlan: BillingPlanType | null
            upgradePlan: BillingPlanType
        }
        freeTier: (product: BillingProductV2AddonType | BillingProductV2Type) => number
        billingLimitAsUsage: (product: BillingProductV2AddonType | BillingProductV2Type) => number
        billingLimitNextPeriod: (
            billing: BillingType | null,
            product: BillingProductV2AddonType | BillingProductV2Type
        ) => number | null
        billingLimitConfig: (
            billing: BillingType | null,
            product: BillingProductV2AddonType | BillingProductV2Type,
            customLimitUsd: number | null,
            billingLimitNextPeriod: number | null
        ) => BillingLimitConfig
        billingGaugeItems: (
            product: BillingProductV2AddonType | BillingProductV2Type,
            billing: BillingType | null,
            billingLimitAsUsage: number
        ) => BillingGaugeItemType[]
        isAddonProduct: (
            billing: BillingType | null,
            product: BillingProductV2AddonType | BillingProductV2Type
        ) => boolean
        productsToDeactivate: (
            billing: BillingType | null,
            isAddonProduct: boolean,
            product: BillingProductV2AddonType | BillingProductV2Type
        ) => string
        eventsRetentionPlansAfterUnsubscribe: (
            product: BillingProductV2AddonType | BillingProductV2Type,
            productsToDeactivate: string,
            productAnalyticsFreePlan: BillingPlanType | null,
            productAnalyticsPlanAfterPackageDowngrade: BillingPlanType | null,
            currentPlatformAddonPlan: BillingPlanType | null
        ) => (BillingPlanType | null)[] | null
        unsubscribeReasonQuestions: (surveyResponse: {
            $survey_response: string
            $survey_response_2: string[]
        }) => string
        trialCancelReasonQuestions: (surveyResponse: {
            $survey_response: string
            $survey_response_2: string[]
        }) => string
        isProductWithVariants: (product: BillingProductV2AddonType | BillingProductV2Type) => boolean
        projectedAmountExcludingAddons: (
            isProductWithVariants: boolean,
            product: BillingProductV2AddonType | BillingProductV2Type
        ) => string
        productVariants: (
            isProductWithVariants: boolean,
            product: BillingProductV2AddonType | BillingProductV2Type
        ) => Array<{
            displayName: string
            key: string
            product: BillingProductV2AddonType | BillingProductV2Type
        }> | null
        combinedMonetaryData: (
            customLimitUsd: number | null,
            product: BillingProductV2AddonType | BillingProductV2Type,
            billing: BillingType | null
        ) => {
            billingLimit: number | null
            currentTotal: number
            discountPercent: number
            projectedTotal: number
            rawCurrentTotal: string
            rawProjectedTotal: string
        }
        combinedMonetaryGaugeItems: (combinedMonetaryData: {
            billingLimit: number | null
            currentTotal: number
            discountPercent: number
            projectedTotal: number
            rawCurrentTotal: string
            rawProjectedTotal: string
        }) => BillingGaugeItemType[]
        heldCompanions: (
            billing: BillingType | null,
            product: BillingProductV2AddonType | BillingProductV2Type
        ) => BillingProductV2Type[]
        noLimitCompanionAmounts: (
            heldCompanions: BillingProductV2Type[],
            combinedMonetaryData: {
                billingLimit: number | null
                currentTotal: number
                discountPercent: number
                projectedTotal: number
                rawCurrentTotal: string
                rawProjectedTotal: string
            },
            featureFlags: FeatureFlagsSet
        ) => {
            companion: BillingProductV2Type
            currentAmount: number
            projectedAmount: number
        }[]
        totalsIncludingCompanions: (
            combinedMonetaryData: {
                billingLimit: number | null
                currentTotal: number
                discountPercent: number
                projectedTotal: number
                rawCurrentTotal: string
                rawProjectedTotal: string
            },
            noLimitCompanionAmounts: {
                companion: BillingProductV2Type
                currentAmount: number
                projectedAmount: number
            }[]
        ) => {
            currentTotal: number
            projectedTotal: number
        }
        currentAmountTotalActual: (
            isProductWithVariants: boolean,
            product: BillingProductV2AddonType | BillingProductV2Type,
            visibleAddons: BillingProductV2AddonType[]
        ) => string
    }
}

export type billingProductLogicType = MakeLogicType<
    billingProductLogicValues,
    billingProductLogicActions,
    BillingProductLogicProps,
    billingProductLogicMeta
>

export const billingProductLogic = kea<billingProductLogicType>([
    props({} as BillingProductLogicProps),
    key((props) => props.product.type),
    path(['scenes', 'billing', 'billingProductLogic']),
    connect(() => ({
        values: [
            billingLogic,
            [
                'billing',
                'isUnlicensedDebug',
                'scrollToProductKey',
                'unsubscribeError',
                'currentPlatformAddon',
                'platformAddons',
                'timeRemainingInSeconds',
                'timeTotalInSeconds',
                'unusedPlatformAddonAmount',
                'selfServeBillingNotice',
                'productAnalyticsFreePlan',
                'productAnalyticsPlanAfterPackageDowngrade',
                'currentPlatformAddonPlan',
            ],
            featureFlagLogic,
            ['featureFlags'],
        ],
        actions: [
            paymentEntryLogic,
            ['upgradeProducts'],
            billingLogic,
            [
                'updateBillingLimits',
                'updateBillingLimitsSuccess',
                'loadBilling',
                'loadBillingSuccess',
                'deactivateProduct',
                'setProductSpecificAlert',
                'setScrollToProductKey',
                'deactivateProductSuccess',
                'switchFlatrateSubscriptionPlan',
                'setSwitchPlanLoading',
            ],
        ],
    })),
    actions({
        setIsEditingBillingLimit: (isEditingBillingLimit: boolean) => ({ isEditingBillingLimit }),
        setBillingLimitInput: (billingLimitInput: number | null) => ({ billingLimitInput }),
        billingLoaded: true,
        setShowTierBreakdown: (showTierBreakdown: boolean) => ({ showTierBreakdown }),
        toggleVariantExpanded: (variantKey: string) => ({ variantKey }),
        toggleIsPricingModalOpen: true,
        toggleIsPlanComparisonModalOpen: (highlightedFeatureKey?: string) => ({ highlightedFeatureKey }),
        setSurveyResponse: (key: string, value: string | string[]) => ({ key, value }),
        toggleSurveyReason: (reason: string) => ({ reason }),
        reportSurveyShown: (surveyID: string, productType: string) => ({ surveyID, productType }),
        reportSurveySent: (surveyID: string, surveyResponse: Record<string, string | string[]>) => ({
            surveyID,
            surveyResponse,
        }),
        reportSurveyDismissed: (surveyID: string) => ({ surveyID }),
        setSurveyID: (surveyID: string) => ({ surveyID }),
        setBillingProductLoading: (productKey: string | null) => ({ productKey }),
        setRemovingBillingLimitNextPeriod: (removingBillingLimitNextPeriod: boolean) => ({
            removingBillingLimitNextPeriod,
        }),
        initiateProductUpgrade: (
            product: BillingProductV2Type | BillingProductV2AddonType,
            plan: BillingPlanType,
            redirectPath?: string
        ) => ({
            plan,
            product,
            redirectPath,
        }),
        handleProductUpgrade: (products: string, redirectPath?: string) => ({
            products,
            redirectPath,
        }),
        activateTrial: true,
        cancelTrial: true,
        setTrialLoading: (loading: boolean) => ({ loading }),
        setUnsubscribeModalStep: (step: number) => ({ step }),
        resetUnsubscribeModalStep: true,
        setHedgehogSatisfied: (satisfied: boolean) => ({ satisfied }),
        triggerMoreHedgehogs: true,
        removeBillingLimitNextPeriod: (productType: string) => ({ productType }),
        showConfirmUpgradeModal: true,
        hideConfirmUpgradeModal: true,
        confirmProductUpgrade: true,
        showConfirmDowngradeModal: true,
        hideConfirmDowngradeModal: true,
        confirmProductDowngrade: true,
        showConfirmPurchaseModal: true,
        hideConfirmPurchaseModal: true,
        confirmProductPurchase: true,
    }),
    reducers({
        billingLimitInput: [
            { input: DEFAULT_BILLING_LIMIT },
            {
                setBillingLimitInput: (_, { billingLimitInput }) => {
                    return {
                        input: billingLimitInput,
                    }
                },
            },
        ],
        isEditingBillingLimit: [
            false,
            {
                setIsEditingBillingLimit: (_, { isEditingBillingLimit }) => isEditingBillingLimit,
            },
        ],
        showTierBreakdown: [
            false,
            {
                setShowTierBreakdown: (_, { showTierBreakdown }) => showTierBreakdown,
            },
        ],
        variantExpandedStates: [
            {} as Record<string, boolean>,
            {
                toggleVariantExpanded: (state, { variantKey }) => ({
                    ...state,
                    [variantKey]: !state[variantKey],
                }),
            },
        ],
        isPricingModalOpen: [
            false as boolean,
            {
                toggleIsPricingModalOpen: (state) => !state,
            },
        ],
        isPlanComparisonModalOpen: [
            false as boolean,
            {
                toggleIsPlanComparisonModalOpen: (state) => !state,
            },
        ],
        surveyResponse: [
            { $survey_response_2: [], $survey_response: '' } as {
                $survey_response_2: string[]
                $survey_response: string
            },
            {
                setSurveyResponse: (state, { key, value }) => {
                    return { ...state, [key]: value }
                },
                toggleSurveyReason: (state, { reason }) => {
                    const reasons = state.$survey_response_2.includes(reason)
                        ? state.$survey_response_2.filter((r) => r !== reason)
                        : [...state.$survey_response_2, reason]
                    return { ...state, $survey_response_2: reasons }
                },
            },
        ],
        unsubscribeReasonSurvey: [
            null,
            {
                setUnsubscribeReasonSurvey: (_, { survey }) => survey,
            },
        ],
        surveyID: [
            '',
            {
                setSurveyID: (_, { surveyID }) => surveyID,
            },
        ],
        billingProductLoading: [
            null as string | null,
            {
                setBillingProductLoading: (_, { productKey }) => productKey,
            },
        ],
        removingBillingLimitNextPeriod: [
            false,
            {
                setRemovingBillingLimitNextPeriod: (_, { removingBillingLimitNextPeriod }) =>
                    removingBillingLimitNextPeriod,
            },
        ],
        comparisonModalHighlightedFeatureKey: [
            null as string | null,
            {
                toggleIsPlanComparisonModalOpen: (_, { highlightedFeatureKey }) => highlightedFeatureKey || null,
            },
        ],
        trialLoading: [
            false,
            {
                setTrialLoading: (_, { loading }) => loading,
            },
        ],
        unsubscribeModalStep: [
            1 as number,
            {
                setUnsubscribeModalStep: (_, { step }) => step,
                resetUnsubscribeModalStep: () => 1,
            },
        ],
        hedgehogSatisfied: [
            false as boolean,
            {
                setHedgehogSatisfied: (_, { satisfied }) => satisfied,
            },
        ],
        confirmUpgradeModalOpen: [
            false as boolean,
            {
                showConfirmUpgradeModal: () => true,
                hideConfirmUpgradeModal: () => false,
            },
        ],
        confirmDowngradeModalOpen: [
            false as boolean,
            {
                showConfirmDowngradeModal: () => true,
                hideConfirmDowngradeModal: () => false,
            },
        ],
        confirmPurchaseModalOpen: [
            false as boolean,
            {
                showConfirmPurchaseModal: () => true,
                hideConfirmPurchaseModal: () => false,
                // Auto-close once the activation call settles (loading cleared), so the modal
                // doesn't linger if the purchase succeeds or routes to payment entry.
                setBillingProductLoading: (state, { productKey }) => (productKey ? state : false),
            },
        ],
    }),
    selectors(({ values }) => ({
        proratedAmount: [
            (s) => [s.currentAndUpgradePlans, s.timeRemainingInSeconds, s.timeTotalInSeconds],
            (
                currentAndUpgradePlans: {
                    currentPlan: BillingPlanType | null
                    upgradePlan: BillingPlanType
                },
                timeRemainingInSeconds: number,
                timeTotalInSeconds: number
            ): number => {
                if (!timeTotalInSeconds) {
                    return 0
                }
                const amountUsd = currentAndUpgradePlans.upgradePlan?.unit_amount_usd
                const unitAmountInt = amountUsd ? parseFloat(amountUsd) : 0
                const ratio = Math.max(0, Math.min(1, timeRemainingInSeconds / timeTotalInSeconds)) // make sure ratio is between 0 and 1
                return Math.round(unitAmountInt * ratio * 100) / 100
            },
        ],
        isProrated: [
            (s) => [s.billing, s.currentAndUpgradePlans, s.proratedAmount],
            (
                billing: BillingType | null,
                currentAndUpgradePlans: {
                    currentPlan: BillingPlanType | null
                    upgradePlan: BillingPlanType
                },
                proratedAmount: number
            ): boolean => {
                const hasActiveSubscription = billing?.has_active_subscription
                const amountUsd = currentAndUpgradePlans.upgradePlan?.unit_amount_usd
                if (!hasActiveSubscription || !amountUsd) {
                    return false
                }
                return proratedAmount !== parseFloat(amountUsd)
            },
        ],
        isLowerTierThanCurrentAddon: [
            (s, p) => [p.product, s.currentPlatformAddon, s.platformAddons],
            (
                product: BillingProductV2AddonType | BillingProductV2Type,
                currentPlatformAddon: BillingProductV2AddonType | null,
                platformAddons: BillingProductV2AddonType[]
            ): boolean => {
                if (!currentPlatformAddon || platformAddons.length === 0) {
                    return false
                }
                const currentIdx = platformAddons.findIndex((a) => a.type === currentPlatformAddon.type)
                const targetIdx = platformAddons.findIndex((a) => a.type === product.type)
                if (currentIdx < 0 || targetIdx < 0) {
                    return false
                }
                return targetIdx < currentIdx
            },
        ],
        isSubscribedToAnotherAddon: [
            (s, p) => [s.billing, p.product],
            (billing: BillingType, addon: BillingProductV2AddonType) => {
                const subscribed = addon.subscribed
                if (subscribed) {
                    // They are subscribed to this addon so can't be subscribed to another one
                    return false
                }

                const parentProduct = billing?.products.find((product: any) =>
                    product.addons.find((a: BillingProductV2AddonType) => a.type === addon.type)
                )
                if (!parentProduct) {
                    return false
                }

                if (parentProduct?.type !== 'platform_and_support') {
                    // Only platform and support can have multiple add-ons
                    return false
                }

                return parentProduct.addons.some((a: BillingProductV2AddonType) => a.subscribed)
            },
        ],
        // Single source of truth for what an add-on purchase/switch costs. Cards show
        // amountDueBeforeCredits (the price of the transaction); the confirmation modals
        // additionally itemize the credit balance and show amountDueToday (what hits the card).
        availableCreditBalance: [
            (s) => [s.billing],
            (billing: BillingType | null): number =>
                billing?.discount_amount_usd ? parseFloat(billing.discount_amount_usd) : 0,
        ],
        amountDueBeforeCredits: [
            (s) => [s.proratedAmount, s.unusedPlatformAddonAmount, s.isSubscribedToAnotherAddon],
            (proratedAmount: number, unusedPlatformAddonAmount: number, isSubscribedToAnotherAddon: boolean): number =>
                // Unused time on the current platform add-on only offsets a switch to another
                // one; a fresh purchase has nothing to trade in.
                Math.max(0, proratedAmount - (isSubscribedToAnotherAddon ? unusedPlatformAddonAmount : 0)),
        ],
        appliedCreditBalance: [
            (s) => [s.amountDueBeforeCredits, s.availableCreditBalance],
            (amountDueBeforeCredits: number, availableCreditBalance: number): number =>
                Math.min(amountDueBeforeCredits, availableCreditBalance),
        ],
        amountDueToday: [
            (s) => [s.amountDueBeforeCredits, s.appliedCreditBalance],
            (amountDueBeforeCredits: number, appliedCreditBalance: number): number =>
                Math.max(0, amountDueBeforeCredits - appliedCreditBalance),
        ],
        customLimitUsd: [
            (s, p) => [s.billing, p.product],
            (billing: BillingType | null, product: BillingProductV2AddonType | BillingProductV2Type) => {
                if (!canHaveBillingLimit(product)) {
                    return null
                }
                const customLimit = billing?.custom_limits_usd?.[product.type]
                if (customLimit === 0 || customLimit) {
                    return Number(customLimit)
                }
                const usageKeyLimit = product.usage_key ? billing?.custom_limits_usd?.[product.usage_key] : null
                return usageKeyLimit === 0 || usageKeyLimit ? Number(usageKeyLimit) : null
            },
        ],
        visibleAddons: [
            (s, p) => [s.featureFlags, p.product],
            (featureFlags: Record<string, any>, product: BillingProductV2Type) => {
                if (!product.addons?.length) {
                    return []
                }

                return product.addons.filter((addon: BillingProductV2AddonType) =>
                    isAddonVisible(product, addon, featureFlags)
                )
            },
        ],
        hasCustomLimitSet: [
            (s) => [s.customLimitUsd],
            (customLimitUsd: number | null) => (!!customLimitUsd || customLimitUsd === 0) && customLimitUsd >= 0,
        ],
        isDataPipelinesDeprecated: [
            (_s, p) => [p.product],
            (product: BillingProductV2Type | BillingProductV2AddonType): boolean => {
                return product.type === 'data_pipelines' && dayjs().isAfter(dayjs(DATA_PIPELINES_CUTOFF_DATE))
            },
        ],
        currentAndUpgradePlans: [
            (_s, p) => [p.product],
            (product: BillingProductV2AddonType | BillingProductV2Type) => {
                const currentPlanIndex = product.plans.findIndex((plan: BillingPlanType) => plan.current_plan)
                const currentPlan = currentPlanIndex >= 0 ? product.plans?.[currentPlanIndex] : null
                const upgradePlan =
                    // If in debug mode and with no license there will be
                    // no currentPlan. So we want to upgrade to the highest plan.
                    values.isUnlicensedDebug
                        ? product.plans?.[product.plans.length - 1]
                        : product.plans?.[currentPlanIndex + 1]
                return { currentPlan, upgradePlan }
            },
        ],
        freeTier: [
            (_s, p) => [p.product],
            (product: BillingProductV2AddonType | BillingProductV2Type) => calculateFreeTier(product),
        ],
        billingLimitAsUsage: [
            (_, p) => [p.product],
            (product: BillingProductV2AddonType | BillingProductV2Type) => {
                return canHaveBillingLimit(product) ? product.usage_limit || 0 : 0
            },
        ],
        billingLimitNextPeriod: [
            (s, p) => [s.billing, p.product],
            (billing: BillingType | null, product: BillingProductV2AddonType | BillingProductV2Type) => {
                if (!canHaveBillingLimit(product)) {
                    return null
                }
                const nextPeriodLimit = billing?.next_period_custom_limits_usd?.[product.type]
                if (nextPeriodLimit === 0 || nextPeriodLimit) {
                    return nextPeriodLimit
                }
                return product.usage_key ? (billing?.next_period_custom_limits_usd?.[product.usage_key] ?? null) : null
            },
        ],
        billingLimitConfig: [
            (s, p) => [s.billing, p.product, s.customLimitUsd, s.billingLimitNextPeriod],
            (
                billing: BillingType | null,
                product: BillingProductV2AddonType | BillingProductV2Type,
                customLimitUsd: number | null,
                billingLimitNextPeriod: number | null
            ) => {
                return getBillingLimitConfig({
                    billing,
                    product,
                    customLimitUsd,
                    billingLimitNextPeriod,
                })
            },
        ],
        billingGaugeItems: [
            (s, p) => [p.product, s.billing, s.billingLimitAsUsage],
            (
                product: BillingProductV2AddonType | BillingProductV2Type,
                billing: BillingType | null,
                billingLimitAsUsage: number
            ): BillingGaugeItemType[] => {
                return createGaugeItems(product, {
                    billing,
                    billingLimitAsUsage,
                })
            },
        ],
        isAddonProduct: [
            (s, p) => [s.billing, p.product],
            (billing: BillingType | null, product: BillingProductV2AddonType | BillingProductV2Type): boolean =>
                !!billing?.products?.some((p) => p.addons?.some((addon) => addon.type === product?.type)),
        ],
        productsToDeactivate: [
            (s, p) => [s.billing, s.isAddonProduct, p.product],
            (
                billing: BillingType | null,
                isAddonProduct: boolean,
                product: BillingProductV2AddonType | BillingProductV2Type
            ): string => (billing?.subscription_level === 'paid' && !isAddonProduct ? 'all_products' : product.type),
        ],
        eventsRetentionPlansAfterUnsubscribe: [
            (s, p) => [
                p.product,
                s.productsToDeactivate,
                s.productAnalyticsFreePlan,
                s.productAnalyticsPlanAfterPackageDowngrade,
                s.currentPlatformAddonPlan,
            ],
            (
                product: BillingProductV2AddonType | BillingProductV2Type,
                productsToDeactivate: string,
                productAnalyticsFreePlan: BillingPlanType | null,
                productAnalyticsPlanAfterPackageDowngrade: BillingPlanType | null,
                currentPlatformAddonPlan: BillingPlanType | null
            ): (BillingPlanType | null)[] | null => {
                if (isPlatformAndSupportAddon(product)) {
                    return [productAnalyticsPlanAfterPackageDowngrade]
                }
                if (productsToDeactivate === 'all_products') {
                    return [productAnalyticsFreePlan]
                }
                if (productsToDeactivate === ProductKey.PRODUCT_ANALYTICS) {
                    return [productAnalyticsFreePlan, currentPlatformAddonPlan]
                }
                return null
            },
        ],
        unsubscribeReasonQuestions: [
            (s) => [s.surveyResponse],
            (surveyResponse: { $survey_response: string; $survey_response_2: string[] }): string => {
                return surveyResponse['$survey_response_2']
                    .map((reason) => {
                        const reasonObject = UNSUBSCRIBE_REASONS.find((r) => r.reason === reason)
                        return reasonObject?.question
                    })
                    .join('\n')
            },
        ],
        trialCancelReasonQuestions: [
            (s) => [s.surveyResponse],
            (surveyResponse: { $survey_response: string; $survey_response_2: string[] }): string => {
                return surveyResponse['$survey_response_2']
                    .map((reason) => {
                        const reasonObject = TRIAL_CANCEL_REASONS.find((r) => r.reason === reason)
                        return reasonObject?.question
                    })
                    .join('\n')
            },
        ],
        isProductWithVariants: [
            (_s, p) => [p.product],
            (product: BillingProductV2AddonType | BillingProductV2Type): boolean =>
                isProductVariantPrimary(product.type) && 'addons' in product && product.addons?.length > 0,
        ],
        projectedAmountExcludingAddons: [
            (s, p) => [s.isProductWithVariants, p.product],
            (isProductWithVariants: boolean, product: BillingProductV2AddonType | BillingProductV2Type): string => {
                if (!isProductWithVariants) {
                    return product.projected_amount_usd || '0'
                }

                const mainProduct = product as BillingProductV2Type
                const totalProjected = parseFloat(mainProduct.projected_amount_usd || '0')

                if (!mainProduct.addons?.length) {
                    return totalProjected.toFixed(2)
                }

                const addonProjected = mainProduct.addons.reduce(
                    (sum: number, addon: BillingProductV2AddonType) =>
                        sum + parseFloat(addon.projected_amount_usd || '0'),
                    0
                )

                return Math.max(0, totalProjected - addonProjected).toFixed(2)
            },
        ],
        productVariants: [
            (s, p) => [s.isProductWithVariants, p.product],
            (
                isProductWithVariants: boolean,
                product: BillingProductV2Type
            ): Array<{
                key: string
                product: BillingProductV2Type | BillingProductV2AddonType
                displayName: string
            }> | null => {
                if (!isProductWithVariants) {
                    return null
                }

                const mainProduct = product as BillingProductV2Type
                const variants: Array<{
                    key: string
                    product: BillingProductV2Type | BillingProductV2AddonType
                    displayName: string
                }> = [
                    {
                        key: mainProduct.type,
                        product: mainProduct as BillingProductV2Type | BillingProductV2AddonType,
                        displayName: billingProductRowDisplayName(mainProduct),
                    },
                ]

                // Billing lists every offered add-on. A free-plan add-on has no price, so `subscribed` alone misses it.
                const heldAddons = mainProduct.addons?.filter(
                    (addon) => addon.subscribed || addon.plans?.some((plan) => plan.current_plan)
                )

                heldAddons?.forEach((addon) => {
                    variants.push({
                        key: addon.type,
                        product: addon as BillingProductV2Type | BillingProductV2AddonType,
                        displayName: billingProductRowDisplayName(addon),
                    })
                })

                return variants
            },
        ],
        combinedMonetaryData: [
            (s, p) => [s.customLimitUsd, p.product, s.billing],
            (limit: number | null, product: BillingProductV2Type, billing: BillingType | null) => {
                const mainProduct = product as BillingProductV2Type
                const discountPercent = billing?.discount_percent || 0
                const discountMultiplier = 1 - discountPercent / 100

                return {
                    currentTotal: parseFloat(mainProduct.current_amount_usd || '0') * discountMultiplier,
                    projectedTotal: parseFloat(mainProduct.projected_amount_usd_with_limit || '0') * discountMultiplier,
                    billingLimit: limit,
                    discountPercent,
                    rawCurrentTotal: mainProduct.current_amount_usd || '0',
                    rawProjectedTotal: mainProduct.projected_amount_usd_with_limit || '0',
                }
            },
        ],
        combinedMonetaryGaugeItems: [
            (s) => [s.combinedMonetaryData],
            (monetaryData: {
                currentTotal: number
                projectedTotal: number
                billingLimit?: number | null
            }): BillingGaugeItemType[] => {
                const { currentTotal, projectedTotal, billingLimit } = monetaryData

                return [
                    billingLimit && {
                        type: BillingGaugeItemKind.BillingLimit,
                        text: 'Billing limit',
                        value: parseFloat(billingLimit.toFixed(2)),
                        prefix: '$',
                    },
                    {
                        type: BillingGaugeItemKind.ProjectedUsage,
                        text: 'Projected',
                        value: parseFloat(projectedTotal.toFixed(2)),
                        prefix: '$',
                    },
                    {
                        type: BillingGaugeItemKind.CurrentUsage,
                        text: 'Current',
                        value: parseFloat(currentTotal.toFixed(2)),
                        prefix: '$',
                    },
                ].filter(Boolean) as BillingGaugeItemType[]
            },
        ],
        heldCompanions: [
            (s, p) => [s.billing, p.product],
            (
                billing: BillingType | null,
                product: BillingProductV2Type | BillingProductV2AddonType
            ): BillingProductV2Type[] => getHeldCompanions(billing?.products, product.type),
        ],
        noLimitCompanionAmounts: [
            (s) => [s.heldCompanions, s.combinedMonetaryData, s.featureFlags],
            (
                heldCompanions: BillingProductV2Type[],
                monetaryData: { discountPercent: number },
                featureFlags: FeatureFlagsSet
            ): { companion: BillingProductV2Type; currentAmount: number; projectedAmount: number }[] => {
                const discountMultiplier = 1 - monetaryData.discountPercent / 100
                // A companion that can have its own billing limit gets its own look later.
                return heldCompanions
                    .filter((companion) => !canHaveBillingLimit(companion))
                    .filter(
                        (companion) => featureFlags[`billing_hide_product_${companion.type}` as FeatureFlagKey] !== true
                    )
                    .map((companion) => ({
                        companion,
                        currentAmount: roundToCents(
                            parseFloat(companion.current_amount_usd || '0') * discountMultiplier
                        ),
                        projectedAmount: roundToCents(
                            parseFloat(companion.projected_amount_usd || '0') * discountMultiplier
                        ),
                    }))
            },
        ],
        totalsIncludingCompanions: [
            (s) => [s.combinedMonetaryData, s.noLimitCompanionAmounts],
            (
                monetaryData: { currentTotal: number; projectedTotal: number },
                noLimitCompanionAmounts: { currentAmount: number; projectedAmount: number }[]
            ): { currentTotal: number; projectedTotal: number } =>
                // Sum the amounts as the card shows them, in cents, so the total matches the figures above it.
                noLimitCompanionAmounts.reduce(
                    (totals, amounts) => ({
                        currentTotal: totals.currentTotal + amounts.currentAmount,
                        projectedTotal: totals.projectedTotal + amounts.projectedAmount,
                    }),
                    {
                        currentTotal: roundToCents(monetaryData.currentTotal),
                        projectedTotal: roundToCents(monetaryData.projectedTotal),
                    }
                ),
        ],
        currentAmountTotalActual: [
            (s, p) => [s.isProductWithVariants, p.product, s.visibleAddons],
            (
                isProductWithVariants: boolean,
                product: BillingProductV2AddonType | BillingProductV2Type,
                visibleAddons: BillingProductV2AddonType[]
            ): string => {
                if (!product.tiers) {
                    return '0.00'
                }

                // Calculate base product total from tiers
                const productTotal = product.tiers.reduce(
                    (sum, tier) => sum + parseFloat(tier.current_amount_usd || '0'),
                    0
                )

                // For variants, return just the product total (addons shown separately)
                if (isProductWithVariants) {
                    return productTotal.toFixed(2)
                }

                // For non-variants, include addon totals
                const addonTotal =
                    visibleAddons?.reduce(
                        (addonSum, addon) =>
                            addonSum +
                            (addon.tiers?.reduce(
                                (tierSum, tier) => tierSum + parseFloat(tier.current_amount_usd || '0'),
                                0
                            ) || 0),
                        0
                    ) || 0

                return (productTotal + addonTotal).toFixed(2)
            },
        ],
    })),
    listeners(({ actions, values, props }) => ({
        updateBillingLimitsSuccess: () => {
            actions.billingLoaded()
        },
        billingLoaded: () => {
            function calculateDefaultBillingLimit(product: BillingProductV2Type | BillingProductV2AddonType): number {
                const projectedAmount = parseInt(product.projected_amount_usd || '0')
                return product.tiers && projectedAmount ? projectedAmount * 1.5 : DEFAULT_BILLING_LIMIT
            }
            actions.setIsEditingBillingLimit(false)
            actions.setBillingLimitInput(
                values.hasCustomLimitSet ? values.customLimitUsd : calculateDefaultBillingLimit(props.product)
            )
        },
        reportSurveyShown: ({ surveyID }) => {
            posthog.capture(SurveyEventName.SHOWN, {
                $survey_id: surveyID,
            })
            actions.setSurveyID(surveyID)
        },
        reportSurveySent: ({ surveyID, surveyResponse }) => {
            // @note(zach): this is submitting to https://us.posthog.com/project/2/surveys/018b6e13-590c-0000-decb-c727a2b3f462?edit=true
            // $survey_response: open text response
            // $survey_response_1: this is the product type
            // $survey_response_2: list of reasons
            // The order is due to the form being built before reasons we're supported. Please do not change the order.
            posthog.capture(SurveyEventName.SENT, {
                $survey_id: surveyID,
                ...surveyResponse,
            })
            actions.setSurveyID('')
        },
        reportSurveyDismissed: ({ surveyID }) => {
            posthog.capture(SurveyEventName.DISMISSED, {
                $survey_id: surveyID,
            })
            actions.setSurveyID('')
        },
        deactivateProductSuccess: async (_, breakpoint) => {
            if (!values.unsubscribeError && values.surveyID) {
                actions.reportSurveySent(values.surveyID, values.surveyResponse)
                await breakpoint(400)
                document.getElementsByClassName('Navigation3000__scene')[0]?.scrollIntoView()
            }
        },
        setScrollToProductKey: ({ scrollToProductKey }) => {
            // Scroll to the product or parent product
            if (scrollToProductKey && scrollToProductKey === props.product.type) {
                setTimeout(() => {
                    if (props.productRef?.current) {
                        props.productRef?.current.scrollIntoView({
                            behavior: 'smooth',
                            block: 'center',
                        })
                        actions.setScrollToProductKey(null)
                    }
                }, 0)
            }
        },
        initiateProductUpgrade: ({ plan, product, redirectPath }) => {
            actions.setBillingProductLoading(product.type)
            const products = `${product.type}:${plan?.plan_key}`
            actions.handleProductUpgrade(products, redirectPath)
        },
        handleProductUpgrade: async ({ products, redirectPath }) => {
            try {
                if (values.selfServeBillingNotice) {
                    lemonToast.info(values.selfServeBillingNotice)
                    return
                }
                await paymentEntryLogic.asyncActions.upgradeProducts(products, redirectPath || null)
            } finally {
                actions.setBillingProductLoading(null)
            }
        },
        confirmProductUpgrade: () => {
            const upgradePlan = values.currentAndUpgradePlans.upgradePlan
            const currentPlatformAddon = values.currentPlatformAddon
            if (!upgradePlan || !currentPlatformAddon) {
                return
            }
            const currentPlanKey =
                currentPlatformAddon.plans?.find((p) => p.current_plan)?.plan_key ||
                currentPlatformAddon.plans?.[0]?.plan_key
            actions.switchFlatrateSubscriptionPlan({
                from_product_key: String(currentPlatformAddon.type),
                from_plan_key: String(currentPlanKey),
                to_product_key: props.product.type,
                to_plan_key: String(upgradePlan.plan_key),
            })
        },
        confirmProductPurchase: () => {
            const upgradePlan = values.currentAndUpgradePlans.upgradePlan
            if (!upgradePlan) {
                return
            }
            // Fresh flat-rate add-on purchase (nothing to switch from). Fire the same activation
            // the "Add" button used to trigger directly — now gated behind the confirmation modal
            // so a card-on-file customer sees what they'll be charged before it happens.
            actions.initiateProductUpgrade(props.product, upgradePlan, '')
        },
        confirmProductDowngrade: () => {
            const targetPlan = values.currentAndUpgradePlans.upgradePlan
            const currentPlatformAddon = values.currentPlatformAddon
            if (!targetPlan || !currentPlatformAddon) {
                return
            }
            const currentPlanKey =
                currentPlatformAddon.plans?.find((p) => p.current_plan)?.plan_key ||
                currentPlatformAddon.plans?.[0]?.plan_key
            actions.switchFlatrateSubscriptionPlan({
                from_product_key: String(currentPlatformAddon.type),
                from_plan_key: String(currentPlanKey),
                to_product_key: props.product.type,
                to_plan_key: String(targetPlan.plan_key),
            })
        },
        setSwitchPlanLoading: ({ productKey }) => {
            if (productKey === null) {
                if (values.confirmUpgradeModalOpen) {
                    actions.hideConfirmUpgradeModal()
                }
                if (values.confirmDowngradeModalOpen) {
                    actions.hideConfirmDowngradeModal()
                }
            }
        },
        activateTrial: async (_, breakpoint) => {
            actions.setTrialLoading(true)
            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingTrialsActivateCreate() from 'products/billing/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                await api.create(`api/billing/trials/activate`, {
                    type: 'autosubscribe',
                    target: props.product.type,
                })
                lemonToast.success('Your trial has been activated!')
                await breakpoint(400)
                window.location.reload()
            } catch {
                lemonToast.error('There was an error activating your trial. Please try again or contact support.')
                actions.setTrialLoading(false)
                actions.loadBilling()
            }
        },
        cancelTrial: async (_, breakpoint) => {
            actions.setTrialLoading(true)
            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingTrialsCancelCreate() from 'products/billing/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                await api.create(`api/billing/trials/cancel`)
                lemonToast.success('Your trial has been cancelled!')
                if (values.surveyID) {
                    actions.reportSurveySent(values.surveyID, values.surveyResponse)
                }
                await breakpoint(1000)
                window.location.reload()
            } catch {
                lemonToast.error('There was an error cancelling your trial. Please try again or contact support.')
                actions.setTrialLoading(false)
                actions.loadBilling()
            }
        },
        triggerMoreHedgehogs: async (_, breakpoint) => {
            for (let i = 0; i < 5; i++) {
                props.hogfettiTrigger?.()
                await breakpoint(200)
            }
        },
        removeBillingLimitNextPeriod: async ({ productType }) => {
            actions.setRemovingBillingLimitNextPeriod(true)
            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                await api.update('api/billing', { reset_limit_next_period: productType })
                lemonToast.success('Billing limit for next period has been removed.')
            } catch (error) {
                console.error(error)
                lemonToast.error(
                    'There was an error removing your billing limit for next period. Please try again or contact support.'
                )
            } finally {
                actions.setRemovingBillingLimitNextPeriod(false)
                actions.loadBilling()
            }
        },
    })),
    forms(({ actions, props, values }) => ({
        billingLimitInput: {
            errors: ({ input }) => ({
                input:
                    input === null || Number.isInteger(input)
                        ? input > values.billingLimitConfig.max
                            ? values.billingLimitConfig.maxExceededError
                            : undefined
                        : 'Please enter a whole number',
            }),
            submit: async ({ input }) => {
                const currentAmountUsd = props.product.current_amount_usd
                    ? parseFloat(props.product.current_amount_usd)
                    : null
                const projectedAmountUsd = props.product.projected_amount_usd
                    ? parseFloat(props.product.projected_amount_usd)
                    : null

                if (input !== null && currentAmountUsd !== null && input < currentAmountUsd) {
                    LemonDialog.open({
                        maxWidth: '600px',
                        title: 'Billing limit warning',
                        description:
                            "The billing limit you set is below your current usage. If you proceed, your current period's limit will be set to your current usage (to prevent additional charges), and the new lower limit will go into effect in your next billing period. Are you sure you want to proceed?",
                        primaryButton: {
                            status: 'danger',
                            children: 'Yes, I understand',
                            onClick: () =>
                                actions.updateBillingLimits({
                                    [props.product.type]: input,
                                }),
                        },
                        secondaryButton: {
                            children: 'No, I changed my mind',
                        },
                    })
                    return
                }

                if (input !== null && projectedAmountUsd !== null && input < projectedAmountUsd) {
                    LemonDialog.open({
                        maxWidth: '600px',
                        title: 'Billing limit warning',
                        description:
                            'Your predicted usage is above your billing limit which is likely to result in usage being throttled and data being dropped. Are you sure you want to proceed?',
                        primaryButton: {
                            status: 'danger',
                            children: 'Yes, I understand',
                            onClick: () =>
                                actions.updateBillingLimits({
                                    [props.product.type]: input,
                                }),
                        },
                        secondaryButton: {
                            children: 'No, I changed my mind',
                        },
                    })
                    return
                }
                actions.updateBillingLimits({
                    [props.product.type]: input,
                })
            },
            options: {
                alwaysShowErrors: true,
            },
        },
    })),
    events(({ actions, values, props }) => ({
        afterMount: () => {
            if (values.scrollToProductKey === props.product.type) {
                actions.setScrollToProductKey(values.scrollToProductKey)
            }
            actions.billingLoaded()
        },
    })),
])