"use client"

import { cva } from "class-variance-authority"

import { env } from "@/env/client"

import styles from "./index.module.css"

const variants = cva(styles.environmentWatermark, {
  variants: {
    environment: {
      "pre-prod": styles.preprod,
      stage: styles.stage,
      test: styles.test,
      development: styles.development,
    },
  },
})
const namedEnvironments = ["pre-prod", "stage", "test", "development"] as const

export function EnvironmentWatermark() {
  if (
    !env.NEXT_PUBLIC_SENTRY_ENVIRONMENT ||
    env.NEXT_PUBLIC_SENTRY_ENVIRONMENT.localeCompare("production") === 0
  ) {
    return null
  }

  const { environment, name } = getEnvironmentName()
  const displayValue = name === environment ? name : `${name} (${environment})`

  return (
    <div className={variants({ environment: environment })}>
      <span>{displayValue}</span>
    </div>
  )
}

function getEnvironmentName(): {
  name: string
  environment: (typeof namedEnvironments)[number]
} {
  const environment = getEnvironmentType()
  const hostname =
    typeof window !== "undefined" ? window.location.hostname : undefined

  if (hostname === "localhost") {
    return { name: "development", environment }
  }

  if (hostname?.endsWith("netlify.app")) {
    const featureBranch = hostname.includes("--")
      ? hostname.split("--").at(0)
      : null

    if (featureBranch) {
      return {
        name: `${featureBranch.slice(0, 10)}`,
        environment,
      }
    }
  }

  return { name: environment, environment }
}

function getEnvironmentType() {
  const environment =
    namedEnvironments.find(
      (e) => e.localeCompare(env.NEXT_PUBLIC_SENTRY_ENVIRONMENT) === 0
    ) ?? "test"

  return environment
}
