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.

38.7 KB
Raw Blame
import '~/queries/nodes/InsightViz/InsightViz.scss'

import clsx from 'clsx'
import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
import React, { Suspense, useEffect, useState } from 'react'

import { IconExpand45, IconInfo, IconLineGraph, IconOpenSidebar, IconX } from '@posthog/icons'
import { LemonSegmentedButton, LemonSegmentedDropdown, LemonSelect, LemonSkeleton } from '@posthog/lemon-ui'

import { IntervalFilterStandalone } from 'lib/components/IntervalFilter/IntervalFilter'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
import { useShortcut } from 'lib/components/Shortcuts/useShortcut'
import { FEATURE_FLAGS } from 'lib/constants'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { IconOpenInNew, IconTableChart } from 'lib/lemon-ui/icons'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { Link, PostHogComDocsURL } from 'lib/lemon-ui/Link/Link'
import { Popover } from 'lib/lemon-ui/Popover'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { isNotNil } from 'lib/utils/guards'
import { addProductIntentForCrossSell } from 'lib/utils/product-intents'
import { lazyWithRetry } from 'lib/utils/retryImport'
import { ChunkLoadErrorBoundary } from 'scenes/ChunkLoadErrorBoundary'
import { Scene } from 'scenes/sceneTypes'
import { QuickSurveyType } from 'scenes/surveys/quick-create/types'
import { QuickSurveyModal } from 'scenes/surveys/QuickSurveyModal'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { WebAnalyticsAchievementsModal } from 'scenes/web-analytics/achievements/WebAnalyticsAchievementsModal'
import {
    ProductTab,
    QueryTile,
    SectionTile,
    TabsTile,
    TileId,
    TileVisualizationOption,
    WEB_ANALYTICS_DATA_COLLECTION_NODE_ID,
    WebAnalyticsTile,
    isContentAutopilotEnabled,
    tabSplitIndicesMap,
} from 'scenes/web-analytics/common'
import { PageReports, PageReportsFilters } from 'scenes/web-analytics/PageReports'
import { ShareNudgePrompt } from 'scenes/web-analytics/ShareNudgePrompt'
import { WebAnalyticsErrorTrackingTile } from 'scenes/web-analytics/tiles/WebAnalyticsErrorTracking'
import { WebAnalyticsRecordingsTile } from 'scenes/web-analytics/tiles/WebAnalyticsRecordings'
import { WebQuery } from 'scenes/web-analytics/tiles/WebAnalyticsTile'
import { WebAnalyticsHealthCheck } from 'scenes/web-analytics/WebAnalyticsHealthCheck'
import { webAnalyticsLoadTimeLogic } from 'scenes/web-analytics/webAnalyticsLoadTimeLogic'
import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'
import { WebAnalyticsModal } from 'scenes/web-analytics/WebAnalyticsModal'
import { WebAnalyticsSavePresetNudge } from 'scenes/web-analytics/WebAnalyticsSavePresetNudge'
import { WebAnalyticsShareColleagueBanner } from 'scenes/web-analytics/WebAnalyticsShareColleagueBanner'
import { WebTileHeader } from 'scenes/web-analytics/WebTileHeader'
import { useWebTileOpenInsight, useWebTileOverflowMenuItems } from 'scenes/web-analytics/webTileHeaderHooks'

import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
import { ProductIntentContext, ProductKey, QuerySchema } from '~/queries/schema/schema-general'
import { InsightLogicProps, OnboardingStepKey, TeamPublicType, TeamType } from '~/types'

import { AgentAnalytics } from 'products/web_analytics/frontend/agent_analytics/AgentAnalytics'
import { AgentAnalyticsFilters } from 'products/web_analytics/frontend/agent_analytics/AgentAnalyticsFilters'
import { ContentAutopilot } from 'products/web_analytics/frontend/contentAutopilot/ContentAutopilot'
import { MarketingAnalyticsFilterHint } from 'products/web_analytics/frontend/marketing/MarketingAnalyticsFilterHint'
import { PageReportsTabLabel } from 'products/web_analytics/frontend/pageReports/PageReportsTabLabel'

import { BotAnalyticsFilters } from './BotAnalyticsFilters'
import { botAnalyticsLogic } from './botAnalyticsLogic'
import { HealthStatusTab, webAnalyticsHealthLogic } from './health'
import { LiveBotTiles } from './LiveMetricsDashboard/LiveBotTiles'
import { PagePerformance } from './PagePerformance'
import { PagePerformanceFilters } from './PagePerformanceFilters'
import { WebAnalyticsExport } from './WebAnalyticsExport'
import { WebAnalyticsFilters } from './WebAnalyticsFilters'
import { webAnalyticsModalLogic } from './webAnalyticsModalLogic'

