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!

71.0 KB
Raw Blame
import _split from 'lodash/split'
import { useTranslation } from 'react-i18next'
import {
  data,
  redirect,
  type ActionFunctionArgs,
  type LinksFunction,
  type LoaderFunctionArgs,
  type MetaFunction,
  type ShouldRevalidateFunctionArgs,
} from 'react-router'

import {
  serverFetch,
  authMeServer,
  getSessionReplaysServer,
  getProjectFeatureFlagsServer,
  getProjectGoalsServer,
  type SessionReplaysResponse,
  type FeatureFlagsResponse,
  type GoalsResponse,
} from '~/api/api.server'
import { parseFiltersFromUrl } from '~/utils/analyticsUrl'
import { useRequiredParams } from '~/hooks/useRequiredParams'
import {
  DEFAULT_TIMEZONE,
  PROJECT_TABS,
  getProjectOgImageUrl,
  getValidTimeBucket,
  isSelfhosted,
  type Period,
} from '~/lib/constants'
import { Project } from '~/lib/models/Project'
import ViewProject from '~/pages/Project/View'
import { CurrentProjectProvider } from '~/providers/CurrentProjectProvider'
import ProjectViewStyle from '~/styles/ProjectViewStyle.css?url'
import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
import {
  redirectIfNotAuthenticated,
  createHeadersWithCookies,
  getProjectPasswordCookie,
  createProjectPasswordCookie,
  hasAuthTokens,
} from '~/utils/session.server'

const GOAL_CONDITION_RELATIONS = new Set(['AND', 'OR'])
const GOAL_CONDITION_COMMON_FIELDS = [
  'host',
  'country',
  'device',
  'browser',
  'os',
  'referrer',
  'utm_source',
  'utm_medium',
  'utm_campaign',
  'utm_term',
  'utm_content',
  'ref',
  'so',
  'me',
  'ca',
  'te',
  'co',
  'cc',
  'dv',
  'br',
]
const GOAL_CONDITION_EVENT_TYPES: Record<string, Set<string>> = {
  any: new Set([
    ...GOAL_CONDITION_COMMON_FIELDS,
    'page',
    'pg',
    'event',
    'event_name',
  ]),
  pageview: new Set([
    ...GOAL_CONDITION_COMMON_FIELDS,
    'page',
    'pg',
    'metadata',
  ]),
  custom_event: new Set([
    ...GOAL_CONDITION_COMMON_FIELDS,
    'event',
    'event_name',
    'metadata',
  ]),
}
const GOAL_CONDITION_OPERATORS = new Set([
  'equals',
  'not_equals',
  'contains',
  'not_contains',
  'exists',
  'not_exists',
])
const GOAL_CONDITION_VALUE_OPERATORS = new Set([
  'equals',
  'not_equals',
  'contains',
  'not_contains',
])

type GoalMetadataFilter = {
  key: string
  value: string
}

type JsonFormFieldResult =
  | { ok: true; value: unknown }
  | { ok: false; error: string }

type GoalJsonFieldsResult =
  | {
      ok: true
      metadataFilters: GoalMetadataFilter[]
      conditions: unknown
    }
  | { ok: false; error: string }

function computeDateRangeForPeriod(
  period: string,
  from?: string,
  to?: string,
): { from: string; to: string } | null {
  if (from && to) {
    return { from: `${from} 00:00:00`, to: `${to} 23:59:59` }
  }

  const now = new Date()
  const pad = (n: number) => String(n).padStart(2, '0')
  const fmt = (d: Date) =>
    `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}`

  const subtract = (ms: number) => new Date(now.getTime() - ms)
  const MS_HOUR = 3_600_000
  const MS_DAY = 86_400_000

  const periodMap: Record<string, () => { from: string; to: string }> = {
    '1h': () => ({ from: fmt(subtract(MS_HOUR)), to: fmt(now) }),
    today: () => {
      const start = new Date(now)
      start.setUTCHours(0, 0, 0, 0)
      return { from: fmt(start), to: fmt(now) }
    },
    yesterday: () => {
      const dayStart = new Date(now.getTime() - MS_DAY)
      dayStart.setUTCHours(0, 0, 0, 0)
      const dayEnd = new Date(now.getTime() - MS_DAY)
      dayEnd.setUTCHours(23, 59, 59, 999)
      return { from: fmt(dayStart), to: fmt(dayEnd) }
    },
    '1d': () => ({ from: fmt(subtract(MS_DAY)), to: fmt(now) }),
    '7d': () => ({ from: fmt(subtract(7 * MS_DAY)), to: fmt(now) }),
    '4w': () => ({ from: fmt(subtract(28 * MS_DAY)), to: fmt(now) }),
    '3M': () => ({ from: fmt(subtract(90 * MS_DAY)), to: fmt(now) }),
    '12M': () => ({ from: fmt(subtract(365 * MS_DAY)), to: fmt(now) }),
    '24M': () => ({ from: fmt(subtract(730 * MS_DAY)), to: fmt(now) }),
    all: () => ({ from: '2020-01-01 00:00:00', to: fmt(now) }),
  }

  const compute = periodMap[period]
  return compute ? compute() : null
}

const parseJsonFormField = (
  formData: FormData,
  field: string,
  fallback: string,
): JsonFormFieldResult => {
  try {
    return {
      ok: true,
      value: JSON.parse(formData.get(field)?.toString() || fallback),
    }
  } catch {
    return { ok: false, error: `Invalid JSON in ${field}` }
  }
}

const isRecord = (value: unknown): value is Record<string, unknown> =>
  typeof value === 'object' && value !== null

const isGoalMetadataFilters = (value: unknown): value is GoalMetadataFilter[] =>
  Array.isArray(value) &&
  value.every(
    (filter) =>
      isRecord(filter) &&
      typeof filter.key === 'string' &&
      typeof filter.value === 'string',
  )

