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.0 KB
Raw Blame
import clsx from 'clsx'
import { BuiltLogic, LogicWrapper, useActions, useValues } from 'kea'
import { useCallback, useMemo } from 'react'

import * as starPng from '@posthog/brand/hoggies/png/star'
import { IconChevronDown, IconTrending, IconUndo, IconWarning } from '@posthog/icons'
import { LemonSegmentedButton, LemonSelect, Link, Tooltip } from '@posthog/lemon-ui'

import { pngHoggie } from 'lib/brand/hoggies'
import { getColorVar } from 'lib/colors'
import { IntervalFilterStandalone } from 'lib/components/IntervalFilter'
import { parseAliasToReadable } from 'lib/components/PathCleanFilters/PathCleanFilterItem'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
import { PropertyIcon } from 'lib/components/PropertyIcon/PropertyIcon'
import { TZLabel } from 'lib/components/TZLabel'
import { FEATURE_FLAGS } from 'lib/constants'
import { IconOpenInNew, IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import {
    COUNTRY_CODE_TO_LONG_NAME,
    LANGUAGE_CODE_TO_NAME,
    countryCodeToFlag,
    languageCodeToFlag,
} from 'lib/utils/country'
import { humanFriendlyDuration } from 'lib/utils/durations'
import { UnexpectedNeverError } from 'lib/utils/guards'
import { percentage } from 'lib/utils/numbers'
import { tryDecodeURIComponent } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { botAnalyticsLogic } from 'scenes/web-analytics/botAnalyticsLogic'
import {
    BREAKDOWN_NULL_DISPLAY,
    BREAKDOWN_REFERRER_PREFIX,
    DEVICE_DRILL_DOWN_MAP,
    GEOGRAPHY_DRILL_DOWN_MAP,
    GeographyTab,
    ProductTab,
    SOURCE_DRILL_DOWN_MAP,
    SourceTab,
    TileId,
    faviconUrl,
    webStatsBreakdownToPropertyName,
} from 'scenes/web-analytics/common'
import {
    buildDataTableTileDataNodeLogicProps,
    buildInsightVizTileDataNodeLogicProps,
    ChartTileSkeleton,
    TableTileSkeleton,
    WebAnalyticsTileSkeletonGate,
    WorldMapTileSkeleton,
} from 'scenes/web-analytics/tiles/skeletons'
import { webAnalyticsFilterLogic } from 'scenes/web-analytics/webAnalyticsFilterLogic'
import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'

import { actionsModel } from '~/models/actionsModel'
import { Query } from '~/queries/Query/Query'
import {
    DataTableNode,
    DataVisualizationNode,
    VisualizationNode,
    InsightVizNode,
    MarketingAnalyticsColumnsSchemaNames,
    NodeKind,
    ProductIntentContext,
    ProductKey,
    QuerySchema,
    WebAnalyticsOrderByFields,
    WebAnalyticsPropertyFilters,
    WebStatsBreakdown,
    WebVitalsPathBreakdownQuery,
} from '~/queries/schema/schema-general'
import { QueryContext, QueryContextColumnComponent, QueryContextColumnTitleComponent } from '~/queries/types'
import { ChartDisplayType, InsightLogicProps, PropertyFilterType, PropertyOperator } from '~/types'

import { NewActionButton } from 'products/actions/frontend/components/NewActionButton'
import { MarketingAnalyticsAdSpendLink } from 'products/web_analytics/frontend/marketing/MarketingAnalyticsAdSpendLink'
import { MarketingAnalyticsCrossSell } from 'products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSell'

import { CreateSurveyButton } from '../CrossSellButtons/CreateSurveyButton'
import { ErrorTrackingButton } from '../CrossSellButtons/ErrorTrackingButton'
import { HeatmapButton } from '../CrossSellButtons/HeatmapButton'
import { ReplayButton } from '../CrossSellButtons/ReplayButton'
import { pageReportsLogic } from '../pageReportsLogic'
import { MarketingAnalyticsTable } from '../tabs/marketing-analytics/frontend/components/MarketingAnalyticsTable/MarketingAnalyticsTable'
import { marketingAnalyticsLogic } from '../tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
import { validColumnsForTiles } from '../tabs/marketing-analytics/frontend/logic/utils'
import { DISPLAY_MODE_OPTIONS } from '../tabs/marketing-analytics/frontend/shared'

export const toUtcOffsetFormat = (value: number): string => {
    if (value === 0) {
        return 'UTC'
    }

    const sign = value > 0 ? '+' : '-'
    const integerPart = Math.abs(Math.trunc(value))

    // India has half-hour offsets, and Australia has 45-minute offsets, why?
    const decimalPart = Math.abs(value) - integerPart
    const decimalPartAsMinutes = decimalPart * 60
    const formattedMinutes = decimalPartAsMinutes > 0 ? `:${decimalPartAsMinutes}` : ''

    // E.g. UTC-3, UTC, UTC+5:30, UTC+11:45
    return `UTC${sign}${integerPart}${formattedMinutes}`
}

const PAGE_LIKE_BREAKDOWNS = new Set([
    WebStatsBreakdown.Page,
    WebStatsBreakdown.InitialPage,
    WebStatsBreakdown.ExitPage,
    WebStatsBreakdown.ExitClick,
    WebStatsBreakdown.FrustrationMetrics,
])

const HedgehogStar = pngHoggie(starPng)

// Outbound clicks come through as a `url` column, which the default renderer would turn into a link.
const UrlValueCell: QueryContextColumnComponent = ({ value }) => <>{value}</>

type VariationCellProps = {
    isPercentage?: boolean
    reverseColors?: boolean
    isDuration?: boolean
    reserveTrendSpace?: boolean
    neutral?: boolean
    formatValue?: (value: number) => string
}

export function comparisonTooltipText(
    current: number,
    previous: number | null,
    compare: boolean,
    formatNumber: (value: number) => string
): string | null {
    if (!compare || previous === null) {
        return null
    }
    if (current === previous) {
        return `No change since last period (${formatNumber(current)})`
    }
    if (previous === 0) {
        return `Increased from ${formatNumber(previous)} to ${formatNumber(current)} since last period`
    }
    return `${current > previous ? 'Increased' : 'Decreased'} by ${percentage(
        Math.abs(current / previous - 1),
        0
    )} since last period (from ${formatNumber(previous)} to ${formatNumber(current)})`
}

export const VariationCell = (
    { isPercentage, reverseColors, isDuration, reserveTrendSpace = true, neutral, formatValue }: VariationCellProps = {
        isPercentage: false,
        reverseColors: false,
        isDuration: false,
    }
) => {
    const formatNumber = (value: number): string => {
        if (formatValue) {
            return formatValue(value)
        }
        if (isPercentage) {
            return `${(value * 100).toFixed(1)}%`
        } else if (isDuration) {
            return humanFriendlyDuration(value)
        }
        return value?.toLocaleString() ?? '(empty)'
    }

    return function Cell({
        value,
        context,
        tooltipContent,
    }: {
        value: unknown
        context?: QueryContext
        tooltipContent?: React.ReactNode
    }) {
        const compareFilter = context?.compareFilter

        if (!value) {
            return null
        }

        if (!Array.isArray(value)) {
            return <span>{String(value)}</span>
        }

        const [current, previous] = value as [number, number | null]
        const hasComparison = previous !== null && compareFilter?.compare === true
        const difference = hasComparison ? current - previous : null

        const trend =
            difference === null
                ? null
                : difference === 0
                  ? { Icon: IconTrendingFlat, color: getColorVar('muted') }
                  : difference > 0
                    ? {
                          Icon: IconTrending,
                          color: reverseColors ? getColorVar('danger') : getColorVar('success'),
                      }
                    : {
                          Icon: IconTrendingDown,
                          color: reverseColors ? getColorVar('success') : getColorVar('danger'),
                      }

        const trendColor = neutral ? getColorVar('muted') : trend?.color

        const comparisonTooltip = comparisonTooltipText(current, previous, hasComparison, formatNumber)
        const tooltip =
            comparisonTooltip && tooltipContent ? (
                <div className="flex flex-col gap-1">
                    <div>{comparisonTooltip}</div>
                    <div>{tooltipContent}</div>
                </div>
            ) : (
                (comparisonTooltip ?? tooltipContent)
            )

        return (
            <div className={clsx({ 'pr-4': !trend && reserveTrendSpace })}>
                <Tooltip title={tooltip}>
                    <span>
                        {formatNumber(current)}
                        {(reserveTrendSpace || trend) && '\u00a0'}
                        {trend && (
                            // eslint-disable-next-line react/forbid-dom-props
                            <span style={{ color: trendColor }}>
                                <trend.Icon color={trendColor} className="ml-1" />
                            </span>
                        )}
                    </span>
                </Tooltip>
            </div>
        )
    }
}

const BreakdownValueTitle: QueryContextColumnTitleComponent = (props) => {
    const { query } = props
    const { source } = query
    if (source.kind !== NodeKind.WebStatsTableQuery) {
        return null
    }
    const { breakdownBy, includeHost } = source
    switch (breakdownBy) {
        case WebStatsBreakdown.Page:
            return <>{includeHost ? 'Host + path' : 'Path'}</>
        case WebStatsBreakdown.InitialPage:
            return <>{includeHost ? 'Host + entry path' : 'Initial Path'}</>
        case WebStatsBreakdown.ExitPage:
            return <>{includeHost ? 'Host + end path' : 'End Path'}</>
        case WebStatsBreakdown.PreviousPage:
            return <>Previous Page</>
        case WebStatsBreakdown.ExitClick:
            return <>Exit Click</>
        case WebStatsBreakdown.ScreenName:
            return <>Screen Name</>
        case WebStatsBreakdown.InitialChannelType:
            return <>Channel Type</>
        case WebStatsBreakdown.InitialReferringDomain:
            return <>Referring Domain</>
        case WebStatsBreakdown.InitialReferringURL:
            return <>Referring URL</>
        case WebStatsBreakdown.InitialUTMSource:
            return <>UTM Source</>
        case WebStatsBreakdown.InitialUTMCampaign:
            return <>UTM Campaign</>
        case WebStatsBreakdown.InitialUTMMedium:
            return <>UTM Medium</>
        case WebStatsBreakdown.InitialUTMTerm:
            return <>UTM Term</>
        case WebStatsBreakdown.InitialUTMContent:
            return <>UTM Content</>
        case WebStatsBreakdown.Browser:
            return <>Browser</>
        case WebStatsBreakdown.InAppBrowser:
            return <>In-app browser</>
        case WebStatsBreakdown.OS:
            return <>OS</>
        case WebStatsBreakdown.Viewport:
            return <>Viewport</>
        case WebStatsBreakdown.DeviceType:
            return <>Device Type</>
        case WebStatsBreakdown.Country:
            return <>Country</>
        case WebStatsBreakdown.Region:
            return <>Region</>
        case WebStatsBreakdown.City:
            return <>City</>
        case WebStatsBreakdown.Timezone:
            return <>Timezone</>
        case WebStatsBreakdown.Language:
            return <>Language</>
        case WebStatsBreakdown.FrustrationMetrics:
            return <>URL</>
        case WebStatsBreakdown.InitialUTMSourceMediumCampaign:
            return <>Source / Medium / Campaign</>
        case WebStatsBreakdown.FirstPageviewChannelType:
            return <>Channel Type (First Pageview)</>
        case WebStatsBreakdown.FirstPageviewReferringDomain:
            return <>Referring Domain (First Pageview)</>
        case WebStatsBreakdown.FirstPageviewUTMSource:
            return <>UTM Source (First Pageview)</>
        case WebStatsBreakdown.FirstPageviewUTMCampaign:
            return <>UTM Campaign (First Pageview)</>
        case WebStatsBreakdown.FirstPageviewUTMMedium:
            return <>UTM Medium (First Pageview)</>
        case WebStatsBreakdown.FirstPageviewUTMTerm:
            return <>UTM Term (First Pageview)</>
        case WebStatsBreakdown.FirstPageviewUTMContent:
            return <>UTM Content (First Pageview)</>
        case WebStatsBreakdown.FirstPageviewUTMSourceMediumCampaign:
            return <>Source / Medium / Campaign (First Pageview)</>
        default:
            throw new UnexpectedNeverError(breakdownBy)
    }
}

const NotSetBreakdownLabel = (): JSX.Element => <span className="text-secondary italic">(not set)</span>

const DirectBreakdownLabel = (): JSX.Element => <span className="text-secondary italic">(direct)</span>

const BreakdownValueCell: QueryContextColumnComponent = (props) => {
    const { value, query } = props
    const { source } = query
    const { featureFlags } = useValues(featureFlagLogic)

    if (source.kind !== NodeKind.WebStatsTableQuery) {
        return null
    }
    const { breakdownBy } = source

    switch (breakdownBy) {
        case WebStatsBreakdown.ExitPage:
        case WebStatsBreakdown.InitialPage:
        case WebStatsBreakdown.Page:
        case WebStatsBreakdown.FrustrationMetrics: {
            if (typeof value !== 'string') {
                return <>{value}</>
            }
            const decoded = tryDecodeURIComponent(value)
            const displayValue = source.doPathCleaning ? parseAliasToReadable(decoded) : decoded
            return <>{displayValue}</>
        }
        case WebStatsBreakdown.ExitClick: {
            if (typeof value !== 'string') {
                return <>{value}</>
            }
            return <>{value}</>
        }
        case WebStatsBreakdown.Viewport:
            if (Array.isArray(value)) {
                const [width, height] = value
                return (
                    <>
                        {width}x{height}
                    </>
                )
            }
            break
        case WebStatsBreakdown.Country:
            if (typeof value === 'string') {
                const countryCode = value
                return (
                    <>
                        {countryCodeToFlag(countryCode)} {COUNTRY_CODE_TO_LONG_NAME[countryCode] || countryCode}
                    </>
                )
            }
            return <NotSetBreakdownLabel />
        case WebStatsBreakdown.Region:
            if (Array.isArray(value)) {
                const [countryCode, regionCode, regionName] = value
                const regionLabel = regionName || regionCode
                return (
                    <>
                        {countryCodeToFlag(countryCode)} {COUNTRY_CODE_TO_LONG_NAME[countryCode] || countryCode} -{' '}
                        {regionLabel ? regionLabel : <NotSetBreakdownLabel />}
                    </>
                )
            }
            break
        case WebStatsBreakdown.City:
            if (Array.isArray(value)) {
                const [countryCode, cityName] = value
                return (
                    <>
                        {countryCodeToFlag(countryCode)} {COUNTRY_CODE_TO_LONG_NAME[countryCode] || countryCode} -{' '}
                        {cityName ? cityName : <NotSetBreakdownLabel />}
                    </>
                )
            }
            break
        case WebStatsBreakdown.Timezone:
            if (typeof value === 'number') {
                return <>{toUtcOffsetFormat(value)}</>
            }
            return <NotSetBreakdownLabel />
        case WebStatsBreakdown.Language:
            if (typeof value === 'string') {
                const [languageCode, countryCode] = value.split('-')

                // Locales are complicated, the country code might be hidden in the second part
                // of the locale
                const parsedCountryCode = countryCode?.match(/([A-Z]{2})/)?.[0] ?? ''
                return (
                    <>
                        {countryCodeToFlag(parsedCountryCode) ?? languageCodeToFlag(languageCode)}&nbsp;
                        {LANGUAGE_CODE_TO_NAME[languageCode] || languageCode}
                    </>
                )
            }
            return <NotSetBreakdownLabel />
        case WebStatsBreakdown.DeviceType:
            if (typeof value === 'string') {
                return <PropertyIcon.WithLabel property="$device_type" value={value} />
            }
            return <NotSetBreakdownLabel />
        case WebStatsBreakdown.Browser:
            if (typeof value === 'string') {
                return <PropertyIcon.WithLabel property="$browser" value={value} />
            }
            return <NotSetBreakdownLabel />
        case WebStatsBreakdown.InAppBrowser:
            if (typeof value === 'string') {
                return <>{value}</>
            }
            return <NotSetBreakdownLabel />
        case WebStatsBreakdown.OS:
            if (typeof value === 'string') {
                return <PropertyIcon.WithLabel property="$os" value={value} />
            }
            return <NotSetBreakdownLabel />
        case WebStatsBreakdown.InitialReferringDomain:
        case WebStatsBreakdown.FirstPageviewReferringDomain:
            // NULL referrer is canonically "Direct" in PostHog (matches the channel-type
            // bucketing in sessions_v2). Keep that wording to stay consistent across tiles.
            if (value == null) {
                return <DirectBreakdownLabel />
            }
            if (featureFlags[FEATURE_FLAGS.SHOW_REFERRER_FAVICON]) {
                if (typeof value === 'string') {
                    return (
                        <div className="flex items-center gap-2">
                            <img
                                src={faviconUrl(value)}
                                width={14}
                                height={14}
                                alt={`${value} favicon`}
                                onError={(e) => (e.currentTarget.style.display = 'none')}
                            />
                            {value}
                        </div>
                    )
                }
            }
            break
        case WebStatsBreakdown.InitialUTMSourceMediumCampaign:
        case WebStatsBreakdown.FirstPageviewUTMSourceMediumCampaign:
            if (typeof value === 'string') {
                return <>{value.replace(BREAKDOWN_REFERRER_PREFIX, '')}</>
            }
            break
        case WebStatsBreakdown.InitialChannelType:
        case WebStatsBreakdown.InitialUTMSource:
            if (typeof value !== 'string') {
                return breakdownBy === WebStatsBreakdown.InitialUTMSource ? <NotSetBreakdownLabel /> : null
            }
            return (
                <MarketingAnalyticsAdSpendLink breakdownBy={breakdownBy} value={value} dateRange={source.dateRange}>
                    {value}
                </MarketingAnalyticsAdSpendLink>
            )
        case WebStatsBreakdown.InitialUTMMedium:
        case WebStatsBreakdown.InitialUTMCampaign:
        case WebStatsBreakdown.InitialUTMTerm:
        case WebStatsBreakdown.InitialUTMContent:
        case WebStatsBreakdown.FirstPageviewUTMSource:
        case WebStatsBreakdown.FirstPageviewUTMMedium:
        case WebStatsBreakdown.FirstPageviewUTMCampaign:
        case WebStatsBreakdown.FirstPageviewUTMTerm:
        case WebStatsBreakdown.FirstPageviewUTMContent:
            return typeof value === 'string' ? <>{value}</> : <NotSetBreakdownLabel />
    }

    if (typeof value === 'string') {
        return <>{value}</>
    }
    return null
}

const SortableCell = (
    name: string,
    orderByField: WebAnalyticsOrderByFields,
    tooltip?: string
): QueryContextColumnTitleComponent =>
    function SortableCell() {
        const { tablesOrderBy } = useValues(webAnalyticsLogic)
        const { setTablesOrderBy } = useActions(webAnalyticsLogic)

        const isSortedByMyField = tablesOrderBy?.[0] === orderByField
        const isAscending = tablesOrderBy?.[1] === 'ASC'

        // Toggle between DESC, ASC, and no sort, in this order
        const onClick = useCallback(() => {
            if (!isSortedByMyField || isAscending) {
                setTablesOrderBy(orderByField, 'DESC')
            } else {
                setTablesOrderBy(orderByField, 'ASC')
            }
        }, [isAscending, isSortedByMyField, setTablesOrderBy])

        const content = (
            <span onClick={onClick} className="group cursor-pointer inline-flex items-center">
                {name}
                <IconChevronDown
                    fontSize="20px"
                    className={clsx('-mr-1 ml-1 text-muted-alt opacity-0 group-hover:opacity-100', {
                        'text-primary opacity-100': isSortedByMyField,
                        'rotate-180': isSortedByMyField && isAscending,
                    })}
                />
            </span>
        )

        return tooltip ? <Tooltip title={tooltip}>{content}</Tooltip> : content
    }

export const webAnalyticsDataTableQueryContext: QueryContext = {
    // findMounted() keeps this scene-agnostic: it only acts when webAnalyticsLogic is actually mounted
    // (i.e. inside the web analytics scene), so reusing this context in product analytics is a no-op.
    onDisableWebAnalyticsPrecompute: () => webAnalyticsLogic.findMounted()?.actions.setUseWebAnalyticsPrecompute(false),
    columns: {
        breakdown_value: {
            renderTitle: BreakdownValueTitle,
            render: BreakdownValueCell,
        },
        bounce_rate: {
            renderTitle: SortableCell('Bounce Rate', WebAnalyticsOrderByFields.BounceRate),
            render: VariationCell({ isPercentage: true, reverseColors: true }),
            align: 'right',
        },
        avg_time_on_page: {
            renderTitle: SortableCell(
                'Time on Page',
                WebAnalyticsOrderByFields.AvgTimeOnPage,
                'The 90th percentile of time users spent on this page'
            ),
            render: VariationCell({ isDuration: true }),
            align: 'right',
        },
        views: {
            renderTitle: SortableCell('Views', WebAnalyticsOrderByFields.Views),
            render: VariationCell(),
            align: 'right',
        },
        clicks: {
            renderTitle: SortableCell('Clicks', WebAnalyticsOrderByFields.Clicks),
            render: VariationCell(),
            align: 'right',
        },
        visitors: {
            renderTitle: SortableCell('Visitors', WebAnalyticsOrderByFields.Visitors),
            render: VariationCell(),
            align: 'right',
        },
        average_scroll_percentage: {
            renderTitle: SortableCell('Average Scroll', WebAnalyticsOrderByFields.AverageScrollPercentage),
            render: VariationCell({ isPercentage: true }),
            align: 'right',
        },
        scroll_gt80_percentage: {
            renderTitle: SortableCell('Deep Scroll Rate', WebAnalyticsOrderByFields.ScrollGt80Percentage),
            render: VariationCell({ isPercentage: true }),
            align: 'right',
        },
        total_conversions: {
            renderTitle: SortableCell('Conversions', WebAnalyticsOrderByFields.TotalConversions),
            render: VariationCell(),
            align: 'right',
        },
        unique_conversions: {
            renderTitle: SortableCell('Uniques', WebAnalyticsOrderByFields.UniqueConversions),
            render: VariationCell(),
            align: 'right',
        },
        conversion_rate: {
            renderTitle: SortableCell('CR', WebAnalyticsOrderByFields.ConversionRate),
            render: VariationCell({ isPercentage: true }),
            align: 'right',
        },
        rage_clicks: {
            renderTitle: SortableCell('Rage Clicks', WebAnalyticsOrderByFields.RageClicks),
            render: VariationCell(),
            align: 'right',
        },
        dead_clicks: {
            renderTitle: SortableCell('Dead Clicks', WebAnalyticsOrderByFields.DeadClicks),
            render: VariationCell(),
            align: 'right',
        },
        errors: {
            renderTitle: SortableCell('Errors', WebAnalyticsOrderByFields.Errors),
            render: VariationCell(),
            align: 'right',
        },
        converting_users: {
            renderTitle: SortableCell('Converting Users', WebAnalyticsOrderByFields.ConvertingUsers),
            render: VariationCell(),
            align: 'right',
        },
        url: {
            render: UrlValueCell,
        },
        'Last seen': {
            render: ({ value }) => (typeof value === 'string' ? <TZLabel time={value} /> : <>{value}</>),
        },
        action_name: {
            title: 'Action',
        },
        cross_sell: {
            title: ' ',
            render: ({ record, query }: { record: any; query: DataTableNode | VisualizationNode }) => {
                const source = query.source as any
                const dateRange = source?.dateRange
                const breakdownBy = source?.breakdownBy
                const value = record[0] ?? ''
                const doPathCleaning = source?.doPathCleaning

                return (
                    <div className="flex flex-row items-center justify-end">
                        <ReplayButton
                            date_from={dateRange?.date_from}
                            date_to={dateRange?.date_to}
                            breakdownBy={breakdownBy}
                            value={value}
                            properties={source?.properties}
                            filter_test_accounts={source?.filterTestAccounts}
                            doPathCleaning={doPathCleaning}
                        />
                        <HeatmapButton breakdownBy={breakdownBy} value={value} />
                        <ErrorTrackingButton breakdownBy={breakdownBy} value={value} doPathCleaning={doPathCleaning} />
                        <CreateSurveyButton value={value} />
                    </div>
                )
            },
            align: 'right',
        },
        ui_fill_fraction: {
            hidden: true,
            isRowFillFraction: true,
        },
    },
}

type QueryWithInsightProps<Q extends QuerySchema> = {
    query: Q
    insightProps: InsightLogicProps
    attachTo?: LogicWrapper | BuiltLogic
}

export const WebStatsTrendTile = ({
    query,
    showIntervalTile,
    insightProps,
    attachTo,
    headerSlot,
    uniqueKey,
}: QueryWithInsightProps<InsightVizNode> & {
    showIntervalTile?: boolean
    headerSlot?: React.ReactNode
    uniqueKey: string
}): JSX.Element => {
    const { togglePropertyFilter, setDateInterval, zoomIntoPeriod, resetZoom } = useActions(webAnalyticsLogic)
    const {
        hasCountryFilter,
        dateFilter: { interval },
        preZoomDateFilter,
    } = useValues(webAnalyticsLogic)
    const { featureFlags } = useValues(featureFlagLogic)
    const isDragToZoomEnabled = !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_DRAG_TO_ZOOM]
    const worldMapPropertyName = webStatsBreakdownToPropertyName(WebStatsBreakdown.Country)?.key
    const regionPropertyName = webStatsBreakdownToPropertyName(WebStatsBreakdown.Region)?.key

    const isWorldMap =
        query.source?.kind === NodeKind.TrendsQuery && query.source.trendsFilter?.display === ChartDisplayType.WorldMap
    const insightPropsForQuery = useMemo(
        (): InsightLogicProps => ({
            ...insightProps,
            query,
        }),
        [insightProps, query]
    )
    const dataNodeLogicProps = buildInsightVizTileDataNodeLogicProps({
        query,
        insightProps: insightPropsForQuery,
    })

    const onWorldMapClick = useCallback(
        (breakdownValue: string) => {
            if (!worldMapPropertyName) {
                return
            }
            togglePropertyFilter(PropertyFilterType.Event, worldMapPropertyName, breakdownValue, {
                geographyTab: hasCountryFilter ? undefined : GeographyTab.REGIONS,
            })
        },
        [togglePropertyFilter, worldMapPropertyName, hasCountryFilter]
    )

    const onRegionMapClick = useCallback(
        (breakdownValue: string) => {
            if (!regionPropertyName || !worldMapPropertyName) {
                return
            }

            const [countryCode, subdivisionCode] = breakdownValue.split('::')
            if (countryCode && subdivisionCode) {
                togglePropertyFilter(PropertyFilterType.Event, worldMapPropertyName, countryCode)
                togglePropertyFilter(PropertyFilterType.Event, regionPropertyName, subdivisionCode)
            }
        },
        [togglePropertyFilter, regionPropertyName, worldMapPropertyName]
    )

    const context = useMemo((): QueryContext => {
        const compareFilter = 'compareFilter' in query.source ? query.source.compareFilter : undefined

        const baseContext: QueryContext = {
            ...webAnalyticsDataTableQueryContext,
            insightProps: {
                ...insightPropsForQuery,
            },
            compareFilter,
            onDateRangeZoom: isDragToZoomEnabled ? zoomIntoPeriod : undefined,
        }

        // World maps need custom click handler for country filtering, trend lines use default persons modal
        const isRegionMap =
            isWorldMap &&
            query.source?.kind === NodeKind.TrendsQuery &&
            query.source.breakdownFilter?.breakdowns &&
            query.source.breakdownFilter.breakdowns.length >= 2 &&
            query.source.breakdownFilter.breakdowns.some(
                (b) => b.property === '$geoip_subdivision_1_code' || b.property === '$geoip_subdivision_1_name'
            )

        if (isRegionMap) {
            return {
                ...baseContext,
                onDataPointClick({ breakdown }, data) {
                    if (typeof breakdown === 'string' && data && (data.count > 0 || data.aggregated_value > 0)) {
                        onRegionMapClick(breakdown)
                    }
                },
            }
        }

        if (isWorldMap) {
            return {
                ...baseContext,
                onDataPointClick({ breakdown }, data) {
                    if (typeof breakdown === 'string' && data && (data.count > 0 || data.aggregated_value > 0)) {
                        onWorldMapClick(breakdown)
                    }
                },
            }
        }

        return baseContext
    }, [
        onWorldMapClick,
        onRegionMapClick,
        zoomIntoPeriod,
        insightPropsForQuery,
        query,
        isDragToZoomEnabled,
        isWorldMap,
    ])

    return (
        <div className="border rounded bg-surface-primary flex-1 flex flex-col">
            {headerSlot}
            {(showIntervalTile || preZoomDateFilter) && (
                <div className="flex flex-row items-center justify-end m-2 mr-4">
                    <div className="flex flex-row items-center gap-2">
                        {showIntervalTile && (
                            <>
                                <span>Group by</span>
                                <IntervalFilterStandalone interval={interval} onIntervalChange={setDateInterval} />
                            </>
                        )}
                        {preZoomDateFilter && (
                            <LemonButton type="secondary" size="small" icon={<IconUndo />} onClick={resetZoom}>
                                Reset zoom
                            </LemonButton>
                        )}
                    </div>
                </div>
            )}
            <WebAnalyticsTileSkeletonGate
                dataNodeLogicProps={dataNodeLogicProps}
                skeleton={
                    isWorldMap ? (
                        <WorldMapTileSkeleton />
                    ) : (
                        <ChartTileSkeleton showLegendStrip={!showIntervalTile && !preZoomDateFilter} />
                    )
                }
            >
                <Query uniqueKey={uniqueKey} attachTo={attachTo} query={query} readOnly={true} context={context} />
            </WebAnalyticsTileSkeletonGate>
        </div>
    )
}