// Only the live tab renders this dashboard, and its world map holds about 1 MiB of country shapes.
const LiveWebAnalyticsMetrics = lazyWithRetry(() =>
    import('./LiveMetricsDashboard/LiveWebAnalyticsMetrics').then((m) => ({ default: m.LiveWebAnalyticsMetrics }))
)

export const Tiles = (props: { tiles?: WebAnalyticsTile[]; compact?: boolean }): JSX.Element => {
    const { tiles: tilesFromProps, compact = false } = props
    const { tiles: tilesFromLogic, productTab } = useValues(webAnalyticsLogic)
    const { currentTeam, currentTeamLoading } = useValues(teamLogic)
    const tiles = tilesFromProps ?? tilesFromLogic
    const { featureFlags } = useValues(featureFlagLogic)
    const useTileHeaderV2 = featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_TILE_HEADER_V2] === 'test'

    const emptyOnboardingContent = getEmptyOnboardingContent(featureFlags, currentTeamLoading, currentTeam, productTab)

    return (
        <div
            className={clsx(
                'mt-4 pb-4 grid grid-cols-1',
                'md:grid-cols-2 2xl:grid-cols-3',
                useTileHeaderV2 && '2xl:grid-flow-dense',
                compact ? 'gap-x-2 gap-y-2' : 'gap-x-4 gap-y-4'
            )}
            data-attr="web-analytics-dashboard"
        >
            {emptyOnboardingContent ??
                tiles.map((tile, i) => {
                    if (tile.kind === 'query') {
                        return <QueryTileItem key={i} tile={tile} />
                    } else if (tile.kind === 'tabs') {
                        return <TabsTileItem key={i} tile={tile} />
                    } else if (tile.kind === 'replay') {
                        return <WebAnalyticsRecordingsTile key={i} tile={tile} />
                    } else if (tile.kind === 'error_tracking') {
                        return <WebAnalyticsErrorTrackingTile key={i} tile={tile} />
                    } else if (tile.kind === 'section') {
                        return <SectionTileItem key={i} tile={tile} />
                    }
                    return null
                })}
        </div>
    )
}

export const QueryTileItem = ({ tile }: { tile: QueryTile }): JSX.Element => {
    const { query, title, layout, insightProps, control, showIntervalSelect, docs } = tile
    const { featureFlags } = useValues(featureFlagLogic)
    const useTileHeaderV2 = featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_TILE_HEADER_V2] === 'test'

    const containerClassName = clsx(
        'col-span-1 row-span-1 flex flex-col',
        layout.colSpanClassName ?? 'md:col-span-1',
        layout.rowSpanClassName ?? 'md:row-span-1',
        layout.orderWhenLargeClassName ?? '2xl:order-12',
        layout.className
    )

    if (useTileHeaderV2) {
        return (
            <QueryTileItemV2
                tile={tile}
                containerClassName={containerClassName}
                query={query}
                title={title}
                insightProps={insightProps}
                control={control}
                showIntervalSelect={showIntervalSelect}
                docs={docs}
            />
        )
    }

    return (
        <QueryTileItemLegacy
            tile={tile}
            containerClassName={containerClassName}
            query={query}
            title={title}
            insightProps={insightProps}
            control={control}
            showIntervalSelect={showIntervalSelect}
            docs={docs}
        />
    )
}

interface QueryTileItemVariantProps {
    tile: QueryTile
    containerClassName: string
    query: QuerySchema
    title?: string
    insightProps: InsightLogicProps
    control?: JSX.Element
    showIntervalSelect?: boolean
    docs?: QueryTile['docs']
}

const HEADERLESS_TILES = new Set<TileId>([TileId.OVERVIEW, TileId.WEB_VITALS])

const QueryTileItemV2 = ({
    tile,
    containerClassName,
    query,
    title,
    insightProps,
    control,
    showIntervalSelect,
    docs,
}: QueryTileItemVariantProps): JSX.Element => {
    const overflowMenuItems = useWebTileOverflowMenuItems({
        tileId: tile.tileId,
        query,
        insightProps,
        canOpenModal: tile.canOpenModal,
        extraMenuItems: tile.extraMenuItems,
    })
    const openInsight = useWebTileOpenInsight({ tileId: tile.tileId, canOpenInsight: !!tile.canOpenInsight })

    return (
        <div className={containerClassName}>
            <WebQuery
                attachTo={webAnalyticsLogic}
                uniqueKey={`WebAnalytics.${tile.tileId}`}
                query={query}
                insightProps={insightProps}
                control={control}
                showIntervalSelect={showIntervalSelect}
                tileId={tile.tileId}
                headerSlot={
                    HEADERLESS_TILES.has(tile.tileId) ? undefined : (
                        <WebTileHeader
                            tileId={tile.tileId}
                            title={title}
                            docs={docs}
                            openInsight={openInsight}
                            overflowMenuItems={overflowMenuItems}
                        />
                    )
                }
            />
        </div>
    )
}