const isGoalConditions = (value: unknown) => {
  if (value === null) {
    return true
  }

  if (
    !isRecord(value) ||
    !GOAL_CONDITION_RELATIONS.has(String(value.relation))
  ) {
    return false
  }

  return (
    Array.isArray(value.conditions) &&
    value.conditions.every((condition) => {
      if (
        !isRecord(condition) ||
        typeof condition.eventType !== 'string' ||
        typeof condition.field !== 'string' ||
        typeof condition.operator !== 'string'
      ) {
        return false
      }

      const allowedFields = GOAL_CONDITION_EVENT_TYPES[condition.eventType]
      if (
        !allowedFields ||
        !allowedFields.has(condition.field) ||
        !GOAL_CONDITION_OPERATORS.has(condition.operator)
      ) {
        return false
      }

      if (condition.field === 'metadata') {
        if (
          typeof condition.metadataKey !== 'string' ||
          condition.metadataKey.trim() === ''
        ) {
          return false
        }
      } else if (
        condition.metadataKey !== undefined &&
        typeof condition.metadataKey !== 'string'
      ) {
        return false
      }

      if (GOAL_CONDITION_VALUE_OPERATORS.has(condition.operator)) {
        return typeof condition.value === 'string' && condition.value !== ''
      }

      return (
        condition.value === undefined || typeof condition.value === 'string'
      )
    })
  )
}

const parseGoalJsonFields = (formData: FormData): GoalJsonFieldsResult => {
  const metadataFilters = parseJsonFormField(formData, 'metadataFilters', '[]')
  if (!metadataFilters.ok) {
    return metadataFilters
  }

  if (!isGoalMetadataFilters(metadataFilters.value)) {
    return { ok: false, error: 'Invalid metadataFilters' }
  }

  const conditions = parseJsonFormField(formData, 'conditions', 'null')
  if (!conditions.ok) {
    return conditions
  }

  if (!isGoalConditions(conditions.value)) {
    return { ok: false, error: 'Invalid conditions' }
  }

  return {
    ok: true,
    metadataFilters: metadataFilters.value,
    conditions: conditions.value,
  }
}

function formatDateForBackend(dateStr: string): string {
  if (!dateStr) return ''

  // If already in YYYY-MM-DD format, return as-is
  if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
    return dateStr
  }

  // Convert ISO 8601 or other formats to YYYY-MM-DD
  const date = new Date(dateStr)
  if (Number.isNaN(date.getTime())) {
    return dateStr
  }

  const yyyy = date.getUTCFullYear()
  const mm = String(date.getUTCMonth() + 1).padStart(2, '0')
  const dd = String(date.getUTCDate()).padStart(2, '0')
  return `${yyyy}-${mm}-${dd}`
}

function parseBooleanFormValue(
  value: FormDataEntryValue | null,
  fallback = false,
): boolean {
  if (value === null) {
    return fallback
  }

  const normalised = String(value).toLowerCase()
  return normalised === 'true' || normalised === 'on'
}

export const links: LinksFunction = () => [
  { rel: 'stylesheet', href: ProjectViewStyle },
]

export const meta: MetaFunction<typeof loader> = ({
  loaderData: data,
  location,
}) => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const { t } = useTranslation('common')
  const { pathname } = location
  const pid = data?.project?.id || _split(pathname, '/')[2]
  const previewURL = getProjectOgImageUrl(pid)

  if (data?.isPasswordRequired) {
    return [
      ...getTitle(t('titles.projectWithPassword')),
      ...getDescription(t('description.projectWithPassword')),
      ...getPreviewImage(previewURL),
    ]
  }

  const projectName = data?.project?.name || 'Untitled Project'
  const searchParams = new URLSearchParams(location.search)
  const tab = (searchParams.get('tab') || PROJECT_TABS.traffic) as
    | keyof typeof PROJECT_TABS
    | 'settings'
  const seoTabId = !isSelfhosted ? PROJECT_TABS.seo : null
  const tabNames: Record<string, string> = {
    [PROJECT_TABS.traffic]: t('dashboard.traffic'),
    [PROJECT_TABS.performance]: t('dashboard.performance'),
    ...(seoTabId ? { [seoTabId]: t('project.seo.title') } : {}),
    [PROJECT_TABS.profiles]: t('dashboard.profiles'),
    [PROJECT_TABS.sessions]: t('dashboard.sessions'),
    [PROJECT_TABS.replays]: t('dashboard.replays'),
    [PROJECT_TABS.errors]: t('dashboard.errors'),
    [PROJECT_TABS.funnels]: t('dashboard.funnels'),
    [PROJECT_TABS.goals]: t('dashboard.goals'),
    [PROJECT_TABS.featureFlags]: t('dashboard.featureFlags'),
    [PROJECT_TABS.captcha]: t('common.captcha'),
    [PROJECT_TABS.ai]: t('dashboard.askAi'),
    [PROJECT_TABS.experiments]: t('dashboard.experiments'),
    settings: t('common.settings'),
  }
  const tabName = tabNames[tab] || tabNames[PROJECT_TABS.traffic]
  const title = `${tabName} > ${projectName}`

  return [
    ...getTitle(title),
    ...getDescription(
      t('description.project', {
        name: projectName,
      }),
    ),
    ...getPreviewImage(previewURL),
  ]
}

export interface ProjectLoaderData {
  project: Project | null
  isPasswordRequired: boolean
  error?: string
  replaysData?: Promise<SessionReplaysResponse | null>
  featureFlagsData?: Promise<FeatureFlagsResponse | null>
  goalsData?: Promise<GoalsResponse | null>
  hasImportedData?: Promise<boolean>
}

const LOADER_BACKED_TABS = new Set<string>([
  PROJECT_TABS.replays,
  PROJECT_TABS.featureFlags,
  PROJECT_TABS.goals,
])

export function shouldRevalidate({
  currentUrl,
  nextUrl,
  formAction,
  defaultShouldRevalidate,
}: ShouldRevalidateFunctionArgs) {
  if (formAction) {
    return defaultShouldRevalidate
  }

  if (currentUrl.pathname !== nextUrl.pathname) {
    return true
  }

  const currentTab = currentUrl.searchParams.get('tab') || PROJECT_TABS.traffic
  const nextTab = nextUrl.searchParams.get('tab') || PROJECT_TABS.traffic

  if (currentTab !== nextTab) {
    return true
  }

  if (
    nextUrl.searchParams.get('password') !==
    currentUrl.searchParams.get('password')
  ) {
    return true
  }

  if (LOADER_BACKED_TABS.has(nextTab)) {
    return defaultShouldRevalidate
  }

  if (
    nextTab === PROJECT_TABS.traffic &&
    (nextUrl.searchParams.get('period') !==
      currentUrl.searchParams.get('period') ||
      nextUrl.searchParams.get('from') !==
        currentUrl.searchParams.get('from') ||
      nextUrl.searchParams.get('to') !== currentUrl.searchParams.get('to'))
  ) {
    return true
  }

  return false
}

