Skip to content

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

82.6 KB
Raw Blame
import type { ChartOptions, GridLineOptions } from 'billboard.js'
import { area, areaSpline, spline, bar, line, zoom } from 'billboard.js'
import * as d3 from 'd3'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezonePlugin from 'dayjs/plugin/timezone'
import type i18next from 'i18next'
import JSZip from 'jszip'
import _fill from 'lodash/fill'
import _forEach from 'lodash/forEach'
import _includes from 'lodash/includes'
import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _map from 'lodash/map'
import _orderBy from 'lodash/orderBy'
import _reduce from 'lodash/reduce'
import _replace from 'lodash/replace'
import _round from 'lodash/round'
import _size from 'lodash/size'
import _some from 'lodash/some'
import _split from 'lodash/split'
import _startsWith from 'lodash/startsWith'
import _sum from 'lodash/sum'
import _toNumber from 'lodash/toNumber'
import _toString from 'lodash/toString'
import {
  QuestionMarkIcon,
  GlobeIcon,
  CompassIcon,
  CpuIcon,
  FileTextIcon,
  GameControllerIcon,
  MapPinIcon,
  MonitorPlayIcon,
  MonitorIcon,
  ShareIcon,
  DeviceMobileIcon,
  DeviceTabletIcon,
  DevicesIcon,
  TelevisionIcon,
  WatchIcon,
  VirtualRealityIcon,
  TranslateIcon,
  ArrowCircleRightIcon,
} from '@phosphor-icons/react'

import {
  TimeFormat,
  chartTypes,
  tbsFormatMapper,
  tbsFormatMapper24h,
  tbsFormatMapperTooltip,
  tbsFormatMapperTooltip24h,
  PROJECT_TABS,
  isSelfhosted,
  BROWSER_LOGO_MAP,
  OS_LOGO_MAP,
  OS_LOGO_MAP_DARK,
} from '~/lib/constants'
import { Entry } from '~/lib/models/Entry'
import { AnalyticsFunnel, Annotation } from '~/lib/models/Project'
import {
  getTimeFromSeconds,
  getStringFromTime,
  sumArrays,
  nFormatter,
  escapeHtml,
} from '~/utils/generic'
import countries from '~/utils/isoCountries'
import { downloadBlob } from '~/utils/download'

import { TrafficLogResponse } from './interfaces/traffic'
import {
  attachDataPointClickHandlers,
  type ChartDataPointClick,
} from './utils/chartPoint'

dayjs.extend(utc)
dayjs.extend(timezonePlugin)

// Max length of annotation text displayed on chart (truncated with "...")
const ANNOTATION_CHART_TEXT_MAX_LENGTH = 25

export const getAnnotationGridLines = (
  annotations?: Annotation[],
): GridLineOptions[] =>
  _map(annotations || [], (annotation) => ({
    value: dayjs(annotation.date).toDate(),
    text:
      annotation.text.length > ANNOTATION_CHART_TEXT_MAX_LENGTH
        ? `${annotation.text.substring(0, ANNOTATION_CHART_TEXT_MAX_LENGTH)}...`
        : annotation.text,
    class: `annotation-line annotation-id-${annotation.id}`,
    position: 'start',
  }))

const getAvg = (arr: any) => {
  const total = _reduce(arr, (acc, c) => acc + c, 0)
  return total / _size(arr)
}

const getSum = (arr: any) => {
  return _reduce(arr, (acc, c) => acc + c, 0)
}

const calculateOptimalTicks = (
  data: number[],
  targetCount: number = 6,
): number[] => {
  const min = Math.min(...data.filter((n) => n !== undefined && n !== null))
  const max = Math.max(...data.filter((n) => n !== undefined && n !== null))

  if (min === max) {
    return max === 0 ? [0, 1] : [0, max * 1.2]
  }

  const upperBound = Math.ceil(max * 1.2)

  const roughStep = upperBound / (targetCount - 1)

  let niceStep: number
  if (roughStep <= 1) {
    niceStep = 1
  } else if (roughStep <= 2) {
    niceStep = 2
  } else if (roughStep <= 5) {
    niceStep = 5
  } else if (roughStep <= 10) {
    niceStep = 10
  } else if (roughStep <= 20) {
    niceStep = 20
  } else if (roughStep <= 25) {
    niceStep = 25
  } else if (roughStep <= 50) {
    niceStep = 50
  } else {
    // For larger numbers, round to nearest 10^n or 5*10^n
    const magnitude = Math.pow(10, Math.floor(Math.log10(roughStep)))
    const normalized = roughStep / magnitude
    if (normalized <= 2) {
      niceStep = 2 * magnitude
    } else if (normalized <= 5) {
      niceStep = 5 * magnitude
    } else {
      niceStep = 10 * magnitude
    }
  }

  const ticks: number[] = []
  for (let i = 0; i <= upperBound; i += niceStep) {
    ticks.push(i)
  }

  if (ticks[ticks.length - 1] < max) {
    ticks.push(ticks[ticks.length - 1] + niceStep)
  }

  return ticks
}

const trendline = (data: any[]): string[] => {
  const xData = _map(_fill(new Array(_size(data)), 0), (_, i) => i + 1)
  const yData = data

  const xMean = getAvg(xData)
  const yMean = getAvg(yData)

  const xMinusxMean = _map(xData, (val) => val - xMean)
  const yMinusyMean = _map(yData, (val) => val - yMean)

  const xMinusxMeanSq = _map(xMinusxMean, (val) => val ** 2)

  const xy = []
  for (let x = 0; x < _size(data); ++x) {
    xy.push(xMinusxMean[x] * yMinusyMean[x])
  }

  const xySum = getSum(xy)

  const b1 = xySum / getSum(xMinusxMeanSq)

  const b0 = yMean - b1 * xMean

  const trendData = []
  for (let x = 0; x < _size(data); ++x) {
    const y = _round(b0 + b1 * x, 2)
    if (y < 0) {
      trendData.push(_toString(0))
    } else {
      trendData.push(_toString(y))
    }
  }

  return trendData
}

const getExportFilename = (prefix: string) => {
  // turn something like 2022-03-02T19:31:00.100Z into 2022-03-02
  const date = _split(
    _replace(_split(new Date().toISOString(), '.')[0], /:/g, '-'),
    'T',
  )[0]
  return `${prefix}-${date}.zip`
}

const convertToCSV = (array: any[]) => {
  let str = 'name,value,percentage\r\n'

  for (let i = 0; i < _size(array); ++i) {
    const [title, value, percentage] = array[i]

    str += `"${title.replace(/"/g, '""')}",${value},${percentage}\r\n`
  }

  return str
}

const onCSVExportClick = (
  data: {
    data: any
    types: any
  },
  pid: string,
  tnMapping: Record<string, string>,
  language: string,
) => {
  const { data: rowData, types } = data
  const zip = new JSZip()

  _forEach(types, (item) => {
    if (_isEmpty(rowData[item])) {
      return null
    }

    const total = _reduce(rowData[item], (acc, { count }) => acc + count, 0)

    const csvData = _map(rowData[item], (entry: Entry) => {
      const perc = _round((entry.count / total) * 100 || 0, 2)

      const title = _toString(
        item === 'cc' || item === 'country'
          ? countries.getName(entry.name || '', language)
          : entry.name,
      )

      return [
        /^[=+\-@]/.test(title) ? `'${title}` : title,
        entry.count,
        `${perc}%`,
      ]
    })

    zip.file(`${tnMapping[item]}.csv`, convertToCSV(csvData))
  })

  zip.generateAsync({ type: 'blob' }).then((content) => {
    downloadBlob(content, getExportFilename(`swetrix-${pid}`))
  })
}

const CHART_METRICS_MAPPING = {
  unique: 'unique',
  views: 'views',
  bounce: 'bounce',
  viewsPerUnique: 'viewsPerUnique',
  trendlines: 'trendlines',
  sessionDuration: 'sessionDuration',
  liveVisitors: 'liveVisitors',
  customEvents: 'customEvents',
  cumulativeMode: 'cumulativeMode',
  revenue: 'revenue',
} as const

const CHART_METRICS_MAPPING_PERF = {
  quantiles: 'quantiles',
  full: 'full',
  timing: 'timing',
  network: 'network',
  frontend: 'frontend',
  backend: 'backend',
}

const CHART_MEASURES_MAPPING_PERF = {
  // Dependent on metric
  average: 'average',
  median: 'median',
  p95: 'p95',
  p75: 'p75',

  // Independent measure that provides it's own metrics
  quantiles: 'quantiles',
}

// function to filter the data for the chart
const getColumns = (
  chart: TrafficLogResponse['chart'] & { [key: string]: number[] },
  activeChartMetrics: Record<string, boolean>,
  compareChart?: TrafficLogResponse['chart'] & { [key: string]: number[] },
) => {
  const {
    views,
    bounce,
    viewsPerUnique,
    unique,
    trendlines,
    sessionDuration,
    liveVisitors,
    occurrences,
    avgResponseTime,
  } = activeChartMetrics

  const columns: any[] = [['x', ..._map(chart.x, (el) => dayjs(el).toDate())]]

  if (unique) {
    columns.push(['unique', ...chart.uniques])
    if (trendlines) {
      columns.push(['trendlineUnique', ...trendline(chart.uniques)])
    }

    if (compareChart?.uniques) {
      columns.push(['uniqueCompare', ...compareChart.uniques])
    }
  }

  if (occurrences) {
    columns.push(['occurrences', ...chart.occurrences])

    if (compareChart?.occurrences) {
      columns.push(['occurrencesCompare', ...compareChart.occurrences])
    }
  }

  if (avgResponseTime) {
    columns.push(['avgResponseTime', ...chart.avgResponseTime])
  }

  if (views) {
    columns.push(['total', ...chart.visits])
    if (trendlines) {
      columns.push(['trendlineTotal', ...trendline(chart.visits)])
    }

    if (compareChart?.visits) {
      columns.push(['totalCompare', ...compareChart.visits])
    }
  }

  if (bounce) {
    const bounceArray = _map(chart.uniques, (sessions, i) => {
      if (!sessions) {
        return 0
      }

      return (
        _round(
          (_toNumber(chart.bounces?.[i]) * 100) / _toNumber(sessions),
          1,
        ) || 0
      )
    })
    columns.push(['bounce', ...bounceArray])
  }

  if (viewsPerUnique) {
    const viewsPerUniqueArray = _map(chart.visits, (el, i) => {
      if (chart.uniques[i] === 0 || chart.uniques[i] === undefined) {
        return 0
      }
      return _round(_toNumber(el) / _toNumber(chart.uniques[i]), 1)
    })
    columns.push(['viewsPerUnique', ...viewsPerUniqueArray])
  }

  if (sessionDuration) {
    columns.push(['sessionDuration', ...chart.sdur])

    if (compareChart?.sdur) {
      columns.push(['sessionDurationCompare', ...compareChart.sdur])
    }
  }

  if (liveVisitors && chart.concurrency) {
    columns.push(['liveVisitors', ...chart.concurrency])

    if (compareChart?.concurrency) {
      columns.push(['liveVisitorsCompare', ...compareChart.concurrency])
    }
  }

  // Revenue data (if available) - revenue as bars with refunds stacked on top
  if (activeChartMetrics.revenue && chart.revenue) {
    columns.push(['revenue', ...chart.revenue])
    // Add refundsAmount if available for stacked bar display
    if (chart.refundsAmount) {
      const hasAnyRefunds = _some(
        chart.refundsAmount,
        (v) => Number(v || 0) > 0,
      )
      if (hasAnyRefunds) {
        columns.push(['refundsAmount', ...chart.refundsAmount])
      }
    }
  }

  return columns
}