export const AveragePageViewVisualizationTile = ({
    query,
    insightProps,
    attachTo,
    uniqueKey,
}: QueryWithInsightProps<DataVisualizationNode> & { uniqueKey: string }): JSX.Element => {
    const { setDateInterval } = useActions(webAnalyticsLogic)
    const {
        dateFilter: { interval },
    } = useValues(webAnalyticsLogic)

    return (
        <div className="border rounded bg-surface-primary flex-1 flex flex-col">
            <div className="flex flex-row items-center justify-end m-2 mr-4">
                <div className="flex flex-row items-center">
                    <span className="mr-2">Group by</span>
                    <IntervalFilterStandalone interval={interval} onIntervalChange={setDateInterval} />
                </div>
            </div>
            <Query
                uniqueKey={uniqueKey}
                attachTo={attachTo}
                query={query}
                readOnly={true}
                context={{ ...webAnalyticsDataTableQueryContext, insightProps }}
            />
        </div>
    )
}

export const MarketingAnalyticsTrendTile = ({
    query,
    showIntervalTile,
    insightProps,
    attachTo,
    uniqueKey,
}: QueryWithInsightProps<InsightVizNode> & { showIntervalTile?: boolean; uniqueKey: string }): JSX.Element => {
    const { setDateInterval, setChartDisplayType, setTileColumnSelection } = useActions(marketingAnalyticsLogic)
    const { dateFilter, chartDisplayType, tileColumnSelection } = useValues(marketingAnalyticsLogic)

    const MARKETING_COLUMN_OPTIONS: { value: validColumnsForTiles; label: string }[] = [
        { value: MarketingAnalyticsColumnsSchemaNames.Cost, label: 'Cost' },
        { value: MarketingAnalyticsColumnsSchemaNames.Impressions, label: 'Impressions' },
        { value: MarketingAnalyticsColumnsSchemaNames.Clicks, label: 'Clicks' },
        { value: MarketingAnalyticsColumnsSchemaNames.ReportedConversion, label: 'Reported conversion' },
        {
            value: MarketingAnalyticsColumnsSchemaNames.ReportedConversionValue,
            label: 'Reported conversion value',
        },
        { value: 'cpc', label: 'CPC' },
        { value: 'ctr', label: 'CTR' },
        { value: 'roas', label: 'Reported ROAS' },
        { value: 'cost_per_reported_conversion', label: 'Cost per reported conversion' },
    ]
    return (
        <div className="border rounded bg-surface-primary flex-1 flex flex-col min-h-100">
            {showIntervalTile && (
                <div className="flex flex-row items-center justify-between m-2 mr-4">
                    <LemonSelect
                        value={tileColumnSelection}
                        onChange={setTileColumnSelection}
                        options={MARKETING_COLUMN_OPTIONS}
                        placeholder="Select column"
                    />
                    <div className="flex flex-row items-center">
                        <div className="flex flex-row items-center mr-4">
                            <span className="mr-2">Group by</span>
                            <IntervalFilterStandalone
                                interval={dateFilter.interval}
                                onIntervalChange={setDateInterval}
                            />
                        </div>
                        <LemonSegmentedButton
                            value={chartDisplayType}
                            onChange={setChartDisplayType}
                            options={DISPLAY_MODE_OPTIONS}
                            size="small"
                        />
                    </div>
                </div>
            )}
            <Query
                uniqueKey={uniqueKey}
                attachTo={attachTo}
                query={query}
                readOnly={true}
                context={{ insightProps: { ...insightProps, query } }}
            />
        </div>
    )
}