export async function loader({ request, params }: LoaderFunctionArgs) {
  const { id: projectId } = params
  const url = new URL(request.url)

  const passwordFromQuery = url.searchParams.get('password') || ''
  const passwordFromCookie = getProjectPasswordCookie(request, projectId || '')
  const password = passwordFromQuery || passwordFromCookie

  const result = await serverFetch<Project>(request, `project/${projectId}`, {
    method: 'GET',
    headers: password ? { 'x-password': password } : undefined,
  })

  if (result.error || !result.data) {
    if (result.status === 404 || result.status === 403) {
      return redirect('/dashboard')
    }

    // legacy live demo redirect
    if (projectId === 'STEzHcB1rALV') {
      return redirect('/demo')
    }

    return data<ProjectLoaderData>(
      {
        project: null,
        isPasswordRequired: false,
        error: result.error as string,
      },
      {
        status: result.status,
        headers: createHeadersWithCookies(result.cookies),
      },
    )
  }

  const project = result.data

  if (project.isPasswordProtected && !project.role && !password) {
    return data<ProjectLoaderData>(
      { project: null, isPasswordRequired: true },
      { headers: createHeadersWithCookies(result.cookies) },
    )
  }

  const cookies = [...result.cookies]
  if (password && passwordFromQuery && password !== passwordFromCookie) {
    cookies.push(createProjectPasswordCookie(projectId || '', password))
  }

  let userTimezone = DEFAULT_TIMEZONE
  if (hasAuthTokens(request)) {
    const authResult = await authMeServer(request)
    cookies.push(...authResult.cookies)

    if (authResult.data?.user?.timezone) {
      userTimezone = authResult.data.user.timezone
    }
  }

  const tab =
    (url.searchParams.get('tab') as keyof typeof PROJECT_TABS) ||
    PROJECT_TABS.traffic
  const period = (url.searchParams.get('period') || '7d') as Period
  const urlTimeBucket = url.searchParams.get('timeBucket')
  const from = formatDateForBackend(url.searchParams.get('from') || '')
  const to = formatDateForBackend(url.searchParams.get('to') || '')
  const timezone = url.searchParams.get('timezone') || userTimezone
  const filters = parseFiltersFromUrl(url.searchParams)

  // Ensure the time bucket is valid for the selected period and date range
  const timeBucket = getValidTimeBucket(period, urlTimeBucket, from, to)

  const analyticsParams = {
    timeBucket,
    period,
    filters,
    from: from || undefined,
    to: to || undefined,
    timezone,
    password: password || undefined,
  }

  // Initialize deferred data promises
  let replaysData: Promise<SessionReplaysResponse | null> | undefined
  let featureFlagsData: Promise<FeatureFlagsResponse | null> | undefined
  let goalsData: Promise<GoalsResponse | null> | undefined
  let hasImportedData: Promise<boolean> | undefined

  // Only fetch data if project is valid and not locked
  if (project && !project.isLocked && projectId) {
    if (
      tab === PROJECT_TABS.replays &&
      (isSelfhosted || project.featureAccess?.replays === true)
    ) {
      replaysData = getSessionReplaysServer(
        request,
        projectId,
        analyticsParams,
      ).then((res) => res.data)
    } else if (
      tab === PROJECT_TABS.featureFlags &&
      (isSelfhosted || project.featureAccess?.featureFlags === true)
    ) {
      featureFlagsData = getProjectFeatureFlagsServer(request, projectId).then(
        (res) => res.data,
      )
    } else if (tab === PROJECT_TABS.goals) {
      goalsData = getProjectGoalsServer(
        request,
        projectId,
        undefined,
        undefined,
        undefined,
        password || undefined,
      ).then((res) => res.data)
    }

    const importRange = computeDateRangeForPeriod(period, from, to)
    if (importRange) {
      hasImportedData = serverFetch<{ hasImportedData: boolean }>(
        request,
        `data-import/${projectId}/has-imported-data?from=${encodeURIComponent(importRange.from)}&to=${encodeURIComponent(importRange.to)}`,
        {
          headers: password ? { 'x-password': password } : undefined,
        },
      )
        .then((res) => res.data?.hasImportedData === true)
        .catch(() => false)
    }
  }

  return data<ProjectLoaderData>(
    {
      project,
      isPasswordRequired: false,
      replaysData,
      featureFlagsData,
      goalsData,
      hasImportedData,
    },
    { headers: createHeadersWithCookies(cookies) },
  )
}

export interface ProjectViewActionData {
  success?: boolean
  intent?: string
  error?: string
  data?: unknown
}