const getColumnsPerf = (
  chart: Record<string, string[]>,
  activeChartMetrics: string,
  compareChart?: Record<string, string[]>,
) => {
  const columns: any[] = [['x', ..._map(chart.x, (el) => dayjs(el).toDate())]]

  if (
    activeChartMetrics === CHART_METRICS_MAPPING_PERF.quantiles &&
    chart?.p50 &&
    chart?.p75 &&
    chart?.p95
  ) {
    columns.push(['p50', ...chart.p50])
    columns.push(['p75', ...chart.p75])
    columns.push(['p95', ...chart.p95])

    if (compareChart?.p50 && compareChart?.p75 && compareChart?.p95) {
      columns.push(['p50Compare', ...compareChart.p50])
      columns.push(['p75Compare', ...compareChart.p75])
      columns.push(['p95Compare', ...compareChart.p95])
    }
  }

  if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.full && chart.dns) {
    columns.push(['dns', ...chart.dns])
    columns.push(['tls', ...chart.tls])
    columns.push(['conn', ...chart.conn])
    columns.push(['response', ...chart.response])
    columns.push(['render', ...chart.render])
    columns.push(['dom_load', ...chart.domLoad])
    columns.push(['ttfb', ...chart.ttfb])

    if (
      compareChart?.dns &&
      compareChart?.tls &&
      compareChart?.conn &&
      compareChart?.response &&
      compareChart?.render &&
      compareChart?.domLoad &&
      compareChart?.ttfb
    ) {
      columns.push(['dnsCompare', ...compareChart.dns])
      columns.push(['tlsCompare', ...compareChart.tls])
      columns.push(['connCompare', ...compareChart.conn])
      columns.push(['responseCompare', ...compareChart.response])
      columns.push(['renderCompare', ...compareChart.render])
      columns.push(['dom_loadCompare', ...compareChart.domLoad])
      columns.push(['ttfbCompare', ...compareChart.ttfb])
    }
  }

  if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.timing && chart.ttfb) {
    columns.push(['frontend', ...sumArrays(chart.render, chart.domLoad)])
    columns.push([
      'network',
      ...sumArrays(chart.dns, chart.tls, chart.conn, chart.response),
    ])
    columns.push(['backend', ...chart.ttfb])

    if (
      compareChart?.dns &&
      compareChart?.tls &&
      compareChart?.conn &&
      compareChart?.response &&
      compareChart?.render &&
      compareChart?.domLoad &&
      compareChart?.ttfb
    ) {
      columns.push([
        'frontendCompare',
        ...sumArrays(compareChart.render, compareChart.domLoad),
      ])
      columns.push([
        'networkCompare',
        ...sumArrays(
          compareChart.dns,
          compareChart.tls,
          compareChart.conn,
          compareChart.response,
        ),
      ])
      columns.push(['backendCompare', ...compareChart.ttfb])
    }
  }

  if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.network && chart.dns) {
    columns.push(['dns', ...chart.dns])
    columns.push(['tls', ...chart.tls])
    columns.push(['conn', ...chart.conn])
    columns.push(['response', ...chart.response])

    if (
      compareChart?.dns &&
      compareChart?.tls &&
      compareChart?.conn &&
      compareChart?.response
    ) {
      columns.push(['dnsCompare', ...compareChart.dns])
      columns.push(['tlsCompare', ...compareChart.tls])
      columns.push(['connCompare', ...compareChart.conn])
      columns.push(['responseCompare', ...compareChart.response])
    }
  }

  if (
    activeChartMetrics === CHART_METRICS_MAPPING_PERF.frontend &&
    chart.render
  ) {
    columns.push(['render', ...chart.render])
    columns.push(['dom_load', ...chart.domLoad])

    if (compareChart?.render && compareChart?.domLoad) {
      columns.push(['renderCompare', ...compareChart.render])
      columns.push(['dom_loadCompare', ...compareChart.domLoad])
    }
  }

  if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.backend && chart.ttfb) {
    columns.push(['ttfb', ...chart.ttfb])

    if (compareChart?.ttfb) {
      columns.push(['ttfbCompare', ...compareChart.ttfb])
    }
  }

  return columns
}

const getValueForTooltipPerfomance = (
  chart: Record<string, string[]>,
  id: string,
  index: number,
) => {
  if (id === 'p50' || id === 'p75' || id === 'p95') {
    return chart[id] ? chart[id][index] : 0
  }

  if (
    id === 'dns' ||
    id === 'tls' ||
    id === 'conn' ||
    id === 'response' ||
    id === 'render' ||
    id === 'ttfb'
  ) {
    return chart[id] ? chart[id][index] : 0
  }

  if (id === 'dom_load') {
    return chart.domLoad ? chart.domLoad[index] : 0
  }

  if (id === 'frontend') {
    const sum = sumArrays(chart.render, chart.domLoad)
    return sum ? sum[index] : 0
  }

  if (id === 'network') {
    const sum = sumArrays(chart.dns, chart.tls, chart.conn, chart.response)
    return sum ? sum[index] : 0
  }

  if (id === 'backend') {
    return chart.ttfb ? chart.ttfb[index] : 0
  }

  return 0
}

const stringToColour = (str: string) => {
  let hash = 0

  // Loop through each character in the string
  for (let i = 0; i < str.length; i++) {
    // Get the ASCII code for the current character
    const charCode = str.charCodeAt(i)
    // Update the hash value using a simple algorithm
    hash = charCode + ((hash << 5) - hash)
  }

  // Initialise color value to #
  let colour = '#'

  // Generate 3-byte color code (RRGGBB)
  for (let i = 0; i < 3; i++) {
    // Get the next 8 bits of the hash value
    const value = (hash >> (i * 8)) & 0xff
    // Convert the value to a 2-digit hex string
    const hexString = `00${value.toString(16)}`.substr(-2)
    // Append the hex string to the color value
    colour += hexString
  }

  // Return the resulting color value
  return colour
}

const CUSTOM_EVENTS_CHART_COLORS = [
  '#7C3AED',
  '#2563EB',
  '#0891B2',
  '#0D9488',
  '#16A34A',
  '#CA8A04',
  '#EA580C',
  '#DC2626',
  '#DB2777',
  '#7C2D12',
]

// setting the default values for the time period dropdown
const noRegionPeriods = ['custom', 'yesterday']