export const WebStatsTableTile = ({
    query,
    breakdownBy,
    insightProps,
    control,
    attachTo,
    headerSlot,
    uniqueKey,
    enablePagination,
    tileId,
}: QueryWithInsightProps<DataTableNode> & {
    breakdownBy: WebStatsBreakdown
    control?: JSX.Element
    tileId: TileId
    headerSlot?: React.ReactNode
    uniqueKey: string
    /** Show the "load more" footer so long-tail breakdowns can be paginated (used by the expanded modal). */
    enablePagination?: boolean
}): JSX.Element => {
    const { togglePropertyFilter } = useActions(webAnalyticsLogic)
    const { productTab } = useValues(webAnalyticsLogic)
    const { rawWebAnalyticsFilters } = useValues(webAnalyticsFilterLogic)

    const { key, type } = webStatsBreakdownToPropertyName(breakdownBy) || {}

    const isCompoundBreakdown =
        breakdownBy === WebStatsBreakdown.InitialUTMSourceMediumCampaign ||
        breakdownBy === WebStatsBreakdown.Viewport ||
        breakdownBy === WebStatsBreakdown.Timezone

    const includeHost = query.source.kind === NodeKind.WebStatsTableQuery ? query.source.includeHost : false

    const utmSource = webStatsBreakdownToPropertyName(WebStatsBreakdown.InitialUTMSource)!
    const utmMedium = webStatsBreakdownToPropertyName(WebStatsBreakdown.InitialUTMMedium)!
    const utmCampaign = webStatsBreakdownToPropertyName(WebStatsBreakdown.InitialUTMCampaign)!
    const referringDomain = webStatsBreakdownToPropertyName(WebStatsBreakdown.InitialReferringDomain)!

    const { featureFlags } = useValues(featureFlagLogic)

    const getDrillDownTabChange = useCallback(
        (
            filterKey: string,
            filterValue: string | number | null
        ): { sourceTab?: string; geographyTab?: string; deviceTab?: string } | undefined => {
            const sourceDrillDown = SOURCE_DRILL_DOWN_MAP[breakdownBy]
            // When the referrer URL drilldown flag is off, don't navigate away from referrer domain
            const sourceTab =
                !featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_REFERRER_URL_DRILLDOWN] &&
                sourceDrillDown === SourceTab.REFERRING_URL
                    ? undefined
                    : sourceDrillDown
            const geographyTab = GEOGRAPHY_DRILL_DOWN_MAP[breakdownBy]
            const deviceTab = DEVICE_DRILL_DOWN_MAP[breakdownBy]
            const drillDownTab = sourceTab || geographyTab || deviceTab
            if (!drillDownTab || filterValue === null) {
                return undefined
            }
            const isAlreadyFiltered = rawWebAnalyticsFilters.some(
                (f) =>
                    f.key === filterKey &&
                    f.operator === PropertyOperator.Exact &&
                    (Array.isArray(f.value) ? f.value.includes(filterValue) : f.value === filterValue)
            )
            if (isAlreadyFiltered) {
                return undefined
            }
            return {
                ...(sourceTab ? { sourceTab } : {}),
                ...(geographyTab ? { geographyTab } : {}),
                ...(deviceTab ? { deviceTab } : {}),
            }
        },
        [breakdownBy, rawWebAnalyticsFilters, featureFlags]
    )

    const onClick = useCallback(
        (breakdownValue: string | null) => {
            if (productTab === ProductTab.PAGE_REPORTS) {
                lemonToast.info('Filters are not yet supported in this tile')
                return
            }

            // When includeHost is active, breakdown value contains host+path which doesn't map to a single property filter
            if (includeHost) {
                return
            }

            if (breakdownBy === WebStatsBreakdown.InitialUTMSourceMediumCampaign && breakdownValue) {
                const values = breakdownValue.split(' / ')
                const sourceValue = values[0]
                if (sourceValue && sourceValue !== BREAKDOWN_NULL_DISPLAY) {
                    if (sourceValue.startsWith(BREAKDOWN_REFERRER_PREFIX)) {
                        togglePropertyFilter(
                            referringDomain.type,
                            referringDomain.key,
                            sourceValue.slice(BREAKDOWN_REFERRER_PREFIX.length)
                        )
                    } else {
                        togglePropertyFilter(utmSource.type, utmSource.key, sourceValue)
                    }
                }
                if (values[1] && values[1] !== BREAKDOWN_NULL_DISPLAY) {
                    togglePropertyFilter(utmMedium.type, utmMedium.key, values[1])
                }
                if (values[2] && values[2] !== BREAKDOWN_NULL_DISPLAY) {
                    const drillDownTabChange = getDrillDownTabChange(utmCampaign.key, values[2])
                    togglePropertyFilter(utmCampaign.type, utmCampaign.key, values[2], drillDownTabChange)
                }
                return
            }

            if (breakdownBy === WebStatsBreakdown.Viewport && breakdownValue) {
                const [width, height] = breakdownValue.split('x')
                if (width) {
                    togglePropertyFilter(PropertyFilterType.Event, '$viewport_width', Number(width))
                }
                if (height) {
                    togglePropertyFilter(PropertyFilterType.Event, '$viewport_height', Number(height))
                }
                return
            }

            if (breakdownBy === WebStatsBreakdown.Timezone && breakdownValue) {
                // Backend displays -(offset_minutes)/60, so reverse: offset = -(display * 60)
                const offsetMinutes = -(Number(breakdownValue) * 60)
                togglePropertyFilter(PropertyFilterType.Event, '$timezone_offset', offsetMinutes)
                return
            }

            if (!key || !type) {
                return
            }

            togglePropertyFilter(type, key, breakdownValue, getDrillDownTabChange(key, breakdownValue))
        },
        [
            togglePropertyFilter,
            type,
            key,
            productTab,
            includeHost,
            breakdownBy,
            utmSource,
            utmMedium,
            utmCampaign,
            referringDomain,
            getDrillDownTabChange,
        ]
    )

    const canFilterRow = !includeHost && productTab !== ProductTab.PAGE_REPORTS

    const context = useMemo((): QueryContext => {
        const rowProps: QueryContext['rowProps'] = (record: unknown) => {
            // Compound breakdowns (UTM s/m/c, Viewport, Timezone) have dedicated handling in onClick
            if (!key && !type && !isCompoundBreakdown) {
                return {}
            }

            const breakdownValue = getBreakdownValue(record, breakdownBy)
            if (breakdownValue === undefined) {
                return {}
            }

            return { onClick: () => onClick(breakdownValue), ...(canFilterRow && { title: 'Filter by this value' }) }
        }

        return {
            ...webAnalyticsDataTableQueryContext,
            insightProps,
            rowProps,
            compareFilter: 'compareFilter' in query.source ? query.source.compareFilter : undefined,
            showLoadNextButton: enablePagination,
        }
    }, [onClick, insightProps, breakdownBy, key, type, isCompoundBreakdown, query, enablePagination, canFilterRow])

    const numericColumns = PAGE_LIKE_BREAKDOWNS.has(breakdownBy) ? 3 : 2
    const dataNodeLogicProps = buildDataTableTileDataNodeLogicProps({
        query,
        insightProps,
        context,
        uniqueKey,
    })

    return (
        <div className="border rounded bg-surface-primary flex-1 flex flex-col">
            {headerSlot}
            {control != null && <div className="flex flex-row items-center justify-end m-2 mr-4">{control}</div>}
            <WebAnalyticsTileSkeletonGate
                dataNodeLogicProps={dataNodeLogicProps}
                skeleton={<TableTileSkeleton numericColumns={numericColumns} />}
            >
                <Query uniqueKey={uniqueKey} attachTo={attachTo} query={query} readOnly={true} context={context} />
            </WebAnalyticsTileSkeletonGate>
            {tileId === TileId.SOURCES &&
                productTab === ProductTab.ANALYTICS &&
                uniqueKey.startsWith('WebAnalytics.') && <MarketingAnalyticsCrossSell breakdown={breakdownBy} />}
        </div>
    )
}