const QueryTileItemLegacy = ({
    tile,
    containerClassName,
    query,
    title,
    insightProps,
    control,
    showIntervalSelect,
    docs,
}: QueryTileItemVariantProps): JSX.Element => {
    const { openModal } = useActions(webAnalyticsModalLogic)
    const { getNewInsightUrl } = useValues(webAnalyticsModalLogic)

    const buttonsRow = [
        <WebAnalyticsExport key="export-button" query={query} insightProps={insightProps} />,
        tile.canOpenInsight ? (
            <LemonButton
                key="open-insight-button"
                to={getNewInsightUrl(tile.tileId)}
                icon={<IconOpenInNew />}
                size="small"
                type="secondary"
                onClick={() => {
                    void addProductIntentForCrossSell({
                        from: ProductKey.WEB_ANALYTICS,
                        to: ProductKey.PRODUCT_ANALYTICS,
                        intent_context: ProductIntentContext.WEB_ANALYTICS_INSIGHT,
                    })
                }}
            >
                <span className="@min-[26rem]/web-tile:hidden">Open insight</span>
                <span className="hidden @min-[26rem]/web-tile:inline">Open as new insight</span>
            </LemonButton>
        ) : null,
        tile.canOpenModal !== false ? (
            <LemonButton
                key="open-modal-button"
                onClick={() => openModal(tile.tileId)}
                icon={<IconExpand45 />}
                size="small"
                type="secondary"
            >
                <span className="@min-[26rem]/web-tile:hidden">Expand</span>
                <span className="hidden @min-[26rem]/web-tile:inline">Show more</span>
            </LemonButton>
        ) : null,
    ].filter(isNotNil)

    return (
        <div className={clsx(containerClassName, '@container/web-tile')}>
            {title && (
                <div className="flex flex-row items-center mb-2">
                    <h2>{title}</h2>
                    {docs && <LearnMorePopover url={docs.url} title={docs.title} description={docs.description} />}
                </div>
            )}

            <WebQuery
                attachTo={webAnalyticsLogic}
                uniqueKey={`WebAnalytics.${tile.tileId}`}
                query={query}
                insightProps={insightProps}
                control={control}
                showIntervalSelect={showIntervalSelect}
                tileId={tile.tileId}
            />

            {buttonsRow.length > 0 ? <div className="flex flex-wrap justify-end gap-2 my-2">{buttonsRow}</div> : null}
        </div>
    )
}

const TABS_TILE_VISUALIZATION_TOGGLE_TILES = [TileId.SOURCES, TileId.DEVICES, TileId.PATHS]

const TILES_WHERE_DROPDOWN_IS_TITLE = new Set<TileId>([TileId.GRAPHS, TileId.PATHS])

const TILE_TITLE_PREFIX: Partial<Record<TileId, string>> = {
    [TileId.SOURCES]: 'Sources by',
    [TileId.DEVICES]: 'Devices by',
    [TileId.GEOGRAPHY]: 'Geography by',
    [TileId.ACTIVE_HOURS]: 'Active hours by',
}

const TabsTileItem = ({ tile }: { tile: TabsTile }): JSX.Element => {
    const { featureFlags } = useValues(featureFlagLogic)
    const useTileHeaderV2 = featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_TILE_HEADER_V2] === 'test'

    if (useTileHeaderV2) {
        return <TabsTileItemV2 tile={tile} />
    }
    return <TabsTileItemLegacy tile={tile} />
}