// function to get the settings and data for the chart(main diagram)
const getSettings = (
  chart: TrafficLogResponse['chart'] & { [key: string]: number[] },
  timeBucket: string,
  activeChartMetrics: Record<string, boolean>,
  applyRegions: boolean,
  timeFormat: string,
  rotateXAxis: boolean,
  chartType: string,
  customEvents?: Record<string, string[]>,
  compareChart?: TrafficLogResponse['chart'] & { [key: string]: number[] },
  onZoom?: (domain: [Date, Date] | null) => void,
  enableZoom?: boolean,
  annotations?: Annotation[],
  period?: string,
  timezone?: string,
  onDataPointClick?: ChartDataPointClick,
  dataPointClickLabel?: string,
): ChartOptions => {
  const xAxisSize = _size(chart.x)

  const lines = getAnnotationGridLines(annotations)
  const modifiedChart = { ...chart }
  let regions
  const customEventsToArray = customEvents
    ? _map(_keys(customEvents), (el) => {
        return [el, ...customEvents[el]]
      })
    : []

  let customEventsColors: Record<string, string> = {}

  if (_isEmpty(compareChart)) {
    _forEach(_keys(customEvents), (el) => {
      customEventsColors = {
        ...customEventsColors,
        [el]: stringToColour(el),
      }
    })
  }

  const columns = getColumns(modifiedChart, activeChartMetrics, compareChart)

  // Calculate optimal Y axis ticks based on the data
  const allYValues: number[] = []
  if (activeChartMetrics.unique && chart.uniques) {
    allYValues.push(
      ...chart.uniques.filter((n) => n !== undefined && n !== null),
    )
  }
  if (activeChartMetrics.views && chart.visits) {
    allYValues.push(
      ...chart.visits.filter((n) => n !== undefined && n !== null),
    )
  }
  if (activeChartMetrics.occurrences && chart.occurrences) {
    allYValues.push(
      ...chart.occurrences.filter((n) => n !== undefined && n !== null),
    )
  }
  if (activeChartMetrics.liveVisitors && chart.concurrency) {
    allYValues.push(
      ...chart.concurrency.filter((n) => n !== undefined && n !== null),
    )
  }

  const optimalTicks =
    allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined

  if (applyRegions) {
    let regionStart

    if (period === 'today' && timezone) {
      // Get current time in the selected timezone
      const nowInTz = dayjs().tz(timezone)
      // Format it without timezone offset to match chart.x strings
      const nowStr = nowInTz.format('YYYY-MM-DD HH:mm:ss')
      const nowDate = dayjs(nowStr).toDate()

      let currentIndex = -1
      for (let i = 0; i < xAxisSize; i++) {
        const pointDate = dayjs(chart.x[i]).toDate()
        if (pointDate <= nowDate) {
          currentIndex = i
        } else {
          break
        }
      }

      if (currentIndex > 0) {
        regionStart = dayjs(chart.x[currentIndex - 1]).toDate()
      } else if (currentIndex === 0) {
        regionStart = dayjs(chart.x[0]).toDate()
      } else {
        regionStart =
          xAxisSize > 1
            ? dayjs(chart.x[xAxisSize - 2]).toDate()
            : dayjs(chart.x[xAxisSize - 1]).toDate()
      }
    } else {
      if (xAxisSize > 1) {
        regionStart = dayjs(chart.x[xAxisSize - 2]).toDate()
      } else {
        regionStart = dayjs(chart.x[xAxisSize - 1]).toDate()
      }
    }

    const regionObj: any = {
      start: regionStart,
      style: {
        dasharray: '6 2',
      },
    }

    regions = {
      unique: [regionObj],
      total: [regionObj],
      bounce: [regionObj],
      viewsPerUnique: [regionObj],
      liveVisitors: [regionObj],
    }
  }

  return {
    data: {
      x: 'x',
      columns: [...columns, ...customEventsToArray],
      onclick: onDataPointClick
        ? (d: any) => {
            if (d?.x) {
              onDataPointClick({
                x: d.x,
                index: d.index,
                xValue: chart.x?.[d.index],
              })
            }
          }
        : undefined,
      types: {
        unique: chartType === chartTypes.line ? area() : bar(),
        uniqueCompare: chartType === chartTypes.line ? line() : bar(),
        total: chartType === chartTypes.line ? area() : bar(),
        totalCompare: chartType === chartTypes.line ? line() : bar(),
        bounce: chartType === chartTypes.line ? spline() : bar(),
        bounceCompare: chartType === chartTypes.line ? spline() : bar(),
        viewsPerUnique: chartType === chartTypes.line ? spline() : bar(),
        trendlineUnique: spline(),
        trendlineTotal: spline(),
        sessionDuration: chartType === chartTypes.line ? spline() : bar(),
        sessionDurationCompare:
          chartType === chartTypes.line ? spline() : bar(),
        liveVisitors: chartType === chartTypes.line ? spline() : bar(),
        liveVisitorsCompare: chartType === chartTypes.line ? spline() : bar(),
        // Revenue is always bars (stacked with refunds)
        revenue: bar(),
        refundsAmount: bar(),
      },
      colors: {
        unique: '#2563EB',
        uniqueCompare: 'rgba(37, 99, 235, 0.4)',
        total: '#D97706',
        totalCompare: 'rgba(217, 119, 6, 0.4)',
        bounce: '#2AC4B3',
        bounceCompare: 'rgba(42, 196, 179, 0.4)',
        viewsPerUnique: '#F87171',
        trendlineUnique: '#436abf',
        trendlineTotal: '#eba14b',
        sessionDuration: '#c945ed',
        sessionDurationCompare: 'rgba(201, 69, 237, 0.4)',
        // Distinct from every CUSTOM_EVENTS_CHART_COLORS entry so the legend
        // stays unambiguous when both series are shown
        liveVisitors: '#10B981',
        liveVisitorsCompare: 'rgba(16, 185, 129, 0.4)',
        revenue: '#ea580c', // orange-600 for net revenue
        refundsAmount: 'rgba(234, 88, 12, 0.25)', // light orange fill for refunds overlay
        ...customEventsColors,
      },
      // Stack revenue and refundsAmount together
      groups: activeChartMetrics.revenue
        ? [['revenue', 'refundsAmount']]
        : undefined,
      // Prevent billboard/c3 from auto-reordering stacked series
      // (we need refunds stacked on top of revenue consistently)
      order: activeChartMetrics.revenue ? null : undefined,
      regions,
      axes: {
        bounce: 'y2',
        sessionDuration: 'y2',
        revenue: 'y2',
        refundsAmount: 'y2',
      },
    },
    grid: {
      x: {
        lines,
      },
      y: {
        show: true,
      },
    },
    transition: {
      duration: 0,
    },
    resize: {
      auto: true,
      timer: true,
    },
    axis: {
      x: {
        clipPath: false,
        tick: {
          fit: true,
          rotate: rotateXAxis ? 45 : 0,

          format:
            // @ts-expect-error
            timeFormat === TimeFormat['24-hour']
              ? (x: string) =>
                  d3.timeFormat(tbsFormatMapper24h[timeBucket])(
                    x as unknown as Date,
                  )
              : (x: string) =>
                  d3.timeFormat(tbsFormatMapper[timeBucket])(
                    x as unknown as Date,
                  ),
        },
        localtime: timeFormat === TimeFormat['24-hour'],
        type: 'timeseries',
      },
      y: {
        tick: {
          format: (d: number) => nFormatter(d, 1),
          values: optimalTicks,
        },
        show: true,
        inner: true,
      },
      y2: {
        show:
          activeChartMetrics.bounce ||
          activeChartMetrics.sessionDuration ||
          activeChartMetrics.revenue,
        tick: {
          // @ts-expect-error
          format: activeChartMetrics.bounce
            ? (d: string) => `${d}%`
            : activeChartMetrics.revenue
              ? (d: number) => `$${nFormatter(d, 1)}`
              : (d: string) => getStringFromTime(getTimeFromSeconds(d)),
        },
        min: activeChartMetrics.bounce ? 10 : undefined,
        max: activeChartMetrics.bounce ? 100 : undefined,
        default: activeChartMetrics.bounce ? [10, 100] : undefined,
      },
    },
    tooltip: {
      contents: (item, _, __, color) => {
        const typesOptionsToTypesCompare: Record<string, string> = {
          unique: 'uniques',
          total: 'visits',
          sessionDuration: 'sdur',
          liveVisitors: 'concurrency',
        }

        if (_isEmpty(compareChart)) {
          return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-md z-50'>
          <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800 sticky top-0 bg-gray-50 dark:bg-slate-900'>${
            timeFormat === TimeFormat['24-hour']
              ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
              : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
          }</li>
          ${_map(
            item,
            (el: {
              id: string
              index: number
              name: string
              value: string
              x: Date
            }) => {
              if (el.id === 'sessionDuration') {
                return `
              <li class='flex justify-between items-center py-px leading-snug'>
                <div class='flex items-center min-w-0 mr-4'>
                  <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
                  <span class="truncate">${el.name}</span>
                </div>
                <span class='font-mono whitespace-nowrap'>${getStringFromTime(getTimeFromSeconds(el.value))}</span>
              </li>
              `
              }

              if (el.id === 'trendlineUnique' || el.id === 'trendlineTotal') {
                return ''
              }

              // Format revenue and refunds as currency
              if (el.id === 'revenue') {
                return `
              <li class='flex justify-between items-center py-px leading-snug'>
                <div class='flex items-center min-w-0 mr-4'>
                  <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style='background-color:${color(el.id)}'></div>
                  <span class="truncate">${el.name}</span>
                </div>
                <span class='font-mono whitespace-nowrap'>$${nFormatter(Number(el.value) || 0, 2)}</span>
              </li>
              `
              }

              if (el.id === 'refundsAmount') {
                return `
              <li class='flex justify-between items-center py-px leading-snug'>
                <div class='flex items-center min-w-0 mr-4'>
                  <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style='background-color:rgba(234,88,12,0.25);border:1.5px dashed #ea580c'></div>
                  <span class="truncate">${el.name}</span>
                </div>
                <span class='font-mono whitespace-nowrap'>$${nFormatter(Number(el.value) || 0, 2)}</span>
              </li>
              `
              }

              return `
            <li class='flex justify-between items-center py-px leading-snug'>
              <div class='flex items-center min-w-0 mr-4'>
                <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
                <span class="truncate">${el.name}</span>
              </div>
              <span class='font-mono whitespace-nowrap'>${el.value}</span>
            </li>
            `
            },
          ).join(
            '',
          )}${onDataPointClick ? `<li class='pt-1 mt-1 border-t border-gray-200 dark:border-slate-700/80 text-[10px] text-gray-400 dark:text-slate-500'>${dataPointClickLabel}</li>` : ''}</ul>`
        }

        // Get dates from first item
        const firstItem = item[0]
        const firstIndex = firstItem?.index ?? 0
        const currentX = firstItem?.x as Date | string | undefined
        const currentDate = currentX
          ? currentX instanceof Date
            ? currentX
            : new Date(currentX)
          : null
        const compareDate = compareChart?.x?.[firstIndex]

        const xDataValue = currentDate
          ? timeFormat === TimeFormat['24-hour']
            ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(currentDate)
            : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(currentDate)
          : ''
        const xDataValueCompare = compareDate
          ? timeFormat === TimeFormat['24-hour']
            ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
                dayjs(compareDate).toDate(),
              )
            : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
                dayjs(compareDate).toDate(),
              )
          : ''

        // Filter out compare series items
        const filteredItems = item.filter(
          (el: { id: string }) =>
            el.id !== 'uniqueCompare' &&
            el.id !== 'totalCompare' &&
            el.id !== 'bounceCompare' &&
            el.id !== 'sessionDurationCompare' &&
            el.id !== 'liveVisitorsCompare',
        )

        // Build current period section
        const currentSection = `
          <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800'>${xDataValue}</li>
          ${_map(
            filteredItems,
            (el: { id: string; name: string; value: string }) => {
              const displayValue =
                el.id === 'sessionDuration'
                  ? getStringFromTime(getTimeFromSeconds(el.value))
                  : el.value
              return `
              <li class='flex justify-between items-center py-px leading-snug'>
                <div class='flex items-center min-w-0 mr-4'>
                  <div class='w-2.5 h-2.5 rounded-xs mr-1.5 shrink-0' style='background-color:${color(el.id)}'></div>
                  <span class="truncate">${el.name}</span>
                </div>
                <span class='font-mono whitespace-nowrap'>${displayValue}</span>
              </li>`
            },
          ).join('')}`

        // Build compare period section
        const compareSection = xDataValueCompare
          ? `
          <li class='font-semibold pb-1 mb-1 mt-3 pt-2 border-t border-b border-gray-200 dark:border-slate-800'>${xDataValueCompare}</li>
          ${_map(
            filteredItems,
            (el: { id: string; index: number; name: string }) => {
              const compareValue =
                el.id === 'sessionDuration'
                  ? getStringFromTime(
                      getTimeFromSeconds(
                        compareChart?.[typesOptionsToTypesCompare?.[el.id]]?.[
                          el.index
                        ],
                      ),
                    )
                  : compareChart?.[typesOptionsToTypesCompare[el.id]]?.[
                      el.index
                    ]
              if (compareValue === undefined || compareValue === null) return ''
              return `
              <li class='flex justify-between items-center py-px leading-snug'>
                <div class='flex items-center min-w-0 mr-4'>
                  <div class='w-2.5 h-2.5 rounded-xs mr-1.5 shrink-0 opacity-60' style='background-color:${color(el.id)}'></div>
                  <span class="truncate opacity-75">${el.name}</span>
                </div>
                <span class='font-mono whitespace-nowrap opacity-75'>${compareValue}</span>
              </li>`
            },
          ).join('')}`
          : ''

        return `
        <ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-md z-50'>
          ${currentSection}
          ${compareSection}
          ${onDataPointClick ? `<li class='pt-1 mt-1 border-t border-gray-200 dark:border-slate-700/80 text-[10px] text-gray-400 dark:text-slate-500'>${dataPointClickLabel}</li>` : ''}
        </ul>`
      },
    },
    point:
      chartType === chartTypes.bar
        ? {}
        : {
            focus: {
              only: xAxisSize > 1,
              expand: onDataPointClick ? { enabled: true, r: 4 } : undefined,
            },
            pattern: ['circle'],
            r: 4,
            sensitivity: onDataPointClick ? 50 : undefined,
          },
    legend: {
      item: {
        tile: {
          type: 'circle',
          width: 10,
          r: 3,
        },
      },
      hide: [
        'uniqueCompare',
        'totalCompare',
        'bounceCompare',
        'sessionDurationCompare',
        'liveVisitorsCompare',
        'refundsAmount',
      ],
    },
    area: {
      linearGradient: true,
    },
    bar: {
      linearGradient: !activeChartMetrics.revenue, // Disable gradient when revenue is shown
      radius: {
        ratio: 0.15,
      },
    },
    onrendered:
      activeChartMetrics.revenue || onDataPointClick
        ? function () {
            const chartInstance = this as any

            if (!chartInstance || !chartInstance.$) return

            try {
              if (activeChartMetrics.revenue && chartInstance.$.bar?.bars) {
                chartInstance.$.bar.bars.each(function (
                  this: SVGPathElement,
                  d: any,
                ) {
                  const value = Number(d?.value || 0)

                  if (d?.id === 'refundsAmount') {
                    if (value > 0) {
                      this.style.stroke = '#ea580c'
                      this.style.strokeWidth = '1.5px'
                      this.style.strokeDasharray = '6,4'
                      this.style.display = ''
                    } else {
                      this.style.strokeDasharray = ''
                      this.style.strokeWidth = '0'
                      this.style.stroke = 'none'
                      this.style.display = 'none'
                    }
                  } else if (d?.id === 'revenue') {
                    if (value === 0) {
                      this.style.strokeWidth = '0'
                      this.style.stroke = 'none'
                      this.style.display = 'none'
                    } else {
                      this.style.strokeWidth = '1.5px'
                      this.style.stroke = '#ea580c'
                      this.style.display = ''
                    }
                  }
                })
              }

              attachDataPointClickHandlers(
                chartInstance,
                columns,
                onDataPointClick,
                chart.x,
              )
            } catch {
              // ignore
            }
          }
        : undefined,
    zoom:
      onZoom && enableZoom !== false
        ? {
            enabled: zoom(),
            type: 'drag',
            onzoom: onZoom,
            resetButton: false,
          }
        : undefined,
    bindto: '#dataChart',
  }
}

// Stacked bar chart for custom events
const getSettingsCustomEventsStacked = (
  chart:
    | { x: string[]; events: Record<string, Array<number | string>> }
    | undefined,
  timeBucket: string,
  rotateXAxis: boolean,
  timeFormat: string,
): ChartOptions => {
  if (!chart || _isEmpty(chart.x) || _isEmpty(chart.events)) {
    return {}
  }

  const eventTotals = _map(_keys(chart.events), (id) => ({
    id,
    total: _sum(_map(chart.events[id] || [], (v) => Number(v) || 0)),
  }))
  const eventIds = _map(
    _orderBy(eventTotals, 'total', 'desc'),
    'id',
  ) as string[]

  const columns: any[] = [['x', ..._map(chart.x, (el) => dayjs(el).toDate())]]
  eventIds.forEach((id) => {
    columns.push([id, ...(chart.events[id] || [])])
  })

  const types: Record<string, any> = _reduce(
    eventIds,
    (acc: Record<string, any>, id: string) => {
      acc[id] = line()
      return acc
    },
    {},
  )

  const eventSeriesStyles = _reduce(
    eventIds,
    (acc: Record<string, { fill: string }>, id: string, index: number) => {
      const fill =
        CUSTOM_EVENTS_CHART_COLORS[index % CUSTOM_EVENTS_CHART_COLORS.length]
      acc[id] = { fill }
      return acc
    },
    {},
  )
  const colors: Record<string, string> = _reduce(
    eventIds,
    (acc: Record<string, string>, id: string) => {
      acc[id] = eventSeriesStyles[id].fill
      return acc
    },
    {},
  )

  const allYValues: number[] = _reduce(
    eventIds,
    (acc: number[], id: string) => {
      acc.push(..._map(chart.events[id] || [], (v) => Number(v) || 0))
      return acc
    },
    [],
  )
  const optimalTicks =
    allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined

  return {
    data: {
      x: 'x',
      columns,
      types,
      colors,
    },
    grid: {
      y: {
        show: true,
      },
    },
    axis: {
      x: {
        clipPath: false,
        tick: {
          fit: true,
          rotate: rotateXAxis ? 45 : 0,
          format:
            // @ts-expect-error
            timeFormat === TimeFormat['24-hour']
              ? (x: string) =>
                  d3.timeFormat(tbsFormatMapper24h[timeBucket])(
                    x as unknown as Date,
                  )
              : (x: string) =>
                  d3.timeFormat(tbsFormatMapper[timeBucket])(
                    x as unknown as Date,
                  ),
        },
        localtime: timeFormat === TimeFormat['24-hour'],
        type: 'timeseries',
      },
      y: {
        tick: {
          format: (d: number) => nFormatter(d, 1),
          values: optimalTicks,
        },
        show: true,
        inner: true,
      },
    },
    tooltip: {
      contents: (item: any, _: any, __: any, color: any) => {
        if (_isEmpty(item)) {
          return ''
        }

        return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-md z-50'>
          <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800 sticky top-0 bg-gray-50 dark:bg-slate-900'>${
            timeFormat === TimeFormat['24-hour']
              ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
              : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
          }</li>
          ${_map(
            item,
            (el: {
              id: string
              index: number
              name: string
              value: string
              x: Date
            }) => `
            <li class='flex justify-between items-center py-px leading-snug'>
              <div class='flex items-center min-w-0 mr-4'>
                <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
                <span class="truncate">${el.name}</span>
              </div>
              <span class='font-mono whitespace-nowrap'>${nFormatter(Number(el.value) || 0, 1)}</span>
            </li>
            `,
          ).join('')}`
      },
    },
    transition: {
      duration: 200,
    },
    resize: {
      auto: true,
      timer: true,
    },
    legend: {
      position: 'bottom',
      item: {
        tile: {
          type: 'circle',
          width: 10,
          r: 3,
        },
      },
    },
    point: {
      focus: {
        only: _size(chart.x) > 1,
      },
      pattern: ['circle'],
      r: 2,
    },
  }
}