const getBreakdownValue = (record: unknown, breakdownBy: WebStatsBreakdown): string | null | undefined => {
    if (typeof record !== 'object' || !record || !('result' in record)) {
        return undefined
    }
    const result = record.result
    if (!Array.isArray(result)) {
        return undefined
    }
    // assume that the first element is the value
    const breakdownValue = result[0]

    switch (breakdownBy) {
        case WebStatsBreakdown.Country:
            if (Array.isArray(breakdownValue)) {
                return breakdownValue[0]
            }
            break
        case WebStatsBreakdown.Region:
            if (Array.isArray(breakdownValue)) {
                // Element 1 may be NULL when GeoIP can't resolve a subdivision; skip the
                // click handler in that case since filtering by NULL has no useful behavior.
                return breakdownValue[1] ?? undefined
            }
            break
        case WebStatsBreakdown.City:
            if (Array.isArray(breakdownValue)) {
                return breakdownValue[1] ?? undefined
            }
            break
        case WebStatsBreakdown.Viewport:
            if (Array.isArray(breakdownValue)) {
                return `${breakdownValue[0]}x${breakdownValue[1]}`
            }
            break
        case WebStatsBreakdown.Timezone:
            if (typeof breakdownValue === 'number') {
                return String(breakdownValue)
            }
            break
        case WebStatsBreakdown.FrustrationMetrics:
            if (typeof breakdownValue === 'string') {
                return breakdownValue
            }
            break
    }

    if (breakdownValue === null) {
        return null // null is a valid value, as opposed to undefined which signals that there isn't a valid value
    }

    if (typeof breakdownValue !== 'string') {
        return undefined
    }
    return breakdownValue
}