export async function action({ request, params }: ActionFunctionArgs) {
  const { id: projectId } = params
  const formData = await request.formData()
  const intent = formData.get('intent')?.toString()

  const publicIntents = new Set([
    'get-project',
    'check-password',
    'get-project-views',
    'get-annotations',
    'get-funnels',
    'get-project-goals',
    'get-goal',
    'get-goal-stats',
    'get-goal-chart',
    'get-project-alerts',
    'get-alert',
    'get-project-feature-flags',
    'get-feature-flag',
    'get-feature-flag-stats',
    'get-feature-flag-profiles',
    'get-project-experiments',
    'get-experiment',
    'get-experiment-results',
    'get-filters',
    'get-errors-filters',
    'get-version-filters',
    'get-recent-ai-chats',
    'get-all-ai-chats',
    'list-ai-chats',
    'list-ai-chat-tags',
    'get-ai-chat',
    'create-ai-chat',
    'update-ai-chat',
    'update-ai-chat-meta',
    'delete-ai-chat',
    'generate-ai-chat-title',
    'submit-ai-chat-feedback',
  ])

  const getPassword = () =>
    formData.get('password')?.toString() ||
    getProjectPasswordCookie(request, projectId || '') ||
    ''

  if (!intent || (!publicIntents.has(intent) && !hasAuthTokens(request))) {
    redirectIfNotAuthenticated(request)
  }

  switch (intent) {
    // Goals
    case 'create-goal': {
      const name = formData.get('name')?.toString() || ''
      const type = formData.get('type')?.toString() || 'pageview'
      const matchType = formData.get('matchType')?.toString() || 'exact'
      const value = formData.get('value')?.toString() || ''
      const goalJson = parseGoalJsonFields(formData)

      if (!goalJson.ok) {
        return data<ProjectViewActionData>(
          { intent, error: goalJson.error },
          { status: 400 },
        )
      }

      const result = await serverFetch(request, 'goal', {
        method: 'POST',
        body: {
          pid: projectId,
          name,
          type,
          matchType,
          value,
          metadataFilters: goalJson.metadataFilters,
          conditions: goalJson.conditions,
        },
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'update-goal': {
      const goalId = formData.get('goalId')?.toString()
      const name = formData.get('name')?.toString()
      const type = formData.get('type')?.toString()
      const matchType = formData.get('matchType')?.toString()
      const value = formData.get('value')?.toString()
      const goalJson = parseGoalJsonFields(formData)

      if (!goalJson.ok) {
        return data<ProjectViewActionData>(
          { intent, error: goalJson.error },
          { status: 400 },
        )
      }

      const result = await serverFetch(request, `goal/${goalId}`, {
        method: 'PUT',
        body: {
          name,
          type,
          matchType,
          value,
          metadataFilters: goalJson.metadataFilters,
          conditions: goalJson.conditions,
        },
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'delete-goal': {
      const goalId = formData.get('goalId')?.toString()

      const result = await serverFetch(request, `goal/${goalId}`, {
        method: 'DELETE',
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Funnels
    case 'create-funnel': {
      const name = formData.get('name')?.toString() || ''
      const steps = JSON.parse(formData.get('steps')?.toString() || '[]')

      const result = await serverFetch(request, 'project/funnel', {
        method: 'POST',
        body: { pid: projectId, name, steps },
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'update-funnel': {
      const funnelId = formData.get('funnelId')?.toString()
      const name = formData.get('name')?.toString() || ''
      const steps = JSON.parse(formData.get('steps')?.toString() || '[]')

      const result = await serverFetch(request, 'project/funnel', {
        method: 'PATCH',
        body: { id: funnelId, pid: projectId, name, steps },
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'delete-funnel': {
      const funnelId = formData.get('funnelId')?.toString()

      const result = await serverFetch(
        request,
        `project/funnel/${funnelId}/${projectId}`,
        {
          method: 'DELETE',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Alerts
    case 'create-alert': {
      const name = formData.get('name')?.toString() || ''
      const queryMetric =
        formData.get('queryMetric')?.toString() || 'page_views'
      const queryCondition = formData.get('queryCondition')?.toString() || null
      const queryValue = formData.get('queryValue')
        ? Number(formData.get('queryValue'))
        : null
      const queryTime = formData.get('queryTime')?.toString() || null
      const queryCustomEvent =
        formData.get('queryCustomEvent')?.toString() || null
      const active = parseBooleanFormValue(formData.get('active'), true)
      const alertOnNewErrorsOnly = parseBooleanFormValue(
        formData.get('alertOnNewErrorsOnly'),
        true,
      )
      const alertOnEveryCustomEvent = parseBooleanFormValue(
        formData.get('alertOnEveryCustomEvent'),
        false,
      )

      const channelIds = formData
        .getAll('channelIds')
        .map((v) => v.toString())
        .filter(Boolean)
      const messageTemplate =
        formData.get('messageTemplate')?.toString() ?? null
      const emailSubjectTemplate =
        formData.get('emailSubjectTemplate')?.toString() ?? null

      const result = await serverFetch(request, 'alert', {
        method: 'POST',
        body: {
          pid: projectId,
          name,
          queryMetric,
          queryCondition,
          queryValue,
          queryTime,
          queryCustomEvent,
          alertOnNewErrorsOnly,
          alertOnEveryCustomEvent,
          active,
          channelIds,
          messageTemplate: messageTemplate || null,
          emailSubjectTemplate: emailSubjectTemplate || null,
        },
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'update-alert': {
      const alertId = formData.get('alertId')?.toString()
      const name = formData.get('name')?.toString()
      const active = parseBooleanFormValue(formData.get('active'))
      const queryMetric = formData.get('queryMetric')?.toString()
      const queryCondition = formData.get('queryCondition')?.toString() || null
      const queryValue = formData.get('queryValue')
        ? Number(formData.get('queryValue'))
        : null
      const queryTime = formData.get('queryTime')?.toString() || null
      const queryCustomEvent =
        formData.get('queryCustomEvent')?.toString() || null
      const alertOnNewErrorsOnly = formData.has('alertOnNewErrorsOnly')
        ? parseBooleanFormValue(formData.get('alertOnNewErrorsOnly'))
        : undefined
      const alertOnEveryCustomEvent = formData.has('alertOnEveryCustomEvent')
        ? parseBooleanFormValue(formData.get('alertOnEveryCustomEvent'))
        : undefined

      const body: Record<string, unknown> = {}
      if (name !== undefined) body.name = name
      body.active = active
      if (queryMetric !== undefined) body.queryMetric = queryMetric
      body.queryCondition = queryCondition
      body.queryValue = queryValue
      body.queryTime = queryTime
      body.queryCustomEvent = queryCustomEvent
      if (alertOnNewErrorsOnly !== undefined)
        body.alertOnNewErrorsOnly = alertOnNewErrorsOnly
      if (alertOnEveryCustomEvent !== undefined)
        body.alertOnEveryCustomEvent = alertOnEveryCustomEvent

      const channelIds = formData
        .getAll('channelIds')
        .map((v) => v.toString())
        .filter(Boolean)
      if (formData.has('channelIdsProvided') || channelIds.length > 0) {
        body.channelIds = channelIds
      }
      if (formData.has('messageTemplate')) {
        const v = formData.get('messageTemplate')?.toString() || ''
        body.messageTemplate = v || null
      }
      if (formData.has('emailSubjectTemplate')) {
        const v = formData.get('emailSubjectTemplate')?.toString() || ''
        body.emailSubjectTemplate = v || null
      }

      const result = await serverFetch(request, `alert/${alertId}`, {
        method: 'PUT',
        body,
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'delete-alert': {
      const alertId = formData.get('alertId')?.toString()

      const result = await serverFetch(request, `alert/${alertId}`, {
        method: 'DELETE',
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Annotations
    case 'get-annotations': {
      const password = getPassword()

      const result = await serverFetch(
        request,
        `project/annotations/${projectId}`,
        {
          method: 'GET',
          headers: password ? { 'x-password': password } : undefined,
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'create-annotation': {
      const date = formData.get('date')?.toString() || ''
      const text = formData.get('text')?.toString() || ''

      const result = await serverFetch(request, 'project/annotation', {
        method: 'POST',
        body: { pid: projectId, date, text },
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'update-annotation': {
      const annotationId = formData.get('annotationId')?.toString() || ''
      const date = formData.get('date')?.toString() || ''
      const text = formData.get('text')?.toString() || ''

      const result = await serverFetch(request, 'project/annotation', {
        method: 'PATCH',
        body: { id: annotationId, pid: projectId, date, text },
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'delete-annotation': {
      const annotationId = formData.get('annotationId')?.toString()

      const result = await serverFetch(
        request,
        `project/annotation/${annotationId}/${projectId}`,
        {
          method: 'DELETE',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Project Views
    case 'get-project-views': {
      const password = getPassword()

      const result = await serverFetch(request, `project/${projectId}/views`, {
        method: 'GET',
        headers: password ? { 'x-password': password } : undefined,
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'create-project-view': {
      const name = formData.get('name')?.toString() || ''
      const requestedType = formData.get('type')?.toString()
      const type = requestedType === 'performance' ? 'performance' : 'traffic'
      const filters = JSON.parse(formData.get('filters')?.toString() || '[]')
      const customEvents =
        type === 'traffic'
          ? JSON.parse(formData.get('customEvents')?.toString() || '[]')
          : []

      const result = await serverFetch(request, `project/${projectId}/views`, {
        method: 'POST',
        body: { name, type, filters, customEvents },
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'update-project-view': {
      const viewId = formData.get('viewId')?.toString()
      const name = formData.get('name')?.toString() || ''
      const filters = JSON.parse(formData.get('filters')?.toString() || '[]')
      const customEvents = JSON.parse(
        formData.get('customEvents')?.toString() || '[]',
      )

      const result = await serverFetch(
        request,
        `project/${projectId}/views/${viewId}`,
        {
          method: 'PATCH',
          body: { name, filters, customEvents },
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'delete-project-view': {
      const viewId = formData.get('viewId')?.toString()

      const result = await serverFetch(
        request,
        `project/${projectId}/views/${viewId}`,
        {
          method: 'DELETE',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // AI Chat
    case 'get-recent-ai-chats':
    case 'get-all-ai-chats':
    case 'list-ai-chats': {
      const params = new URLSearchParams()
      const limit = formData.get('limit')?.toString()
      const skip = formData.get('skip')?.toString()
      const take = formData.get('take')?.toString()
      const search = formData.get('search')?.toString().trim()
      const tag = formData.get('tag')?.toString()
      const pinnedRaw = formData.get('pinned')?.toString()
      const orderByPinnedRaw = formData.get('orderByPinned')?.toString()

      if (limit) params.append('limit', limit)
      if (skip) params.append('skip', skip)
      if (take) params.append('take', take)
      if (search && search.length >= 2) params.append('search', search)
      if (tag) params.append('tag', tag)
      if (pinnedRaw === 'true' || pinnedRaw === 'false') {
        params.append('pinned', pinnedRaw)
      }
      if (orderByPinnedRaw === 'true' || orderByPinnedRaw === 'false') {
        params.append('orderByPinned', orderByPinnedRaw)
      }

      const qs = params.toString()
      const result = await serverFetch(
        request,
        `ai/${projectId}/chats${qs ? `?${qs}` : ''}`,
        {
          method: 'GET',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'list-ai-chat-tags': {
      const result = await serverFetch(request, `ai/${projectId}/chats/tags`, {
        method: 'GET',
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-ai-chat': {
      const chatId = formData.get('chatId')?.toString()

      const result = await serverFetch(
        request,
        `ai/${projectId}/chats/${chatId}`,
        {
          method: 'GET',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'create-ai-chat': {
      const messages = JSON.parse(formData.get('messages')?.toString() || '[]')
      const name = formData.get('name')?.toString()
      const parentChatId = formData.get('parentChatId')?.toString()

      const body: Record<string, unknown> = { messages, name }
      if (parentChatId) body.parentChatId = parentChatId

      const result = await serverFetch(request, `ai/${projectId}/chats`, {
        method: 'POST',
        body,
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'update-ai-chat': {
      const chatId = formData.get('chatId')?.toString()
      const messages = formData.get('messages')
        ? JSON.parse(formData.get('messages')!.toString())
        : undefined
      const name = formData.get('name')?.toString()

      const body: Record<string, unknown> = {}
      if (messages) body.messages = messages
      if (name !== undefined) body.name = name

      const result = await serverFetch(
        request,
        `ai/${projectId}/chats/${chatId}`,
        {
          method: 'POST',
          body,
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'update-ai-chat-meta': {
      const chatId = formData.get('chatId')?.toString()
      const pinnedRaw = formData.get('pinned')?.toString()
      const tagsRaw = formData.get('tags')?.toString()
      const name = formData.get('name')?.toString()

      const body: Record<string, unknown> = {}
      if (pinnedRaw === 'true' || pinnedRaw === 'false') {
        body.pinned = pinnedRaw === 'true'
      }
      if (tagsRaw !== undefined) {
        try {
          body.tags = JSON.parse(tagsRaw)
        } catch {
          return data<ProjectViewActionData>(
            { intent, error: 'Malformed tags payload' },
            { status: 400 },
          )
        }
      }
      if (name !== undefined) body.name = name

      const result = await serverFetch(
        request,
        `ai/${projectId}/chats/${chatId}`,
        {
          method: 'PATCH',
          body,
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'delete-ai-chat': {
      const chatId = formData.get('chatId')?.toString()

      const result = await serverFetch(
        request,
        `ai/${projectId}/chats/${chatId}`,
        {
          method: 'DELETE',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'generate-ai-chat-title': {
      const chatId = formData.get('chatId')?.toString()

      const result = await serverFetch(
        request,
        `ai/${projectId}/chats/${chatId}/title`,
        {
          method: 'POST',
          body: {},
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'submit-ai-chat-feedback': {
      const chatId = formData.get('chatId')?.toString()
      const rawRating = formData.get('rating')?.toString()
      const messageIndex = formData.get('messageIndex')?.toString()
      const comment = formData.get('comment')?.toString()

      if (rawRating !== 'good' && rawRating !== 'bad') {
        return data<ProjectViewActionData>(
          { intent, error: 'Invalid rating value' },
          { status: 400 },
        )
      }
      const rating: 'good' | 'bad' = rawRating

      const body: Record<string, unknown> = { rating }
      if (messageIndex !== undefined && messageIndex !== '') {
        body.messageIndex = Number(messageIndex)
      }
      if (comment) body.comment = comment

      const result = await serverFetch(
        request,
        `ai/${projectId}/chats/${chatId}/feedback`,
        {
          method: 'POST',
          body,
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Feature Flags
    case 'get-project-feature-flags': {
      const take = Number(formData.get('take') || '20')
      const skip = Number(formData.get('skip') || '0')
      const search = formData.get('search')?.toString() || ''

      const params = new URLSearchParams({
        take: String(take),
        skip: String(skip),
      })
      if (search) params.append('search', search)

      const result = await serverFetch(
        request,
        `feature-flag/project/${projectId}?${params.toString()}`,
        {
          method: 'GET',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-feature-flag': {
      const flagId = formData.get('flagId')?.toString()

      const result = await serverFetch(request, `feature-flag/${flagId}`, {
        method: 'GET',
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'create-feature-flag': {
      const key = formData.get('key')?.toString() || ''
      const description = formData.get('description')?.toString() || ''
      const flagType = formData.get('flagType')?.toString() || 'boolean'
      const rolloutPercentage = Number(
        formData.get('rolloutPercentage') || '100',
      )
      const targetingRules = JSON.parse(
        formData.get('targetingRules')?.toString() || '[]',
      )
      const enabled = formData.get('enabled') === 'true'
      const scheduledChangeRaw = formData.get('scheduledChange')?.toString()
      let scheduledChange: unknown = null

      if (scheduledChangeRaw) {
        try {
          scheduledChange = JSON.parse(scheduledChangeRaw)
        } catch {
          return data<ProjectViewActionData>(
            { intent, error: 'Invalid JSON in scheduledChange' },
            { status: 400 },
          )
        }
      }

      const result = await serverFetch(request, 'feature-flag', {
        method: 'POST',
        body: {
          pid: projectId,
          key,
          description,
          flagType,
          rolloutPercentage,
          targetingRules,
          enabled,
          scheduledChange,
        },
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'update-feature-flag': {
      const flagId = formData.get('flagId')?.toString()
      const key = formData.get('key')?.toString()
      const description = formData.get('description')?.toString()
      const flagType = formData.get('flagType')?.toString()
      const rolloutPercentage = formData.get('rolloutPercentage')
        ? Number(formData.get('rolloutPercentage'))
        : undefined
      const targetingRules = formData.get('targetingRules')
        ? JSON.parse(formData.get('targetingRules')!.toString())
        : undefined
      const enabled = formData.has('enabled')
        ? formData.get('enabled') === 'true'
        : undefined
      let scheduledChange: unknown = undefined

      if (formData.has('scheduledChange')) {
        const scheduledChangeRaw = formData.get('scheduledChange')?.toString()

        if (scheduledChangeRaw === 'null') {
          scheduledChange = null
        } else {
          try {
            scheduledChange = JSON.parse(scheduledChangeRaw || '')
          } catch {
            return data<ProjectViewActionData>(
              { intent, error: 'Invalid JSON in scheduledChange' },
              { status: 400 },
            )
          }
        }
      }

      const body: Record<string, unknown> = {}
      if (key !== undefined) body.key = key
      if (description !== undefined) body.description = description
      if (flagType !== undefined) body.flagType = flagType
      if (rolloutPercentage !== undefined)
        body.rolloutPercentage = rolloutPercentage
      if (targetingRules !== undefined) body.targetingRules = targetingRules
      if (enabled !== undefined) body.enabled = enabled
      if (scheduledChange !== undefined) body.scheduledChange = scheduledChange

      const result = await serverFetch(request, `feature-flag/${flagId}`, {
        method: 'PUT',
        body,
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'kill-feature-flag': {
      const flagId = formData.get('flagId')?.toString()
      const rawKillSwitch = formData.get('killSwitchValue')?.toString()

      if (rawKillSwitch !== 'true' && rawKillSwitch !== 'false') {
        return data<ProjectViewActionData>(
          { intent, error: 'Invalid killSwitchValue' },
          { status: 400 },
        )
      }

      const killSwitchValue = rawKillSwitch === 'true'

      const result = await serverFetch(request, `feature-flag/${flagId}/kill`, {
        method: 'PUT',
        body: { killSwitchValue },
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'release-feature-flag-kill-switch': {
      const flagId = formData.get('flagId')?.toString()

      const result = await serverFetch(
        request,
        `feature-flag/${flagId}/release-kill-switch`,
        {
          method: 'PUT',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'delete-feature-flag': {
      const flagId = formData.get('flagId')?.toString()

      const result = await serverFetch(request, `feature-flag/${flagId}`, {
        method: 'DELETE',
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-feature-flag-stats': {
      const flagId = formData.get('flagId')?.toString()
      const period = formData.get('period')?.toString() || '7d'
      const fromDate = formData.get('from')?.toString() || ''
      const toDate = formData.get('to')?.toString() || ''
      const tz = formData.get('timezone')?.toString() || ''
      const filters = formData.get('filters')?.toString() || '[]'

      const params = new URLSearchParams({ period })
      if (fromDate) params.append('from', fromDate)
      if (toDate) params.append('to', toDate)
      if (tz) params.append('timezone', tz)
      params.append('filters', filters)

      const result = await serverFetch(
        request,
        `feature-flag/${flagId}/stats?${params.toString()}`,
        {
          method: 'GET',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: { flagId, stats: result.data } },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-feature-flag-profiles': {
      const flagId = formData.get('flagId')?.toString()
      const period = formData.get('period')?.toString() || '7d'
      const fromDate = formData.get('from')?.toString() || ''
      const toDate = formData.get('to')?.toString() || ''
      const tz = formData.get('timezone')?.toString() || ''
      const take = Number(formData.get('take') || '15')
      const skip = Number(formData.get('skip') || '0')
      const resultFilter = formData.get('result')?.toString() || ''

      const params = new URLSearchParams({
        period,
        take: String(take),
        skip: String(skip),
      })
      if (fromDate) params.append('from', fromDate)
      if (toDate) params.append('to', toDate)
      if (tz) params.append('timezone', tz)
      if (resultFilter && resultFilter !== 'all')
        params.append('result', resultFilter)

      const result = await serverFetch(
        request,
        `feature-flag/${flagId}/profiles?${params.toString()}`,
        {
          method: 'GET',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      const profilesData = result.data as { profiles: unknown[]; total: number }
      return data<ProjectViewActionData>(
        {
          intent,
          success: true,
          data: {
            flagId,
            profiles: profilesData.profiles,
            total: profilesData.total,
          },
        },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Experiments
    case 'get-project-experiments': {
      const password = getPassword()
      const take = Number(formData.get('take') || '20')
      const skip = Number(formData.get('skip') || '0')
      const search = formData.get('search')?.toString() || ''

      const params = new URLSearchParams({
        take: String(take),
        skip: String(skip),
      })
      if (search) params.append('search', search)

      const result = await serverFetch(
        request,
        `experiment/project/${projectId}?${params.toString()}`,
        {
          method: 'GET',
          headers: password ? { 'x-password': password } : undefined,
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-experiment': {
      const experimentId = formData.get('experimentId')?.toString()
      const password = getPassword()

      const result = await serverFetch(request, `experiment/${experimentId}`, {
        method: 'GET',
        headers: password ? { 'x-password': password } : undefined,
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'create-experiment': {
      const name = formData.get('name')?.toString() || ''
      const description = formData.get('description')?.toString() || ''
      const hypothesis = formData.get('hypothesis')?.toString() || ''
      const exposureTrigger =
        formData.get('exposureTrigger')?.toString() || 'feature_flag'
      const customEventName = formData.get('customEventName')?.toString() || ''
      const multipleVariantHandling =
        formData.get('multipleVariantHandling')?.toString() || 'exclude'
      const filterInternalUsers = formData.get('filterInternalUsers') === 'true'
      const featureFlagMode =
        formData.get('featureFlagMode')?.toString() || 'create'
      const featureFlagKey = formData.get('featureFlagKey')?.toString() || ''
      const existingFeatureFlagId =
        formData.get('existingFeatureFlagId')?.toString() || ''
      const goalId = formData.get('goalId')?.toString() || ''
      const variants = JSON.parse(formData.get('variants')?.toString() || '[]')

      const body: Record<string, unknown> = {
        pid: projectId,
        name,
        variants,
      }
      if (description) body.description = description
      if (hypothesis) body.hypothesis = hypothesis
      if (exposureTrigger) body.exposureTrigger = exposureTrigger
      if (customEventName) body.customEventName = customEventName
      if (multipleVariantHandling)
        body.multipleVariantHandling = multipleVariantHandling
      body.filterInternalUsers = filterInternalUsers
      if (featureFlagMode) body.featureFlagMode = featureFlagMode
      if (featureFlagKey) body.featureFlagKey = featureFlagKey
      if (existingFeatureFlagId)
        body.existingFeatureFlagId = existingFeatureFlagId
      if (goalId) body.goalId = goalId

      const result = await serverFetch(request, 'experiment', {
        method: 'POST',
        body,
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'update-experiment': {
      const experimentId = formData.get('experimentId')?.toString()
      const name = formData.get('name')?.toString()
      const description = formData.get('description')?.toString()
      const hypothesis = formData.get('hypothesis')?.toString()
      const exposureTrigger = formData.get('exposureTrigger')?.toString()
      const customEventName = formData.get('customEventName')?.toString()
      const multipleVariantHandling = formData
        .get('multipleVariantHandling')
        ?.toString()
      const filterInternalUsers = formData.has('filterInternalUsers')
        ? formData.get('filterInternalUsers') === 'true'
        : undefined
      const featureFlagMode = formData.get('featureFlagMode')?.toString()
      const featureFlagKey = formData.get('featureFlagKey')?.toString()
      const existingFeatureFlagId = formData
        .get('existingFeatureFlagId')
        ?.toString()
      const goalId = formData.get('goalId')?.toString()
      const variants = formData.get('variants')
        ? JSON.parse(formData.get('variants')!.toString())
        : undefined

      const body: Record<string, unknown> = {}
      if (name !== undefined) body.name = name
      if (description !== undefined) body.description = description
      if (hypothesis !== undefined) body.hypothesis = hypothesis
      if (exposureTrigger !== undefined) body.exposureTrigger = exposureTrigger
      if (customEventName !== undefined) body.customEventName = customEventName
      if (multipleVariantHandling !== undefined)
        body.multipleVariantHandling = multipleVariantHandling
      if (filterInternalUsers !== undefined)
        body.filterInternalUsers = filterInternalUsers
      if (featureFlagMode !== undefined) body.featureFlagMode = featureFlagMode
      if (featureFlagMode === 'create' && featureFlagKey)
        body.featureFlagKey = featureFlagKey
      if (featureFlagMode === 'link') body.featureFlagKey = null
      if (featureFlagMode === 'link' && existingFeatureFlagId)
        body.existingFeatureFlagId = existingFeatureFlagId
      if (goalId !== undefined) body.goalId = goalId || null
      if (variants !== undefined) body.variants = variants

      const result = await serverFetch(request, `experiment/${experimentId}`, {
        method: 'PUT',
        body,
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'delete-experiment': {
      const experimentId = formData.get('experimentId')?.toString()

      const result = await serverFetch(request, `experiment/${experimentId}`, {
        method: 'DELETE',
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'start-experiment': {
      const experimentId = formData.get('experimentId')?.toString()

      const result = await serverFetch(
        request,
        `experiment/${experimentId}/start`,
        {
          method: 'POST',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'pause-experiment': {
      const experimentId = formData.get('experimentId')?.toString()

      const result = await serverFetch(
        request,
        `experiment/${experimentId}/pause`,
        {
          method: 'POST',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'complete-experiment': {
      const experimentId = formData.get('experimentId')?.toString()

      const result = await serverFetch(
        request,
        `experiment/${experimentId}/complete`,
        {
          method: 'POST',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-experiment-results': {
      const experimentId = formData.get('experimentId')?.toString()
      const password = getPassword()
      const period = formData.get('period')?.toString() || '7d'
      const timeBucket = formData.get('timeBucket')?.toString() || 'day'
      const fromDate = formData.get('from')?.toString() || ''
      const toDate = formData.get('to')?.toString() || ''
      const tz = formData.get('timezone')?.toString() || ''
      const filters = formData.get('filters')?.toString() || '[]'

      const params = new URLSearchParams({ period, timeBucket })
      if (fromDate) params.append('from', fromDate)
      if (toDate) params.append('to', toDate)
      if (tz) params.append('timezone', tz)
      params.append('filters', filters)

      const result = await serverFetch(
        request,
        `experiment/${experimentId}/results?${params.toString()}`,
        {
          method: 'GET',
          headers: password ? { 'x-password': password } : undefined,
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Goals (getters)
    case 'get-project-goals': {
      const password = getPassword()
      const take = Number(formData.get('take') || '20')
      const skip = Number(formData.get('skip') || '0')
      const search = formData.get('search')?.toString() || ''

      const params = new URLSearchParams({
        take: String(take),
        skip: String(skip),
      })
      if (search) params.append('search', search)

      const result = await serverFetch(
        request,
        `goal/project/${projectId}?${params.toString()}`,
        {
          method: 'GET',
          headers: password ? { 'x-password': password } : undefined,
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-goal': {
      const goalId = formData.get('goalId')?.toString()
      const password = getPassword()

      const result = await serverFetch(request, `goal/${goalId}`, {
        method: 'GET',
        headers: password ? { 'x-password': password } : undefined,
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-goal-stats': {
      const goalId = formData.get('goalId')?.toString()
      const period = formData.get('period')?.toString() || '7d'
      const fromDate = formData.get('from')?.toString() || ''
      const toDate = formData.get('to')?.toString() || ''
      const tz = formData.get('timezone')?.toString() || ''
      const filters = formData.get('filters')?.toString() || '[]'

      const params = new URLSearchParams({ period })
      if (fromDate) params.append('from', fromDate)
      if (toDate) params.append('to', toDate)
      if (tz) params.append('timezone', tz)
      params.append('filters', filters)

      const result = await serverFetch(
        request,
        `goal/${goalId}/stats?${params.toString()}`,
        {
          method: 'GET',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-goal-chart': {
      const goalId = formData.get('goalId')?.toString()
      const period = formData.get('period')?.toString() || '7d'
      const fromDate = formData.get('from')?.toString() || ''
      const toDate = formData.get('to')?.toString() || ''
      const timeBucket = formData.get('timeBucket')?.toString() || 'day'
      const tz = formData.get('timezone')?.toString() || ''
      const filters = formData.get('filters')?.toString() || '[]'

      const params = new URLSearchParams({ period, timeBucket })
      if (fromDate) params.append('from', fromDate)
      if (toDate) params.append('to', toDate)
      if (tz) params.append('timezone', tz)
      params.append('filters', filters)

      const result = await serverFetch(
        request,
        `goal/${goalId}/chart?${params.toString()}`,
        {
          method: 'GET',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Funnels (getters)
    case 'get-funnels': {
      const password = getPassword()

      const result = await serverFetch(
        request,
        `project/funnels/${projectId}`,
        {
          method: 'GET',
          headers: password ? { 'x-password': password } : undefined,
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Alerts (getters)
    case 'get-project-alerts': {
      const take = Number(formData.get('take') || '25')
      const skip = Number(formData.get('skip') || '0')

      const result = await serverFetch(
        request,
        `alert/project/${projectId}?take=${take}&skip=${skip}`,
        {
          method: 'GET',
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-alert': {
      const alertId = formData.get('alertId')?.toString()

      const result = await serverFetch(request, `alert/${alertId}`, {
        method: 'GET',
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-alert-template-variables': {
      const metric = formData.get('metric')?.toString() || ''
      const result = await serverFetch(
        request,
        `alert/template-variables?metric=${encodeURIComponent(metric)}`,
        { method: 'GET' },
      )
      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }
      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Filters
    case 'get-filters': {
      const filterType = formData.get('type')?.toString() || ''
      const password = getPassword()

      const result = await serverFetch(
        request,
        `log/filters?pid=${projectId}&type=${filterType}`,
        {
          method: 'GET',
          headers: password ? { 'x-password': password } : undefined,
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-errors-filters': {
      const filterType = formData.get('type')?.toString() || ''
      const password = getPassword()

      const result = await serverFetch(
        request,
        `log/errors-filters?pid=${projectId}&type=${filterType}`,
        {
          method: 'GET',
          headers: password ? { 'x-password': password } : undefined,
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    case 'get-version-filters': {
      const dataType = formData.get('dataType')?.toString() || 'traffic'
      const column = formData.get('column')?.toString() || 'br'
      const password = getPassword()

      const result = await serverFetch(
        request,
        `log/filters/versions?pid=${projectId}&type=${dataType}&column=${column}`,
        {
          method: 'GET',
          headers: password ? { 'x-password': password } : undefined,
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Error status update
    case 'update-error-status': {
      const eid = formData.get('eid')?.toString()
      const eids = formData.get('eids')
        ? JSON.parse(formData.get('eids')!.toString())
        : undefined
      const status = formData.get('status')?.toString() || 'active'

      const result = await serverFetch(request, 'log/error-status', {
        method: 'PATCH',
        body: { pid: projectId, eid, eids, status },
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(result.cookies) },
      )
    }

    // Project data
    case 'get-project': {
      const password = getPassword()

      const result = await serverFetch(request, `project/${projectId}`, {
        method: 'GET',
        headers: password ? { 'x-password': password } : undefined,
      })

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: result.status },
        )
      }

      const cookies = [...result.cookies]
      if (password) {
        cookies.push(createProjectPasswordCookie(projectId || '', password))
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(cookies) },
      )
    }

    case 'check-password': {
      const password = getPassword()

      const result = await serverFetch<boolean>(
        request,
        `project/password/${projectId}`,
        {
          method: 'GET',
          headers: { 'x-password': password },
        },
      )

      if (result.error) {
        return data<ProjectViewActionData>(
          { intent, error: result.error as string },
          { status: 400 },
        )
      }

      const cookies = [...result.cookies]
      if (password && result.data) {
        cookies.push(createProjectPasswordCookie(projectId || '', password))
      }

      return data<ProjectViewActionData>(
        { intent, success: true, data: result.data },
        { headers: createHeadersWithCookies(cookies) },
      )
    }

    default:
      return data<ProjectViewActionData>(
        { error: 'Unknown action' },
        { status: 400 },
      )
  }
}

export default function Index() {
  const { id } = useRequiredParams<{ id: string }>()

  return (
    <CurrentProjectProvider id={id}>
      <ViewProject />
    </CurrentProjectProvider>
  )
}