// function to get the settings and data for the session inspector chart
const getSettingsSession = (
  chartInput:
    | {
        x: string[]
        pageviews?: number[]
        customEvents?: number[]
        errors?: number[]
      }
    | undefined,
  timeBucket: string,
  timeFormat: string,
  rotateXAxis: boolean,
  chartType: string,
  onZoom?: (domain: [Date, Date]) => void,
  enableZoom: boolean = true,
): ChartOptions => {
  const chartData = chartInput || { x: [] } // Default to an empty chart structure if undefined
  const xAxisSize = _size(chartData.x)

  const columns: any[] = [
    ['x', ..._map(chartData.x, (el) => dayjs(el).toDate())],
  ]
  const dataTypes: Record<string, any> = {}
  const dataColors: Record<string, string> = {}

  if (chartData.pageviews && !_isEmpty(chartData.pageviews)) {
    columns.push(['pageviews', ...chartData.pageviews])
    dataTypes.pageviews = chartType === chartTypes.line ? area() : bar()
    dataColors.pageviews = '#D97706'
  }

  if (chartData.customEvents && !_isEmpty(chartData.customEvents)) {
    columns.push(['customEvents', ...chartData.customEvents])
    dataTypes.customEvents = chartType === chartTypes.line ? area() : bar()
    dataColors.customEvents = '#0d9488'
  }

  if (chartData.errors && !_isEmpty(chartData.errors)) {
    columns.push(['errors', ...chartData.errors])
    dataTypes.errors = chartType === chartTypes.line ? area() : bar()
    dataColors.errors = '#dc2626'
  }

  // Calculate optimal Y axis ticks based on the data
  const allYValues: number[] = []
  if (chartData.pageviews && !_isEmpty(chartData.pageviews)) {
    allYValues.push(
      ...chartData.pageviews.filter((n) => n !== undefined && n !== null),
    )
  }
  if (chartData.customEvents && !_isEmpty(chartData.customEvents)) {
    allYValues.push(
      ...chartData.customEvents.filter((n) => n !== undefined && n !== null),
    )
  }
  if (chartData.errors && !_isEmpty(chartData.errors)) {
    allYValues.push(
      ...chartData.errors.filter((n) => n !== undefined && n !== null),
    )
  }

  const optimalTicks =
    allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined

  return {
    data: {
      x: 'x',
      columns,
      types: dataTypes,
      colors: dataColors,
      type: chartType === chartTypes.line ? area() : bar(),
    },
    zoom: enableZoom
      ? {
          enabled: zoom(),
          type: 'drag',
          onzoom: onZoom,
          resetButton: false, // We render a custom button that also resets pageflow
        }
      : undefined,
    grid: {
      y: {
        show: true,
      },
    },
    transition: {
      duration: 200,
    },
    resize: {
      auto: true,
      timer: true,
    },
    axis: {
      x: {
        clipPath: false,
        tick: {
          fit: true,
          rotate: rotateXAxis ? 45 : 0,

          format:
            // @ts-expect-error
            timeFormat === TimeFormat['24-hour']
              ? (x: string) =>
                  d3.timeFormat(tbsFormatMapper24h[timeBucket])(
                    x as unknown as Date,
                  )
              : (x: string) =>
                  d3.timeFormat(tbsFormatMapper[timeBucket])(
                    x as unknown as Date,
                  ),
        },
        localtime: timeFormat === TimeFormat['24-hour'],
        type: 'timeseries',
      },
      y: {
        tick: {
          format: (d: number) => nFormatter(d, 1),
          values: optimalTicks,
        },
        show: true,
        inner: true,
      },
    },
    tooltip: {
      contents: (item: any, _: any, __: any, color: any) => {
        if (!item || _isEmpty(item) || !item[0]) {
          return ''
        }
        return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-md z-50'>
          <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800 sticky top-0 bg-gray-50 dark:bg-slate-900'>${
            timeFormat === TimeFormat['24-hour']
              ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
              : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
          }</li>
          ${_map(
            item,
            (el: {
              id: string
              index: number
              name: string
              value: string
              x: Date
            }) => {
              return `
            <li class='flex justify-between items-center py-px leading-snug'>
              <div class='flex items-center min-w-0 mr-4'>
                <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
                <span class="truncate">${el.name}</span>
              </div>
              <span class='font-mono whitespace-nowrap'>${el.value}</span>
            </li>
            `
            },
          ).join('')}</ul>`
      },
    },
    point:
      chartType === chartTypes.bar
        ? {}
        : {
            focus: {
              only: xAxisSize > 1,
            },
            pattern: ['circle'],
            r: 2,
          },
    legend: {
      item: {
        tile: {
          type: 'circle',
          width: 10,
          r: 3,
        },
      },
      hide: [], // No series hidden by default for session chart
    },
    area: {
      linearGradient: true,
    },
    bar: {
      linearGradient: true,
      radius: {
        ratio: 0.15,
      },
    },
    bindto: '#sessionChart',
  }
}

const getSettingsError = (
  chart: any,
  timeBucket: string,
  timeFormat: string,
  rotateXAxis: boolean,
  chartType: string,
  annotations?: Annotation[],
  dataNames?: Record<string, string>,
  onDataPointClick?: ChartDataPointClick,
  dataPointClickLabel?: string,
): ChartOptions => {
  const xAxisSize = _size(chart.x)

  const annotationLines = getAnnotationGridLines(annotations)

  // Build columns with both occurrences and affectedUsers if available
  const columns: any[] = [
    ['x', ..._map(chart.x, (el: string) => dayjs(el).toDate())],
  ]

  if (chart.occurrences) {
    columns.push(['occurrences', ...chart.occurrences])
  }
  if (chart.affectedUsers) {
    columns.push(['affectedUsers', ...chart.affectedUsers])
  }

  const allYValues: number[] = []
  if (chart.occurrences) {
    allYValues.push(
      ...chart.occurrences.filter((n: any) => n !== undefined && n !== null),
    )
  }
  if (chart.affectedUsers) {
    allYValues.push(
      ...chart.affectedUsers.filter((n: any) => n !== undefined && n !== null),
    )
  }

  const optimalTicks =
    allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined

  let regionStart

  if (xAxisSize > 1) {
    regionStart = dayjs(chart.x[xAxisSize - 2]).toDate()
  } else {
    regionStart = dayjs(chart.x[xAxisSize - 1]).toDate()
  }

  const types: Record<string, any> = {
    occurrences: chartType === chartTypes.line ? area() : bar(),
  }
  if (chart.affectedUsers) {
    types.affectedUsers = chartType === chartTypes.line ? area() : bar()
  }

  const colors: Record<string, string> = {
    occurrences: '#f97316', // orange-500
    affectedUsers: '#dc2626', // red-600
  }

  return {
    data: {
      x: 'x',
      columns,
      onclick: onDataPointClick
        ? (d: any) => {
            if (d?.x) {
              onDataPointClick({
                x: d.x,
                index: d.index,
                xValue: chart.x?.[d.index],
              })
            }
          }
        : undefined,
      types,
      colors,
      names: dataNames,
      regions: {
        occurrences: [
          {
            // @ts-expect-error
            start: regionStart,
            style: {
              dasharray: '6 2',
            },
          },
        ],
      },
    },
    grid: {
      x: {
        lines: annotationLines,
      },
      y: {
        show: true,
      },
    },
    transition: {
      duration: 200,
    },
    resize: {
      auto: true,
      timer: true,
    },
    axis: {
      x: {
        clipPath: false,
        tick: {
          fit: true,
          rotate: rotateXAxis ? 45 : 0,
          format:
            // @ts-expect-error
            timeFormat === TimeFormat['24-hour']
              ? (x: string) =>
                  d3.timeFormat(tbsFormatMapper24h[timeBucket])(
                    x as unknown as Date,
                  )
              : (x: string) =>
                  d3.timeFormat(tbsFormatMapper[timeBucket])(
                    x as unknown as Date,
                  ),
        },
        localtime: timeFormat === TimeFormat['24-hour'],
        type: 'timeseries',
      },
      y: {
        tick: {
          format: (d: number) => nFormatter(d, 1),
          values: optimalTicks,
        },
        show: true,
        inner: true,
      },
    },
    tooltip: {
      contents: (item: any, _: any, __: any, color: any) => {
        return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-md z-50'>
          <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800 sticky top-0 bg-gray-50 dark:bg-slate-900'>${
            timeFormat === TimeFormat['24-hour']
              ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
              : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
          }</li>
          ${_map(
            item,
            (el: {
              id: string
              index: number
              name: string
              value: string
              x: Date
            }) => `
            <li class='flex justify-between items-center py-px leading-snug'>
              <div class='flex items-center min-w-0 mr-4'>
                <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
                <span class="truncate">${el.name}</span>
              </div>
              <span class='font-mono whitespace-nowrap'>${el.value}</span>
            </li>
            `,
          ).join(
            '',
          )}${onDataPointClick ? `<li class='pt-1 mt-1 border-t border-gray-200 dark:border-slate-700/80 text-[10px] text-gray-400 dark:text-slate-500'>${dataPointClickLabel}</li>` : ''}</ul>`
      },
    },
    point:
      chartType === chartTypes.bar
        ? {}
        : {
            focus: {
              only: xAxisSize > 1,
              expand: onDataPointClick ? { enabled: true, r: 4 } : undefined,
            },
            pattern: ['circle'],
            r: 2,
            sensitivity: onDataPointClick ? 50 : undefined,
          },
    legend: {
      item: {
        tile: {
          type: 'circle',
          width: 10,
          r: 3,
        },
      },
    },
    area: {
      linearGradient: true,
    },
    bar: {
      linearGradient: true,
      radius: {
        ratio: 0.15,
      },
    },
    onrendered: onDataPointClick
      ? function (this: any) {
          attachDataPointClickHandlers(this, columns, onDataPointClick, chart.x)
        }
      : undefined,
  }
}