export const WebGoalsTile = ({
    query,
    insightProps,
    attachTo,
    headerSlot,
    uniqueKey,
}: QueryWithInsightProps<DataTableNode> & {
    headerSlot?: React.ReactNode
    uniqueKey: string
}): JSX.Element | null => {
    const { actions, actionsLoading } = useValues(actionsModel)
    const { updateHasSeenProductIntroFor } = useActions(userLogic)

    if (actionsLoading) {
        return null
    }

    if (!actions.length) {
        return (
            <ProductIntroduction
                thingName="action"
                isEmpty={true}
                titleOverride="Track your conversions"
                description="Goals show how many visitors complete the actions that matter to you. Sign-ups, purchases, demo requests. Create an action for a key conversion to see its visitors and conversion rate here."
                docsURL="https://posthog.com/docs/web-analytics/conversion-goals"
                hogLayout="responsive"
                actionElementOverride={
                    <NewActionButton onSelectOption={() => updateHasSeenProductIntroFor(ProductKey.ACTIONS)} />
                }
            />
        )
    }

    return (
        <WebGoalsTileContent
            query={query}
            insightProps={insightProps}
            attachTo={attachTo}
            headerSlot={headerSlot}
            uniqueKey={uniqueKey}
        />
    )
}

const WebGoalsTileContent = ({
    query,
    insightProps,
    attachTo,
    headerSlot,
    uniqueKey,
}: QueryWithInsightProps<DataTableNode> & {
    headerSlot?: React.ReactNode
    uniqueKey: string
}): JSX.Element => {
    const { addProductIntentForCrossSell } = useActions(teamLogic)

    const context = useMemo((): QueryContext => {
        return { ...webAnalyticsDataTableQueryContext, insightProps }
    }, [insightProps])
    const dataNodeLogicProps = buildDataTableTileDataNodeLogicProps({ query, insightProps, context, uniqueKey })

    return (
        <div className="border rounded bg-surface-primary flex-1">
            {headerSlot ?? (
                <div className="flex flex-row-reverse p-2">
                    <LemonButton
                        to={urls.actions()}
                        onClick={() => {
                            addProductIntentForCrossSell({
                                from: ProductKey.WEB_ANALYTICS,
                                to: ProductKey.ACTIONS,
                                intent_context: ProductIntentContext.WEB_ANALYTICS_INSIGHT,
                            })
                        }}
                        sideIcon={<IconOpenInNew />}
                        type="secondary"
                        size="small"
                    >
                        Manage actions
                    </LemonButton>
                </div>
            )}
            <WebAnalyticsTileSkeletonGate
                dataNodeLogicProps={dataNodeLogicProps}
                skeleton={<TableTileSkeleton numericColumns={4} />}
            >
                <Query uniqueKey={uniqueKey} attachTo={attachTo} query={query} readOnly={true} context={context} />
            </WebAnalyticsTileSkeletonGate>
        </div>
    )
}