const TabsTileItemV2 = ({ tile }: { tile: TabsTile }): JSX.Element => {
    const { layout, tileId, activeTabId, setTabId, tabs } = tile

    const { setDateInterval, setTileVisualization } = useActions(webAnalyticsLogic)
    const {
        dateFilter: { interval },
        tileVisualizations,
    } = useValues(webAnalyticsLogic)

    const activeTab = tabs.find((t) => t.id === activeTabId)
    const useLongLabels = TILES_WHERE_DROPDOWN_IS_TITLE.has(tileId)
    const titlePrefix = TILE_TITLE_PREFIX[tileId]
    const dropdownOptions = tabs.map((t) => ({
        value: t.id,
        label: (useLongLabels ? t.title : t.linkText) as string | JSX.Element,
    }))

    const showIntervalInHeader = tileId === TileId.GRAPHS && !!activeTab?.showIntervalSelect
    const showVisualizationToggle = TABS_TILE_VISUALIZATION_TOGGLE_TILES.includes(tileId)

    const overflowMenuItems = useWebTileOverflowMenuItems({
        tileId,
        tabId: activeTabId,
        query: activeTab?.query,
        insightProps: activeTab?.insightProps,
        canOpenModal: activeTab?.canOpenModal,
        extraMenuItems: activeTab?.extraMenuItems,
    })
    const openInsight = useWebTileOpenInsight({
        tileId,
        tabId: activeTabId,
        canOpenInsight: !!activeTab?.canOpenInsight,
    })

    const header = (
        <WebTileHeader
            tileId={tileId}
            titlePrefix={titlePrefix}
            titleDropdown={{ value: activeTabId, options: dropdownOptions, onChange: setTabId }}
            docs={activeTab?.docs}
            intervalSelector={
                showIntervalInHeader
                    ? {
                          node: <IntervalFilterStandalone interval={interval} onIntervalChange={setDateInterval} />,
                      }
                    : undefined
            }
            visualizationToggle={
                showVisualizationToggle
                    ? {
                          value: tileVisualizations[tileId],
                          onChange: (value) => setTileVisualization(tileId, value),
                      }
                    : undefined
            }
            openInsight={openInsight}
            overflowMenuItems={overflowMenuItems}
        />
    )

    return (
        <div
            className={clsx(
                'col-span-1 row-span-1 flex flex-col',
                layout.colSpanClassName ?? 'md:col-span-1',
                layout.rowSpanClassName ?? 'md:row-span-1',
                layout.orderWhenLargeClassName ?? '2xl:order-12',
                layout.className
            )}
        >
            {activeTab ? (
                <WebQuery
                    attachTo={webAnalyticsLogic}
                    uniqueKey={`WebAnalytics.${tileId}.${activeTab.id}`}
                    key={activeTab.id}
                    query={activeTab.query}
                    showIntervalSelect={showIntervalInHeader ? false : activeTab.showIntervalSelect}
                    control={activeTab.control}
                    insightProps={activeTab.insightProps}
                    tileId={tileId}
                    headerSlot={header}
                />
            ) : (
                <div className="border rounded bg-surface-primary flex-1 flex flex-col">{header}</div>
            )}
        </div>
    )
}

const TabsTileItemLegacy = ({ tile }: { tile: TabsTile }): JSX.Element => {
    const { layout } = tile

    const { getNewInsightUrl } = useValues(webAnalyticsModalLogic)

    return (
        <WebTabs
            className={clsx(
                'col-span-1 row-span-1',
                layout.colSpanClassName || 'md:col-span-1',
                layout.rowSpanClassName || 'md:row-span-1',
                layout.orderWhenLargeClassName || '2xl:order-12',
                layout.className
            )}
            activeTabId={tile.activeTabId}
            setActiveTabId={tile.setTabId}
            tabs={tile.tabs.map((tab) => ({
                id: tab.id,
                content: (
                    <WebQuery
                        attachTo={webAnalyticsLogic}
                        uniqueKey={`WebAnalytics.${tile.tileId}.${tab.id}`}
                        key={tab.id}
                        query={tab.query}
                        showIntervalSelect={tab.showIntervalSelect}
                        control={tab.control}
                        insightProps={tab.insightProps}
                        tileId={tile.tileId}
                    />
                ),
                linkText: tab.linkText,
                title: tab.title,
                canOpenModal: !!tab.canOpenModal,
                canOpenInsight: !!tab.canOpenInsight,
                query: tab.query,
                docs: tab.docs,
                insightProps: tab.insightProps,
            }))}
            tileId={tile.tileId}
            splitIndices={tile.splitIndices}
            getNewInsightUrl={getNewInsightUrl}
        />
    )
}