const getSettingsFunnels = (
  funnel: AnalyticsFunnel[],
  totalPageviews: number,
  t: typeof i18next.t,
  language: string,
  onBarClick?: (stepIndex: number) => void,
): ChartOptions => {
  const values = _map(funnel, (step) => {
    if (_startsWith(step.value, '/')) {
      return t('project.visitPage', { page: step.value })
    }

    return step.value
  })
  const events = _map(funnel, (step) => step.events)
  const dropoff = _map(funnel, (step) => step.dropoff)

  // Calculate optimal Y axis ticks based on the data
  const allYValues: number[] = []
  if (events && !_isEmpty(events)) {
    allYValues.push(...events.filter((n) => n !== undefined && n !== null))
  }
  if (dropoff && !_isEmpty(dropoff)) {
    allYValues.push(...dropoff.filter((n) => n !== undefined && n !== null))
  }
  const optimalTicks =
    allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined

  return {
    data: {
      x: 'x',
      columns: [
        ['x', ...values],
        ['dropoff', ...dropoff],
        ['events', ...events],
      ],
      types: {
        events: bar(),
        dropoff: bar(),
      },
      colors: {
        events: '#1d4ed8', // blue-700
        dropoff: 'rgba(71, 85, 105, 0.2)', // slate-600 + opacity
      },
      groups: [['events', 'dropoff']],
      // @ts-expect-error
      order: (a: any, b: any) => {
        return a.id < b.id
      },
      onover: (_d: any, el: SVGElement) => {
        el?.style?.setProperty('fill-opacity', '0.75', 'important')
      },
      onout: (_d: any, el: SVGElement) => {
        el?.style?.removeProperty('fill-opacity')
      },
      onclick: onBarClick
        ? (d: any) => {
            if (d?.index !== undefined) {
              onBarClick(d.index)
            }
          }
        : undefined,
    },
    bar: {
      radius: {
        ratio: 0.05,
      },
    },
    transition: {
      duration: 200,
    },
    resize: {
      auto: true,
      timer: true,
    },
    grid: {
      y: {
        show: true,
      },
    },
    axis: {
      x: {
        type: 'category',
      },
      y: {
        tick: {
          format: (d: number) => nFormatter(d, 1),
          values: optimalTicks,
        },
        show: true,
        inner: true,
      },
    },
    tooltip: {
      contents: (items: any) => {
        const { index = 0 } = items[0] || {}
        const step = funnel[index]
        const stepTitle = escapeHtml(values[index] ?? '')
        const prevStep = index > 0 ? funnel[index - 1] : null
        const prevStepTitle = escapeHtml(values[index - 1] ?? '')

        // the v2 stats API ships per-step breakdowns; topSources/topCountries
        // are the legacy v1 fields kept as a fallback
        const topSourcesEntries = Object.entries(
          step.breakdowns?.sources || step.topSources || {},
        )
        const topCountriesEntries = Object.entries(
          step.breakdowns?.countries || step.topCountries || {},
        )

        const primary = 'text-gray-900 dark:text-gray-50'
        const secondary = 'text-gray-700 dark:text-gray-200'
        const success = 'text-green-600 dark:text-green-400'
        const error = 'text-red-600 dark:text-red-400'

        let headerHtml = ''

        if (index === 0) {
          const neverEntered = totalPageviews - step.events
          headerHtml = `
            <div class='flex items-center justify-between gap-6'>
              <div class='flex items-center gap-1.5 min-w-0'>
                <span class='${secondary}'>↳</span>
                <span class='font-semibold truncate ${primary}'>${stepTitle}</span>
              </div>
              <span class='font-mono font-semibold tabular-nums shrink-0 ${primary}'>${nFormatter(step.events, 1)}</span>
            </div>
            ${
              neverEntered > 0
                ? `
              <div class='flex items-center justify-between gap-6 mt-1'>
                <span class='${secondary}'>${t('project.neverEnteredTheFunnel')}</span>
                <span class='font-mono tabular-nums ${error}'>-${nFormatter(neverEntered, 1)}</span>
              </div>
            `
                : ''
            }
          `
        } else {
          headerHtml = `
            <div class='flex items-center justify-between gap-6'>
              <div class='flex items-center gap-1.5 min-w-0'>
                <span class='${secondary}'>↳</span>
                <span class='font-medium truncate ${secondary}'>${prevStepTitle}</span>
              </div>
              <span class='font-mono font-medium tabular-nums shrink-0 ${secondary}'>${nFormatter(prevStep!.events, 1)}</span>
            </div>
            <div class='flex items-center justify-between gap-6 mt-1'>
              <span class='${secondary}'>${t('project.dropoff')}</span>
              <span class='font-mono tabular-nums ${error}'>-${nFormatter(step.dropoff, 1)}</span>
            </div>
            <div class='flex items-center justify-between gap-6 mt-1'>
              <div class='flex items-center gap-1.5 min-w-0 pl-4'>
                <span class='${secondary}'>↳</span>
                <span class='font-semibold truncate ${primary}'>${stepTitle}</span>
              </div>
              <span class='font-mono font-semibold tabular-nums shrink-0 ${primary}'>${nFormatter(step.events, 1)}</span>
            </div>
          `
        }

        const conversionHtml = `
          <div class='border-t border-gray-200 dark:border-slate-700/80 mt-2 pt-2'>
            <div class='flex items-center justify-between gap-6'>
              <span class='font-semibold ${primary}'>${t('project.conversion')}</span>
              <span class='font-mono tabular-nums font-semibold ${success}'>${step.eventsPercStep}%</span>
            </div>
            <div class='flex items-center justify-between gap-6 mt-0.5'>
              <span class='${secondary}'>${t('project.conversionFromStart')}</span>
              <span class='font-mono tabular-nums ${success}'>${step.eventsPerc}%</span>
            </div>
          </div>
        `

        let detailsHtml = ''
        if (topSourcesEntries.length > 0 || topCountriesEntries.length > 0) {
          const sourcesHtml =
            topSourcesEntries.length > 0
              ? `
            <div class='flex-1 min-w-0'>
              <p class='text-[10px] font-semibold uppercase tracking-wider ${secondary} mb-1.5'>
                ${t('project.topSources')}
              </p>
              ${topSourcesEntries
                .map(([domain, count]) => {
                  const perc =
                    step.events > 0
                      ? Math.round((count / step.events) * 100)
                      : 0
                  const isDirect = domain === 'Direct / None'
                  const safeDomain = escapeHtml(domain)
                  const iconHtml = isDirect
                    ? `
                    <img src='/assets/icons/chain.svg' class='size-3.5 shrink-0 dark:hidden' alt='' />
                    <img src='/assets/icons/chain-light.svg' class='size-3.5 shrink-0 hidden dark:inline' alt='' />
                  `
                    : `<img src='/api/favicon?domain=${encodeURIComponent(domain)}' class='size-3.5 rounded-sm shrink-0' loading='lazy' alt='' />`
                  return `
                  <div class='flex items-center justify-between gap-2 mt-1'>
                    <div class='flex items-center gap-1.5 min-w-0'>
                      ${iconHtml}
                      <span class='truncate ${primary}'>${safeDomain}</span>
                    </div>
                    <span class='font-mono tabular-nums shrink-0 ${primary}'>${perc}%</span>
                  </div>
                `
                })
                .join('')}
            </div>
          `
              : ''

          const countriesHtml =
            topCountriesEntries.length > 0
              ? `
            <div class='flex-1 min-w-0'>
              <p class='text-[10px] font-semibold uppercase tracking-wider ${secondary} mb-1.5'>
                ${t('project.topCountries')}
              </p>
              ${topCountriesEntries
                .map(([cc, count]) => {
                  const perc =
                    step.events > 0
                      ? Math.round((count / step.events) * 100)
                      : 0
                  const safeName = escapeHtml(
                    countries.getName(cc, language) || cc,
                  )
                  const safeCC = encodeURIComponent(cc.toLowerCase())
                  return `
                  <div class='flex items-center justify-between gap-2 mt-1'>
                    <div class='flex items-center gap-1.5 min-w-0'>
                      <img src='/assets/flags/${safeCC}.svg' width='16' height='12' class='shrink-0 rounded-[2px]' loading='lazy' alt='' />
                      <span class='truncate ${primary}'>${safeName}</span>
                    </div>
                    <span class='font-mono tabular-nums shrink-0 ${primary}'>${perc}%</span>
                  </div>
                `
                })
                .join('')}
            </div>
          `
              : ''

          detailsHtml = `
            <div class='border-t border-gray-200 dark:border-slate-700/80 mt-2 pt-2 flex gap-5'>
              ${sourcesHtml}
              ${countriesHtml}
            </div>
          `
        }

        return `
          <div class='bg-gray-50 dark:bg-slate-900 rounded-lg ring-1 ring-black/10 dark:ring-white/10 px-3 py-2.5 text-xs md:text-sm max-w-sm md:max-w-md shadow-lg z-50'>
            ${headerHtml}
            ${conversionHtml}
            ${detailsHtml}
          </div>
        `
      },
    },
  }
}