export const WebExternalClicksTile = ({
    query,
    insightProps,
    attachTo,
    headerSlot,
    uniqueKey,
}: QueryWithInsightProps<DataTableNode> & {
    headerSlot?: React.ReactNode
    uniqueKey: string
}): JSX.Element | null => {
    const { productTab, shouldStripQueryParams } = useValues(webAnalyticsLogic)
    const { setShouldStripQueryParams } = useActions(webAnalyticsLogic)

    const isPageReportsPage = productTab === ProductTab.PAGE_REPORTS

    const context = useMemo((): QueryContext => {
        return { ...webAnalyticsDataTableQueryContext, insightProps }
    }, [insightProps])
    const dataNodeLogicProps = buildDataTableTileDataNodeLogicProps({ query, insightProps, context, uniqueKey })

    return (
        <div className="border rounded bg-surface-primary flex-1 flex flex-col">
            {headerSlot}
            {!isPageReportsPage && (
                <div className="flex flex-row items-center justify-end m-2 mr-4">
                    <div className="flex flex-row items-center deprecated-space-x-2">
                        <LemonSwitch
                            label="Strip query parameters"
                            checked={shouldStripQueryParams}
                            onChange={setShouldStripQueryParams}
                            className="h-full"
                        />
                    </div>
                </div>
            )}
            <WebAnalyticsTileSkeletonGate
                dataNodeLogicProps={dataNodeLogicProps}
                skeleton={<TableTileSkeleton numericColumns={2} />}
            >
                <Query uniqueKey={uniqueKey} attachTo={attachTo} query={query} readOnly={true} context={context} />
            </WebAnalyticsTileSkeletonGate>
        </div>
    )
}