export const WebTabs = ({
    className,
    activeTabId,
    tabs,
    setActiveTabId,
    getNewInsightUrl,
    tileId,
    splitIndices,
}: {
    className?: string
    activeTabId: string
    tabs: {
        id: string
        title: string | JSX.Element
        linkText: string | JSX.Element
        content: React.ReactNode
        canOpenModal?: boolean
        canOpenInsight: boolean
        query: QuerySchema
        docs: LearnMorePopoverProps | undefined
        insightProps: InsightLogicProps
    }[]
    setActiveTabId: (id: string) => void
    getNewInsightUrl: (tileId: TileId, tabId: string) => string | undefined
    tileId: TileId
    splitIndices?: number[]
}): JSX.Element => {
    const activeTab = tabs.find((t) => t.id === activeTabId)
    const newInsightUrl = getNewInsightUrl(tileId, activeTabId)

    const { openModal } = useActions(webAnalyticsModalLogic)
    const { setTileVisualization } = useActions(webAnalyticsLogic)
    const { tileVisualizations } = useValues(webAnalyticsLogic)
    const visualization = tileVisualizations[tileId]

    const isVisualizationToggleEnabled = [TileId.SOURCES, TileId.DEVICES, TileId.PATHS].includes(tileId)

    const activeTabData = tabs.find((t) => t.id === activeTabId)
    const tabOptions = tabs.map(({ id, linkText }) => ({ value: id, label: linkText }))

    const buttonsRow = [
        activeTab && activeTabData ? (
            <WebAnalyticsExport
                key="export-button"
                query={activeTabData.query}
                insightProps={activeTabData.insightProps}
            />
        ) : null,
        activeTab?.canOpenInsight && newInsightUrl ? (
            <LemonButton
                key="open-insight-button"
                to={newInsightUrl}
                icon={<IconOpenInNew />}
                size="small"
                type="secondary"
                onClick={() => {
                    void addProductIntentForCrossSell({
                        from: ProductKey.WEB_ANALYTICS,
                        to: ProductKey.PRODUCT_ANALYTICS,
                        intent_context: ProductIntentContext.WEB_ANALYTICS_INSIGHT,
                    })
                }}
            >
                <span className="@min-[26rem]/web-tile:hidden">Open insight</span>
                <span className="hidden @min-[26rem]/web-tile:inline">Open as new insight</span>
            </LemonButton>
        ) : null,
        activeTab?.canOpenModal !== false ? (
            <LemonButton
                key="open-modal-button"
                onClick={() => openModal(tileId, activeTabId)}
                icon={<IconExpand45 />}
                size="small"
                type="secondary"
            >
                <span className="@min-[26rem]/web-tile:hidden">Expand</span>
                <span className="hidden @min-[26rem]/web-tile:inline">Show more</span>
            </LemonButton>
        ) : null,
    ].filter(isNotNil)

    return (
        <div className={clsx(className, '@container/web-tile flex flex-col')}>
            <div className="flex flex-row flex-wrap items-center gap-2 self-stretch mb-2">
                <h2 className="flex-1 m-0 flex flex-row ml-1 whitespace-nowrap">
                    {activeTab?.title}
                    {activeTab?.docs && (
                        <LearnMorePopover
                            url={activeTab.docs.url}
                            title={activeTab.docs.title}
                            description={activeTab.docs.description}
                        />
                    )}
                </h2>

                {isVisualizationToggleEnabled && (
                    <LemonSegmentedButton
                        value={visualization || 'table'}
                        onChange={(value) => setTileVisualization(tileId, value as TileVisualizationOption)}
                        options={[
                            {
                                value: 'table',
                                icon: <IconTableChart />,
                            },
                            {
                                value: 'graph',
                                icon: <IconLineGraph />,
                            },
                        ]}
                        size="small"
                    />
                )}

                <div className="hidden @min-[30rem]/web-tile:block">
                    <LemonSegmentedDropdown
                        splitIndices={splitIndices ?? tabSplitIndicesMap[tileId]}
                        size="small"
                        value={activeTabId}
                        onChange={setActiveTabId}
                        options={tabOptions}
                    />
                </div>
                <div className="@min-[30rem]/web-tile:hidden">
                    <LemonSelect size="small" value={activeTabId} onChange={setActiveTabId} options={tabOptions} />
                </div>
            </div>
            <div className="flex-1 flex flex-col">{activeTab?.content}</div>
            {buttonsRow.length > 0 ? <div className="flex flex-wrap justify-end gap-2 my-2">{buttonsRow}</div> : null}
        </div>
    )
}

export const SectionTileItem = ({ tile, separator }: { tile: SectionTile; separator?: boolean }): JSX.Element => {
    return (
        <div className="col-span-full">
            {tile.title && <h2 className="text-lg font-semibold mb-2">{tile.title}</h2>}
            <div className={clsx('grid gap-2', tile.layout.className)}>
                {tile.tiles.map((subTile, i) => {
                    if (subTile.kind === 'query') {
                        return (
                            <div key={`${subTile.tileId}-${i}`} className="col-span-1">
                                <QueryTileItem tile={subTile} />
                            </div>
                        )
                    }
                    return null
                })}
            </div>
            {separator && <LemonDivider className="my-3" />}
        </div>
    )
}