const perfomanceChartCompare = [
  'dnsCompare',
  'tlsCompare',
  'connCompare',
  'responseCompare',
  'renderCompare',
  'dom_loadCompare',
  'ttfbCompare',
  'frontendCompare',
  'networkCompare',
  'backendCompare',
  'p50Compare',
  'p75Compare',
  'p95Compare',
]

const getSettingsPerf = (
  chart: Record<string, string[]>,
  timeBucket: string,
  activeChartMetrics: string,
  rotateXAxis: boolean,
  chartType: string,
  timeFormat: string,
  compareChart?: Record<string, string[]>,
  onZoom?: (domain: [Date, Date] | null) => void,
  enableZoom?: boolean,
  annotations?: Annotation[],
  onDataPointClick?: ChartDataPointClick,
  dataPointClickLabel?: string,
): ChartOptions => {
  const xAxisSize = _size(chart.x)
  const columns = getColumnsPerf(chart, activeChartMetrics, compareChart)

  const annotationLines = getAnnotationGridLines(annotations)

  return {
    data: {
      x: 'x',
      xFormat: tbsFormatMapper[timeBucket],
      columns,
      onclick: onDataPointClick
        ? (d: any) => {
            if (d?.x) {
              onDataPointClick({
                x: d.x,
                index: d.index,
                xValue: chart.x?.[d.index],
              })
            }
          }
        : undefined,
      types: {
        dns: chartType === chartTypes.line ? areaSpline() : bar(),
        tls: chartType === chartTypes.line ? areaSpline() : bar(),
        conn: chartType === chartTypes.line ? areaSpline() : bar(),
        response: chartType === chartTypes.line ? areaSpline() : bar(),
        render: chartType === chartTypes.line ? areaSpline() : bar(),
        dom_load: chartType === chartTypes.line ? areaSpline() : bar(),
        ttfb: chartType === chartTypes.line ? areaSpline() : bar(),
        frontend: chartType === chartTypes.line ? areaSpline() : bar(),
        network: chartType === chartTypes.line ? areaSpline() : bar(),
        backend: chartType === chartTypes.line ? areaSpline() : bar(),
        p50: chartType === chartTypes.line ? areaSpline() : bar(),
        p75: chartType === chartTypes.line ? areaSpline() : bar(),
        p95: chartType === chartTypes.line ? areaSpline() : bar(),
        dnsCompare: chartType === chartTypes.line ? spline() : bar(),
        tlsCompare: chartType === chartTypes.line ? spline() : bar(),
        connCompare: chartType === chartTypes.line ? spline() : bar(),
        responseCompare: chartType === chartTypes.line ? spline() : bar(),
        renderCompare: chartType === chartTypes.line ? spline() : bar(),
        dom_loadCompare: chartType === chartTypes.line ? spline() : bar(),
        ttfbCompare: chartType === chartTypes.line ? spline() : bar(),
        frontendCompare: chartType === chartTypes.line ? spline() : bar(),
        networkCompare: chartType === chartTypes.line ? spline() : bar(),
        backendCompare: chartType === chartTypes.line ? spline() : bar(),
        p50Compare: chartType === chartTypes.line ? spline() : bar(),
        p75Compare: chartType === chartTypes.line ? spline() : bar(),
        p95Compare: chartType === chartTypes.line ? spline() : bar(),
      },
      colors: {
        dns: '#EC4319',
        tls: '#F27059',
        conn: '#F7A265',
        response: '#F5D376',
        render: '#709775',
        dom_load: '#A5E6AB',
        ttfb: '#00A8E8',
        frontend: '#709775',
        network: '#F7A265',
        backend: '#00A8E8',
        p50: '#38bdf8',
        p75: '#facc15',
        p95: '#f87171',
        p50Compare: 'rgba(56, 189, 248, 0.4)',
        p75Compare: 'rgba(250, 204, 21, 0.4)',
        p95Compare: 'rgba(248, 113, 113, 0.4)',
        dnsCompare: 'rgba(236, 67, 25, 0.4)',
        tlsCompare: 'rgba(242, 112, 89, 0.4)',
        connCompare: 'rgba(247, 162, 101, 0.4)',
        responseCompare: 'rgba(245, 211, 118, 0.4)',
        renderCompare: 'rgba(112, 151, 117, 0.4)',
        dom_loadCompare: 'rgba(165, 230, 171, 0.4)',
        ttfbCompare: 'rgba(0, 168, 232, 0.4)',
        frontendCompare: 'rgba(112, 151, 117, 0.4)',
        networkCompare: 'rgba(247, 162, 101, 0.4)',
        backendCompare: 'rgba(0, 168, 232, 0.4)',
      },
      groups: [
        [
          'dns',
          'tls',
          'conn',
          'response',
          'render',
          'dom_load',
          'ttfb',
          'frontend',
          'network',
          'backend',
        ],
        [
          'dnsCompare',
          'tlsCompare',
          'connCompare',
          'responseCompare',
          'renderCompare',
          'dom_loadCompare',
          'ttfbCompare',
          'frontendCompare',
          'networkCompare',
          'backendCompare',
        ],
      ],
    },
    grid: {
      x: {
        lines: annotationLines,
      },
      y: {
        show: true,
      },
    },
    axis: {
      x: {
        clipPath: false,
        tick: {
          fit: true,
          rotate: rotateXAxis ? 45 : 0,

          format:
            // @ts-expect-error
            timeFormat === TimeFormat['24-hour']
              ? (x: string) =>
                  d3.timeFormat(tbsFormatMapper24h[timeBucket])(
                    x as unknown as Date,
                  )
              : (x: string) =>
                  d3.timeFormat(tbsFormatMapper[timeBucket])(
                    x as unknown as Date,
                  ),
        },
        localtime: timeFormat === TimeFormat['24-hour'],
        type: 'timeseries',
      },
      y: {
        tick: {
          // @ts-expect-error
          format: (d: string) => getStringFromTime(getTimeFromSeconds(d), true),
        },
        show: true,
        inner: true,
      },
    },
    transition: {
      duration: 0,
    },
    resize: {
      auto: true,
      timer: true,
    },
    tooltip: {
      contents: (item: any, _: any, __: any, color: any) => {
        if (_isEmpty(compareChart)) {
          return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-md z-50'>
        <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800 sticky top-0 bg-gray-50 dark:bg-slate-900'>${
          timeFormat === TimeFormat['24-hour']
            ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
            : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
        }</li>
        ${_map(
          item,
          (el: {
            id: string
            index: number
            name: string
            value: string
            x: Date
          }) => {
            return `
          <li class='flex justify-between items-center py-px leading-snug'>
            <div class='flex items-center min-w-0 mr-4'>
              <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
              <span class="truncate">${el.name}</span>
            </div>
            <span class='font-mono whitespace-nowrap'>${getStringFromTime(getTimeFromSeconds(el.value), true)}</span>
          </li>
          `
          },
        ).join(
          '',
        )}${onDataPointClick ? `<li class='pt-1 mt-1 border-t border-gray-200 dark:border-slate-700/80 text-[10px] text-gray-400 dark:text-slate-500'>${dataPointClickLabel}</li>` : ''}</ul>`
        }

        // Get dates from first item
        const firstItem = item[0]
        const firstIndex = firstItem?.index ?? 0
        const currentX = firstItem?.x as Date | string | undefined
        const currentDate = currentX
          ? currentX instanceof Date
            ? currentX
            : new Date(currentX)
          : null
        const compareDate = compareChart?.x?.[firstIndex]

        const xDataValue = currentDate
          ? timeFormat === TimeFormat['24-hour']
            ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(currentDate)
            : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(currentDate)
          : ''
        const xDataValueCompare = compareDate
          ? timeFormat === TimeFormat['24-hour']
            ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
                dayjs(compareDate).toDate(),
              )
            : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
                dayjs(compareDate).toDate(),
              )
          : ''

        // Filter out compare series items
        const filteredItems = item.filter(
          (el: { id: string }) => !_includes(perfomanceChartCompare, el.id),
        )

        // Build current period section
        const currentSection = `
          <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800'>${xDataValue}</li>
          ${_map(
            filteredItems,
            (el: { id: string; name: string; value: string }) => {
              return `
              <li class='flex justify-between items-center py-px leading-snug'>
                <div class='flex items-center min-w-0 mr-4'>
                  <div class='w-2.5 h-2.5 rounded-xs mr-1.5 shrink-0' style='background-color:${color(el.id)}'></div>
                  <span class="truncate">${el.name}</span>
                </div>
                <span class='font-mono whitespace-nowrap'>${getStringFromTime(getTimeFromSeconds(el.value), true)}</span>
              </li>`
            },
          ).join('')}`

        // Build compare period section
        const compareSection = xDataValueCompare
          ? `
          <li class='font-semibold pb-1 mb-1 mt-3 pt-2 border-t border-b border-gray-200 dark:border-slate-800'>${xDataValueCompare}</li>
          ${_map(
            filteredItems,
            (el: { id: string; index: number; name: string }) => {
              const compareValue = getValueForTooltipPerfomance(
                compareChart,
                el.id,
                el.index,
              )
              if (compareValue === undefined || compareValue === null) return ''
              return `
              <li class='flex justify-between items-center py-px leading-snug'>
                <div class='flex items-center min-w-0 mr-4'>
                  <div class='w-2.5 h-2.5 rounded-xs mr-1.5 shrink-0 opacity-60' style='background-color:${color(el.id)}'></div>
                  <span class="truncate opacity-75">${el.name}</span>
                </div>
                <span class='font-mono whitespace-nowrap opacity-75'>${getStringFromTime(getTimeFromSeconds(compareValue), true)}</span>
              </li>`
            },
          ).join('')}`
          : ''

        return `
      <ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-md z-50'>
        ${currentSection}
        ${compareSection}
        ${onDataPointClick ? `<li class='pt-1 mt-1 border-t border-gray-200 dark:border-slate-700/80 text-[10px] text-gray-400 dark:text-slate-500'>${dataPointClickLabel}</li>` : ''}
      </ul>`
      },
    },
    point:
      chartType === chartTypes.bar
        ? {}
        : {
            focus: {
              only: xAxisSize > 1,
              expand: onDataPointClick ? { enabled: true, r: 4 } : undefined,
            },
            pattern: ['circle'],
            r: 2,
            sensitivity: onDataPointClick ? 50 : undefined,
          },
    legend: {
      item: {
        tile: {
          type: 'circle',
          width: 10,
          r: 3,
        },
      },
      hide: perfomanceChartCompare,
    },
    area: {
      linearGradient: true,
    },
    bar: {
      linearGradient: true,
      radius: {
        ratio: 0.15,
      },
    },
    onrendered: onDataPointClick
      ? function (this: any) {
          attachDataPointClickHandlers(this, columns, onDataPointClick, chart.x)
        }
      : undefined,
    zoom:
      onZoom && enableZoom !== false
        ? {
            enabled: zoom(),
            type: 'drag',
            onzoom: onZoom,
            resetButton: false,
          }
        : undefined,
    bindto: '#dataChart',
  }
}

const typeNameMapping = (t: typeof i18next.t) => ({
  country: t('project.mapping.cc'),
  host: t('project.mapping.host'),
  region: t('project.mapping.rg'),
  city: t('project.mapping.ct'),
  page: t('project.mapping.pg'),
  title: t('project.mapping.title'),
  outbound_link: t('project.outboundLinks'),
  query: t('project.seo.query'),
  entry_page: t('project.entryPages'),
  exit_page: t('project.exitPages'),
  locale: t('project.mapping.lc'),
  referrer: t('project.mapping.ref'),
  referrer_name: t('project.mapping.ref'),
  device: t('project.mapping.dv'),
  browser: t('project.mapping.br'),
  browser_version: t('project.mapping.brv'),
  os: t('project.mapping.os'),
  os_version: t('project.mapping.osv'),
  utm_source: t('project.mapping.so'),
  utm_medium: t('project.mapping.me'),
  utm_campaign: t('project.mapping.ca'),
  utm_term: t('project.mapping.te'),
  utm_content: t('project.mapping.co'),
  isp: t('project.mapping.isp'),
  organization: t('project.mapping.og'),
  user_type: t('project.mapping.ut'),
  connection_type: t('project.mapping.ctp'),
  event: t('project.event'),
  event_metadata: t('project.metamapping.ev.key'),
  page_property: t('project.metamapping.tag.key'),
  error_name: t('project.mapping.error_name'),
  error_message: t('project.mapping.error_message'),
  error_filename: t('project.mapping.error_filename'),
  searchEngine: t('project.mapping.searchEngine'),
  aiReferral: t('project.mapping.aiReferral'),
  captcha_event: t('project.event'),
  captcha_difficulty: t('project.mapping.captcha_difficulty'),
  captcha_reason: t('project.mapping.captcha_reason'),
  solve_time: t('project.mapping.solve_time'),
  // Combined panel types
  location: t('project.location'),
  devices: t('project.devices'),
  network: t('project.network'),
  map: t('project.map'),
})

const iconClassName = 'w-5 h-5'
const panelIconMapping = {
  country: <MapPinIcon className={iconClassName} />,
  page: <FileTextIcon className={iconClassName} />,
  locale: <TranslateIcon className={iconClassName} />,
  referrer: <ArrowCircleRightIcon className={iconClassName} />,
  device: <DevicesIcon className={iconClassName} />,
  browser: <CompassIcon className={iconClassName} />,
  os: <MonitorPlayIcon className={iconClassName} />,
  utm_source: <ShareIcon className={iconClassName} />,
  isp: <GlobeIcon className={iconClassName} />,
}

export const deviceIconMapping = {
  desktop: <MonitorIcon className='size-5' />,
  mobile: <DeviceMobileIcon className='size-5' />,
  tablet: <DeviceTabletIcon className='size-5' />,
  smarttv: <TelevisionIcon className='size-5' />,
  console: <GameControllerIcon className='size-5' />,
  wearable: <WatchIcon className='size-5' />,
  embedded: <CpuIcon className='size-5' />,
  xr: <VirtualRealityIcon className='size-5' />,
}

// This function return date using the same format as the backend
const getFormatDate = (date: Date) => {
  const yyyy = date.getFullYear()
  let mm: string | number = date.getMonth() + 1
  let dd: string | number = date.getDate()
  if (dd < 10) dd = `0${dd}`
  if (mm < 10) mm = `0${mm}`
  return `${yyyy}-${mm}-${dd}`
}

const SHORTCUTS_TABS_MAP = {
  T: PROJECT_TABS.traffic,
  P: PROJECT_TABS.performance,
  U: PROJECT_TABS.profiles,
  F: PROJECT_TABS.funnels,
  S: PROJECT_TABS.sessions,
  R: PROJECT_TABS.errors,
}

const _SHORTCUTS_TABS_LISTENERS =
  'shift+t, shift+p, shift+u, shift+s, shift+f, shift+e, shift+r'
const SHORTCUTS_TABS_LISTENERS = _SHORTCUTS_TABS_LISTENERS

const _SHORTCUTS_GENERAL_LISTENERS = 'alt+s,alt+ß, alt+b,alt+∫, alt+l,alt+¬, r'
const SHORTCUTS_GENERAL_LISTENERS = isSelfhosted
  ? _SHORTCUTS_GENERAL_LISTENERS
  : _SHORTCUTS_GENERAL_LISTENERS + ',alt+f,alt+ƒ'

const SHORTCUTS_TIMEBUCKETS_LISTENERS = 'h, t, y, d, w, m, q, l, z, a, u, c'

export const getDeviceRowMapper = (
  activeTab: string,
  theme: string,
  t: typeof i18next.t,
) => {
  if (activeTab === 'br') {
    // eslint-disable-next-line
    return (entry: any) => {
      const { name: entryName, version } = entry
      const logoKey = entryName
      // @ts-expect-error
      const logoUrl = BROWSER_LOGO_MAP[logoKey]
      const displayName = version ? `${entryName} ${version}` : entryName

      if (entryName === null) {
        return (
          <>
            <GlobeIcon className='h-5 w-5' />
            &nbsp;
            <span className='italic'>{t('common.unknown')}</span>
          </>
        )
      }

      if (!logoUrl) {
        return (
          <>
            <GlobeIcon className='h-5 w-5' />
            &nbsp;
            {displayName}
          </>
        )
      }

      return (
        <>
          <img src={logoUrl} className='h-5 w-5' alt='' />
          &nbsp;
          {displayName}
        </>
      )
    }
  }

  if (activeTab === 'os') {
    // eslint-disable-next-line
    return (entry: any) => {
      const { name: entryName, version } = entry
      const logoKey = entryName
      // @ts-expect-error
      const logoUrlLight = OS_LOGO_MAP[logoKey]
      // @ts-expect-error
      const logoUrlDark = OS_LOGO_MAP_DARK[logoKey]
      const displayName = version ? `${entryName} ${version}` : entryName

      let logoUrl = theme === 'dark' ? logoUrlDark : logoUrlLight
      logoUrl ||= logoUrlLight

      if (entryName === null) {
        return (
          <>
            <GlobeIcon className='h-5 w-5' />
            &nbsp;
            <span className='italic'>{t('common.unknown')}</span>
          </>
        )
      }

      if (!logoUrl) {
        return (
          <>
            <GlobeIcon className='h-5 w-5' />
            &nbsp;
            {displayName}
          </>
        )
      }

      return (
        <>
          <img src={logoUrl} className='h-5 w-5 dark:fill-gray-50' alt='' />
          &nbsp;
          {displayName}
        </>
      )
    }
  }

  if (activeTab === 'dv') {
    // eslint-disable-next-line
    return (entry: { name: keyof typeof deviceIconMapping }) => {
      const { name: entryName } = entry
      const icon = deviceIconMapping[entryName]

      if (entryName === null) {
        return (
          <>
            <QuestionMarkIcon className='h-5 w-5' />
            &nbsp;
            <span className='italic'>{t('common.unknown')}</span>
          </>
        )
      }

      if (!icon) {
        return entryName
      }

      return (
        <>
          {icon}
          &nbsp;
          {entryName === 'xr' ? t('project.deviceLabels.xr') : entryName}
        </>
      )
    }
  }

  return undefined
}

const sanitiseNetworkKey = (value: string) =>
  value.toLowerCase().replace(/[\s/]+/g, '_')

export const getUsageTypeLabel = (value: string, t: typeof i18next.t): string =>
  t(`project.usageTypeMapping.${sanitiseNetworkKey(value)}`, {
    defaultValue: value,
  }) as string

export const getConnectionTypeLabel = (
  value: string,
  t: typeof i18next.t,
): string =>
  t(`project.connectionTypeMapping.${sanitiseNetworkKey(value)}`, {
    defaultValue: value,
  }) as string

const getSettingsCaptcha = (
  chart: {
    x: string[]
    results?: number[]
    generated?: number[]
    passed?: number[]
    failed?: number[]
    validationFailed?: number[]
    replayed?: number[]
  },
  timeBucket: string,
  timeFormat: string,
  rotateXAxis: boolean,
  chartType: string,
): ChartOptions => {
  const xAxisSize = _size(chart.x)
  const series = [
    'generated',
    'passed',
    'failed',
    'validationFailed',
    'replayed',
  ] as const
  const activeSeries = series.filter((key) => chart[key]?.length)
  const fallbackSeries: Array<
    | 'generated'
    | 'passed'
    | 'failed'
    | 'validationFailed'
    | 'replayed'
    | 'results'
  > = activeSeries.length ? [...activeSeries] : ['results']

  const columns: any[] = [
    ['x', ..._map(chart.x, (el) => dayjs(el).toDate())],
    ...fallbackSeries.map((key) => [key, ...(chart[key] || [])]),
  ]

  const allYValues: number[] = []
  fallbackSeries.forEach((key) => {
    allYValues.push(
      ...(chart[key] || []).filter((n: any) => n !== undefined && n !== null),
    )
  })

  const optimalTicks =
    allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined

  let regionStart

  if (xAxisSize > 1) {
    regionStart = dayjs(chart.x[xAxisSize - 2]).toDate()
  } else {
    regionStart = dayjs(chart.x[xAxisSize - 1]).toDate()
  }
  const regions = Object.fromEntries(
    fallbackSeries.map((key) => [
      key,
      [
        {
          start: regionStart,
          style: {
            dasharray: '6 2',
          },
        },
      ],
    ]),
  ) as any

  return {
    data: {
      x: 'x',
      columns,
      types: Object.fromEntries(
        fallbackSeries.map((key) => [
          key,
          chartType === chartTypes.line ? area() : bar(),
        ]),
      ),
      colors: {
        generated: '#2563eb',
        passed: '#16a34a',
        failed: '#dc2626',
        validationFailed: '#f97316',
        replayed: '#7c3aed',
        results: '#16a34a',
      },
      regions,
    },
    grid: {
      y: {
        show: true,
      },
    },
    transition: {
      duration: 200,
    },
    resize: {
      auto: true,
      timer: true,
    },
    axis: {
      x: {
        clipPath: false,
        tick: {
          fit: true,
          rotate: rotateXAxis ? 45 : 0,
          format:
            // @ts-expect-error
            timeFormat === TimeFormat['24-hour']
              ? (x: string) =>
                  d3.timeFormat(tbsFormatMapper24h[timeBucket])(
                    x as unknown as Date,
                  )
              : (x: string) =>
                  d3.timeFormat(tbsFormatMapper[timeBucket])(
                    x as unknown as Date,
                  ),
        },
        localtime: timeFormat === TimeFormat['24-hour'],
        type: 'timeseries',
      },
      y: {
        tick: {
          format: (d: number) => nFormatter(d, 1),
          values: optimalTicks,
        },
        show: true,
        inner: true,
      },
    },
    tooltip: {
      contents: (item: any, _: any, __: any, color: any) => {
        return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-md z-50'>
          <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800 sticky top-0 bg-gray-50 dark:bg-slate-900'>${
            timeFormat === TimeFormat['24-hour']
              ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
              : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
          }</li>
          ${_map(
            item,
            (el: {
              id: string
              index: number
              name: string
              value: string
              x: Date
            }) => `
            <li class='flex justify-between items-center py-px leading-snug'>
              <div class='flex items-center min-w-0 mr-4'>
                <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
                <span class="truncate">${el.name}</span>
              </div>
              <span class='font-mono whitespace-nowrap'>${el.value}</span>
            </li>
            `,
          ).join('')}`
      },
    },
    point:
      chartType === chartTypes.bar
        ? {}
        : {
            focus: {
              only: xAxisSize > 1,
            },
            pattern: ['circle'],
            r: 2,
          },
    legend: {
      item: {
        tile: {
          type: 'circle',
          width: 10,
          r: 3,
        },
      },
    },
    area: {
      linearGradient: true,
    },
    bar: {
      linearGradient: true,
      radius: {
        ratio: 0.15,
      },
    },
  }
}

export {
  getFormatDate,
  panelIconMapping,
  typeNameMapping,
  noRegionPeriods,
  getSettings,
  getSettingsCustomEventsStacked,
  onCSVExportClick,
  CHART_METRICS_MAPPING,
  CHART_METRICS_MAPPING_PERF,
  getSettingsPerf,
  getSettingsFunnels,
  getSettingsSession,
  SHORTCUTS_TABS_MAP,
  SHORTCUTS_TABS_LISTENERS,
  SHORTCUTS_GENERAL_LISTENERS,
  SHORTCUTS_TIMEBUCKETS_LISTENERS,
  CHART_MEASURES_MAPPING_PERF,
  getSettingsError,
  getSettingsCaptcha,
}