export const WebVitalsPathBreakdownTile = ({
    query,
    insightProps,
    attachTo,
    uniqueKey,
}: QueryWithInsightProps<WebVitalsPathBreakdownQuery> & { uniqueKey: string }): JSX.Element => {
    const { isPathCleaningEnabled } = useValues(webAnalyticsLogic)
    const { setIsPathCleaningEnabled } = useActions(webAnalyticsLogic)

    return (
        <div>
            <div className="flex flex-row items-center gap-1 m-2">
                <h3 className="text-lg font-semibold">Path Breakdown</h3>
                {!isPathCleaningEnabled && (
                    <Tooltip
                        title={
                            <span>
                                Path Breakdown is more useful when path cleaning is turned on.{' '}
                                <Link onClick={() => setIsPathCleaningEnabled(true)}>Enable it.</Link>
                            </span>
                        }
                        interactive
                    >
                        <IconWarning className="mb-2" fontSize="18" />
                    </Tooltip>
                )}
            </div>
            <Query
                uniqueKey={uniqueKey}
                attachTo={attachTo}
                query={query}
                readOnly
                context={{ ...webAnalyticsDataTableQueryContext, insightProps }}
            />
        </div>
    )
}

interface HogQLTableTileProps {
    uniqueKey: string
    attachTo?: BuiltLogic | LogicWrapper
    query: DataTableNode
    insightProps: InsightLogicProps
    tileId: TileId
    headerSlot?: React.ReactNode
}

const useSingleSelectDrilldownContext = ({
    insightProps,
    filters,
    setFilters,
    filterKey,
    filterType,
}: {
    insightProps: InsightLogicProps
    filters: WebAnalyticsPropertyFilters
    setFilters: (filters: WebAnalyticsPropertyFilters) => void
    filterKey: string | undefined
    filterType: PropertyFilterType.Event | PropertyFilterType.Session
}): QueryContext =>
    useMemo((): QueryContext => {
        const toggleFilter = (key: string, value: string): void => {
            const existing = filters.find((f) => 'key' in f && f.key === key)
            const otherFilters = filters.filter((f) => !('key' in f && f.key === key))
            const existingValues =
                existing && 'value' in existing
                    ? Array.isArray(existing.value)
                        ? existing.value
                        : [existing.value]
                    : []
            if (existingValues.length === 1 && existingValues[0] === value) {
                setFilters(otherFilters)
                return
            }
            setFilters([...otherFilters, { key, value: [value], operator: PropertyOperator.Exact, type: filterType }])
        }

        return {
            ...webAnalyticsDataTableQueryContext,
            insightProps,
            rowProps: (record: unknown) => {
                const result = (record as { result?: unknown[] })?.result
                const value = Array.isArray(result) ? (result[0] as string) : null
                if (!value || !filterKey) {
                    return {}
                }
                return {
                    className: 'cursor-pointer',
                    onClick: () => toggleFilter(filterKey, value),
                }
            },
        }
    }, [insightProps, filters, setFilters, filterKey, filterType])

const BOT_HOGQL_TILES = new Set<TileId>([TileId.BOT_CRAWLERS, TileId.BOT_PATHS])

const BotHogQLTableTile = ({ uniqueKey, attachTo, query, insightProps, tileId }: HogQLTableTileProps): JSX.Element => {
    const { setBotAnalyticsFilters } = useActions(botAnalyticsLogic)
    const { rawBotAnalyticsFilters } = useValues(botAnalyticsLogic)

    const context = useSingleSelectDrilldownContext({
        insightProps,
        filters: rawBotAnalyticsFilters,
        setFilters: setBotAnalyticsFilters,
        filterKey: tileId === TileId.BOT_CRAWLERS ? '$virt_bot_name' : '$pathname',
        filterType: PropertyFilterType.Event,
    })
    const dataNodeLogicProps = buildDataTableTileDataNodeLogicProps({ query, insightProps, context, uniqueKey })

    return (
        <div className="border rounded bg-surface-primary flex-1 flex flex-col py-2 px-1">
            <WebAnalyticsTileSkeletonGate
                dataNodeLogicProps={dataNodeLogicProps}
                skeleton={<TableTileSkeleton numericColumns={2} />}
            >
                <Query uniqueKey={uniqueKey} attachTo={attachTo} query={query} readOnly={true} context={context} />
            </WebAnalyticsTileSkeletonGate>
        </div>
    )
}