export interface LearnMorePopoverProps {
    url?: PostHogComDocsURL
    title: string
    description: string | JSX.Element
}

export const LearnMorePopover = ({ url, title, description }: LearnMorePopoverProps): JSX.Element => {
    const [isOpen, setIsOpen] = useState(false)

    return (
        <Popover
            visible={isOpen}
            onClickOutside={() => setIsOpen(false)}
            overlay={
                <div className="p-4 max-w-160 max-h-160 overflow-auto">
                    <div className="flex flex-row w-full">
                        <h2 className="flex-1">{title}</h2>
                        <LemonButton
                            targetBlank
                            type="tertiary"
                            onClick={() => setIsOpen(false)}
                            size="small"
                            icon={<IconX />}
                        />
                    </div>
                    <div className="text-sm text-gray-700 dark:text-white">{description}</div>
                    {url && (
                        <div className="flex justify-end mt-4">
                            <LemonButton
                                to={url}
                                onClick={() => setIsOpen(false)}
                                targetBlank={true}
                                sideIcon={<IconOpenSidebar />}
                            >
                                Learn more
                            </LemonButton>
                        </div>
                    )}
                </div>
            }
        >
            <LemonButton
                onClick={() => setIsOpen(!isOpen)}
                size="small"
                noPadding
                icon={<IconInfo />}
                aria-label="More info"
            />
        </Popover>
    )
}

// We're switching the filters based on the productTab right now so it is abstracted here
// until we decide if we want to keep the same components/states for both tabs
const Filters = ({ tabs }: { tabs: JSX.Element }): JSX.Element | null => {
    const { productTab } = useValues(webAnalyticsLogic)
    switch (productTab) {
        case ProductTab.PAGE_REPORTS:
            return <PageReportsFilters tabs={tabs} />
        case ProductTab.HEALTH:
        case ProductTab.LIVE:
            return null
        case ProductTab.PAGE_PERFORMANCE:
            return <PagePerformanceFilters tabs={tabs} />
        case ProductTab.AGENTS:
            return <AgentAnalyticsFilters tabs={tabs} />
        case ProductTab.CONTENT_AUTOPILOT:
        case ProductTab.BOT_ANALYTICS:
            return null
        default:
            return <WebAnalyticsFilters tabs={tabs} />
    }
}

const MainContent = (): JSX.Element => {
    const { productTab } = useValues(webAnalyticsLogic)

    if (productTab === ProductTab.PAGE_REPORTS) {
        return <PageReports />
    }

    if (productTab === ProductTab.HEALTH) {
        return <HealthStatusTab />
    }

    if (productTab === ProductTab.LIVE) {
        return (
            <ChunkLoadErrorBoundary>
                <Suspense fallback={<LemonSkeleton className="h-96 w-full" />}>
                    <LiveWebAnalyticsMetrics />
                </Suspense>
            </ChunkLoadErrorBoundary>
        )
    }

    if (productTab === ProductTab.PAGE_PERFORMANCE) {
        return <PagePerformance />
    }

    if (productTab === ProductTab.AGENTS) {
        return <AgentAnalytics />
    }

    if (productTab === ProductTab.CONTENT_AUTOPILOT || productTab === ProductTab.BOT_ANALYTICS) {
        return <AiVisibility />
    }

    return <Tiles />
}

const AiVisibility = (): JSX.Element => {
    const { productTab } = useValues(webAnalyticsLogic)
    const { setProductTab } = useActions(webAnalyticsLogic)

    return (
        <ContentAutopilot
            bots={{
                active: productTab === ProductTab.BOT_ANALYTICS,
                open: () => setProductTab(ProductTab.BOT_ANALYTICS),
                close: () => setProductTab(ProductTab.CONTENT_AUTOPILOT),
                content: (
                    <div className="flex flex-col gap-2">
                        <BotAnalyticsFilters tabs={<></>} />
                        <BotAnalyticsTiles />
                    </div>
                ),
            }}
        />
    )
}

const BotAnalyticsTiles = (): JSX.Element => {
    // Drives bot tab off its own logic so bot filters don't pollute the regular Analytics tab.
    useMountedLogic(botAnalyticsLogic)
    const { tiles } = useValues(botAnalyticsLogic)

    return (
        <>
            <LemonBanner type="info" dismissKey="bot-analytics-detection-info" className="mb-4">
                Bot detection is based on user agent pattern matching. Events with no user agent are excluded from these
                results. For better coverage, send server-side HTTP logs as <code>$http_log</code> events — most bots
                don't execute JavaScript, so client-side tracking alone misses the majority of crawler traffic.
            </LemonBanner>
            <LiveBotTiles />
            <Tiles tiles={tiles} />
        </>
    )
}

const HealthTabLabel = (): JSX.Element => {
    const { hasUrgentIssues } = useValues(webAnalyticsHealthLogic)

    return (
        <div className="flex items-center gap-1.5">
            Installation Health
            {hasUrgentIssues && (
                <div className="w-4 h-4 rounded-full bg-danger flex items-center justify-center">
                    <span className="text-white text-xs font-bold">!</span>
                </div>
            )}
        </div>
    )
}

const healthTab = (): { key: ProductTab; label: JSX.Element; link: string }[] => {
    return [
        {
            key: ProductTab.HEALTH,
            label: <HealthTabLabel />,
            link: urls.webAnalyticsHealth(),
        },
    ]
}

const liveTab = (): { key: ProductTab; label: string | JSX.Element; link: string }[] => {
    return [
        {
            key: ProductTab.LIVE,
            label: 'Live',
            link: urls.webAnalyticsLive(),
        },
    ]
}

const pagePerformanceTab = (
    featureFlags: FeatureFlagsSet
): { key: ProductTab; label: string | JSX.Element; link: string }[] => {
    if (!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE]) {
        return []
    }

    return [
        {
            key: ProductTab.PAGE_PERFORMANCE,
            label: (
                <div className="flex items-center gap-1">
                    Search & AI
                    <LemonTag type="completion" className="uppercase">
                        Alpha
                    </LemonTag>
                </div>
            ),
            link: urls.webAnalyticsPagePerformance(),
        },
    ]
}

const agentAnalyticsTab = (
    featureFlags: FeatureFlagsSet
): { key: ProductTab; label: string | JSX.Element; link: string }[] => {
    if (!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_AGENT_ANALYTICS]) {
        return []
    }

    return [
        {
            key: ProductTab.AGENTS,
            label: (
                <div className="flex items-center gap-1">
                    Agents
                    <LemonTag type="completion">Alpha</LemonTag>
                </div>
            ),
            link: urls.webAnalyticsAgents(),
        },
    ]
}

const contentAutopilotTab = (
    featureFlags: FeatureFlagsSet
): { key: ProductTab; label: string | JSX.Element; link: string }[] => {
    if (!isContentAutopilotEnabled(featureFlags)) {
        return []
    }

    return [
        {
            key: ProductTab.CONTENT_AUTOPILOT,
            label: (
                <div className="flex items-center gap-1">
                    AI visibility
                    <LemonTag type="completion" className="uppercase">
                        Alpha
                    </LemonTag>
                </div>
            ),
            link: urls.webAnalyticsContentAutopilot(),
        },
    ]
}

const WebAnalyticsSurveyModal = (): JSX.Element | null => {
    const { surveyModalPath } = useValues(webAnalyticsLogic)
    const { closeSurveyModal } = useActions(webAnalyticsLogic)

    if (!surveyModalPath) {
        return null
    }

    return (
        <QuickSurveyModal
            context={{ type: QuickSurveyType.WEB_PATH, path: surveyModalPath }}
            isOpen={!!surveyModalPath}
            onCancel={closeSurveyModal}
            showFollowupToggle={true}
            modalTitle={`Survey users on ${surveyModalPath}`}
            info={`Shown to users who spend more than 15 seconds on URLs containing ${surveyModalPath}, once per unique user`}
        />
    )
}

export const WebAnalyticsDashboard = (): JSX.Element => {
    const { currentTeamId } = useValues(teamLogic)
    useOnMountEffect(() => {
        globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.ReviewWebAnalyticsDashboard)
    })

    return (
        <BindLogic logic={webAnalyticsLogic} props={{}}>
            <BindLogic logic={dataNodeCollectionLogic} props={{ key: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID }}>
                <WebAnalyticsLoadTimeTracker />
                <WebAnalyticsModal />
                <WebAnalyticsAchievementsModal />
                <WebAnalyticsSurveyModal />
                <SceneContent className="WebAnalyticsDashboard gap-y-2">
                    <>
                        <WebAnalyticsTabs />
                        {/* Empty fragment so tabs are not part of the sticky bar */}
                        <Filters tabs={<></>} />

                        <WebAnalyticsShareColleagueBanner />
                        <WebAnalyticsSavePresetNudge />
                        <ShareNudgePrompt />
                        {currentTeamId ? <MarketingAnalyticsFilterHint teamId={currentTeamId} /> : null}
                        <WebAnalyticsHealthCheck />
                        <MainContent />
                    </>
                </SceneContent>
            </BindLogic>
        </BindLogic>
    )
}