const HogQLTableTile = (props: HogQLTableTileProps): JSX.Element => {
    if (BOT_HOGQL_TILES.has(props.tileId)) {
        return <BotHogQLTableTile {...props} />
    }
    return (
        <div className="border rounded bg-surface-primary flex-1 flex flex-col py-2 px-1">
            {props.headerSlot}
            <Query
                uniqueKey={props.uniqueKey}
                attachTo={props.attachTo}
                query={props.query}
                readOnly={true}
                context={{ ...webAnalyticsDataTableQueryContext, insightProps: props.insightProps }}
            />
        </div>
    )
}

export const WebQuery = ({
    query,
    showIntervalSelect,
    control,
    insightProps,
    tileId,
    attachTo,
    uniqueKey,
    headerSlot,
    enablePagination,
}: QueryWithInsightProps<QuerySchema> & {
    showIntervalSelect?: boolean
    control?: JSX.Element
    tileId: TileId
    uniqueKey: string
    headerSlot?: React.ReactNode
    /** Show the "load more" footer on breakdown tables (used by the expanded modal). */
    enablePagination?: boolean
}): JSX.Element => {
    const { productTab, shouldStripQueryParams: stripQueryParamsDashboard } = useValues(webAnalyticsLogic)
    const { stripQueryParams: stripQueryParamsPageReports } = useValues(pageReportsLogic)

    if (query.kind === NodeKind.DataTableNode && query.source.kind === NodeKind.WebStatsTableQuery) {
        // Handle Frustrating Pages tile specifically, which uses WebStatsTableQuery but is not wrapped by a WebAnalyticsTabTile
        if (query.source.breakdownBy === WebStatsBreakdown.FrustrationMetrics) {
            return (
                <FrustrationMetricsTile
                    attachTo={attachTo}
                    query={query}
                    insightProps={insightProps}
                    uniqueKey={uniqueKey}
                    headerSlot={headerSlot}
                />
            )
        }

        return (
            <WebStatsTableTile
                attachTo={attachTo}
                query={query}
                breakdownBy={query.source.breakdownBy}
                insightProps={insightProps}
                control={control}
                tileId={tileId}
                headerSlot={headerSlot}
                uniqueKey={uniqueKey}
                enablePagination={enablePagination}
            />
        )
    }

    if (query.kind === NodeKind.DataTableNode && query.source.kind === NodeKind.WebExternalClicksTableQuery) {
        const effectiveStripQueryParams =
            productTab === ProductTab.PAGE_REPORTS ? stripQueryParamsPageReports : stripQueryParamsDashboard

        const adjustedQuery = {
            ...query,
            source: {
                ...query.source,
                stripQueryParams: effectiveStripQueryParams,
            },
        }
        return (
            <WebExternalClicksTile
                attachTo={attachTo}
                query={adjustedQuery}
                insightProps={insightProps}
                headerSlot={headerSlot}
                uniqueKey={uniqueKey}
            />
        )
    }

    if (query.kind === NodeKind.InsightVizNode && tileId === TileId.MARKETING) {
        return (
            <MarketingAnalyticsTrendTile
                attachTo={attachTo}
                query={query}
                showIntervalTile={showIntervalSelect}
                insightProps={insightProps}
                uniqueKey={uniqueKey}
            />
        )
    } else if (query.kind === NodeKind.InsightVizNode) {
        return (
            <WebStatsTrendTile
                attachTo={attachTo}
                query={query}
                showIntervalTile={showIntervalSelect}
                insightProps={insightProps}
                headerSlot={headerSlot}
                uniqueKey={uniqueKey}
            />
        )
    }

    if (query.kind === NodeKind.DataTableNode && query.source.kind === NodeKind.WebGoalsQuery) {
        return (
            <WebGoalsTile
                attachTo={attachTo}
                query={query}
                insightProps={insightProps}
                headerSlot={headerSlot}
                uniqueKey={uniqueKey}
            />
        )
    }

    if (query.kind === NodeKind.DataTableNode && query.source.kind === NodeKind.MarketingAnalyticsTableQuery) {
        return <MarketingAnalyticsTable attachTo={attachTo} query={query} insightProps={insightProps} />
    }

    if (query.kind === NodeKind.MarketingAnalyticsAggregatedQuery) {
        return (
            <Query
                uniqueKey={uniqueKey}
                attachTo={attachTo}
                query={query}
                readOnly={true}
                context={{ ...webAnalyticsDataTableQueryContext, insightProps }}
            />
        )
    }

    if (query.kind === NodeKind.WebVitalsPathBreakdownQuery) {
        return (
            <WebVitalsPathBreakdownTile
                attachTo={attachTo}
                query={query}
                insightProps={insightProps}
                uniqueKey={uniqueKey}
            />
        )
    }

    if (query.kind === NodeKind.DataVisualizationNode) {
        return (
            <AveragePageViewVisualizationTile
                attachTo={attachTo}
                query={query}
                insightProps={insightProps}
                uniqueKey={uniqueKey}
            />
        )
    }

    if (query.kind === NodeKind.DataTableNode && query.source.kind === NodeKind.HogQLQuery) {
        return (
            <HogQLTableTile
                uniqueKey={uniqueKey}
                attachTo={attachTo}
                query={query}
                insightProps={insightProps}
                tileId={tileId}
                headerSlot={headerSlot}
            />
        )
    }

    if (!headerSlot) {
        return (
            <Query
                uniqueKey={uniqueKey}
                attachTo={attachTo}
                query={query}
                readOnly={true}
                context={{ ...webAnalyticsDataTableQueryContext, insightProps }}
            />
        )
    }

    return (
        <div className="border rounded bg-surface-primary flex-1 flex flex-col">
            {headerSlot}
            <Query
                uniqueKey={uniqueKey}
                attachTo={attachTo}
                query={query}
                readOnly={true}
                context={{ ...webAnalyticsDataTableQueryContext, insightProps }}
            />
        </div>
    )
}

const FrustrationMetricsTile = ({
    query,
    insightProps,
    attachTo,
    uniqueKey,
    headerSlot,
}: {
    query: DataTableNode
    insightProps: InsightLogicProps
    attachTo?: BuiltLogic | LogicWrapper
    uniqueKey: string
    headerSlot?: React.ReactNode
}): JSX.Element => {
    const context = useMemo((): QueryContext => {
        return {
            ...webAnalyticsDataTableQueryContext,
            insightProps,
            emptyStateHeading: '',
            emptyStateDetail: FrustrationMetricsEmptyState,
            emptyStateIcon: <></>,
        }
    }, [insightProps])
    const dataNodeLogicProps = buildDataTableTileDataNodeLogicProps({ query, insightProps, context })

    return (
        <div className="border rounded bg-surface-primary flex-1 flex flex-col py-2 px-1">
            {headerSlot}
            <WebAnalyticsTileSkeletonGate
                dataNodeLogicProps={dataNodeLogicProps}
                skeleton={<TableTileSkeleton numericColumns={3} />}
            >
                <Query attachTo={attachTo} query={query} key={uniqueKey} readOnly={true} context={context} />
            </WebAnalyticsTileSkeletonGate>
        </div>
    )
}

const FrustrationMetricsEmptyState = (
    <>
        <div className="w-full p-8 justify-center rounded mt-2 mb-4">
            <div className="flex items-center gap-8 w-full justify-center">
                <div>
                    <div className="w-40 lg:w-50 mx-auto mb-4 hidden md:block">
                        <HedgehogStar />
                    </div>
                    <p>No frustrating pages found! Keep up the great work!</p>
                </div>
            </div>
        </div>
    </>
)