const WebAnalyticsLoadTimeTracker = (): null => {
    useMountedLogic(webAnalyticsLoadTimeLogic)
    return null
}

const WebAnalyticsTabs = (): JSX.Element => {
    const { productTab } = useValues(webAnalyticsLogic)
    const { featureFlags } = useValues(featureFlagLogic)

    const { setProductTab } = useActions(webAnalyticsLogic)

    // Tab switching shortcuts
    useShortcut({
        name: 'WebAnalyticsTab1',
        keybind: [keyBinds.tab1],
        intent: 'Web analytics tab',
        interaction: 'function',
        callback: () => setProductTab(ProductTab.ANALYTICS),
        scope: Scene.WebAnalytics,
    })
    useShortcut({
        name: 'WebAnalyticsTab2',
        keybind: [keyBinds.tab2],
        intent: 'Web vitals tab',
        interaction: 'function',
        callback: () => setProductTab(ProductTab.WEB_VITALS),
        scope: Scene.WebAnalytics,
    })
    useShortcut({
        name: 'WebAnalyticsTab3',
        keybind: [keyBinds.tab3],
        intent: 'Page reports tab',
        interaction: 'function',
        callback: () => setProductTab(ProductTab.PAGE_REPORTS),
        scope: Scene.WebAnalytics,
    })
    useShortcut({
        name: 'WebAnalyticsTab4',
        keybind: [keyBinds.tab4],
        intent: 'Health tab',
        interaction: 'function',
        callback: () => setProductTab(ProductTab.HEALTH),
        scope: Scene.WebAnalytics,
    })

    useEffect(() => {
        if (productTab === ProductTab.ANALYTICS) {
            globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.ReviewWebAnalyticsDashboard)
        }
        if (productTab === ProductTab.WEB_VITALS) {
            globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.VisitWebVitalsDashboard)
        }
    }, [productTab])

    return (
        <LemonTabs<ProductTab>
            // Bots lives inside AI visibility, so its route keeps that tab active.
            activeKey={productTab === ProductTab.BOT_ANALYTICS ? ProductTab.CONTENT_AUTOPILOT : productTab}
            onChange={setProductTab}
            tabs={[
                { key: ProductTab.ANALYTICS, label: 'Web analytics', link: '/web' },
                { key: ProductTab.WEB_VITALS, label: 'Web vitals', link: '/web/web-vitals' },
                {
                    key: ProductTab.PAGE_REPORTS,
                    label: featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PAGE_REPORTS_DIRECTORY] ? (
                        <PageReportsTabLabel />
                    ) : (
                        'Page reports'
                    ),
                    link: '/web/page-reports',
                },
                ...liveTab(),
                ...pagePerformanceTab(featureFlags),
                ...agentAnalyticsTab(featureFlags),
                ...contentAutopilotTab(featureFlags),
                ...healthTab(),
            ]}
            sceneInset
            className="-mt-4"
        />
    )
}

const getEmptyOnboardingContent = (
    featureFlags: FeatureFlagsSet,
    currentTeamLoading: boolean,
    currentTeam: TeamType | TeamPublicType | null,
    productTab: ProductTab
): JSX.Element | null => {
    if (!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_EMPTY_ONBOARDING]) {
        return null
    }

    if (currentTeamLoading && !currentTeam) {
        return <LemonSkeleton className="col-span-full w-full" />
    }

    if (productTab === ProductTab.ANALYTICS && !currentTeam?.ingested_event) {
        return (
            <div className="col-span-full w-full">
                <ProductIntroduction
                    thingName="event"
                    isEmpty={true}
                    titleOverride="Nothing to investigate yet!"
                    description="Install PostHog on your site or app to start capturing events. Head to the installation guide to get set up in just a few minutes."
                    hogLayout="responsive"
                    useMainContentContainerQueries
                    className="p-4 @min-[48rem]/main-content:p-8"
                    hogClassName="w-40 sm:w-40 lg:w-56"
                    actionElementOverride={
                        <div className="flex flex-col @min-[30rem]/main-content:flex-row items-center gap-x-2 gap-y-3">
                            <LemonButton
                                type="primary"
                                to={urls.onboarding({
                                    productKey: ProductKey.WEB_ANALYTICS,
                                    stepKey: OnboardingStepKey.INSTALL,
                                })}
                                data-attr="web-analytics-onboarding"
                            >
                                Open installation guide
                            </LemonButton>
                            <span className="text-muted-alt text-center">
                                or{' '}
                                <Link target="_blank" to="/web/web-vitals">
                                    Set up web vitals while you wait
                                </Link>
                            </span>
                        </div>
                    }
                />
            </div>
        )
    }

    return null
}