"use client"

import Link from "next/link"
import { ArrowRight } from "lucide-react"
import { cn } from "@/lib/utils"
import { useEffect, useMemo, useState } from "react"
import type { AnnouncementConfig } from "@/config/announcements"

interface AnnouncementTickerProps {
  config: AnnouncementConfig
  className?: string
  speed?: number
  pauseBeforeStart?: number
  ctaClassName?: string
  highlightClassName?: string
  textClassName?: string
}

export function AnnouncementTicker({
  config,
  className,
  speed = 18,
  pauseBeforeStart = 120,
  ctaClassName,
  highlightClassName,
  textClassName,
}: AnnouncementTickerProps) {
  const { enabled, message, href, highlight, cta } = config
  const [displayText, setDisplayText] = useState("")

  useEffect(() => {
    if (!enabled || !message) return

    let index = 0
    let animationFrame: number

    const typeCharacter = () => {
      index = Math.min(index + 1, message.length)
      setDisplayText(message.slice(0, index))

      if (index < message.length) {
        animationFrame = window.setTimeout(typeCharacter, speed)
      }
    }

    const startTimeout = window.setTimeout(() => {
      typeCharacter()
    }, pauseBeforeStart)

    return () => {
      clearTimeout(startTimeout)
      window.clearTimeout(animationFrame)
    }
  }, [enabled, message, pauseBeforeStart, speed])

  const renderedContent = useMemo(() => {
    if (!highlight) {
      return displayText
    }

    const highlightIndex = displayText.indexOf(highlight)
    if (highlightIndex === -1) {
      return displayText
    }

    const before = displayText.slice(0, highlightIndex)
    const match = displayText.slice(highlightIndex, highlightIndex + highlight.length)
    const after = displayText.slice(highlightIndex + highlight.length)

    return (
      <>
        {before}
        <span className={cn("text-primary font-medium", highlightClassName)}>{match}</span>
        {after}
      </>
    )
  }, [displayText, highlight, highlightClassName])

  if (!enabled || !message) {
    return null
  }

  const content = (
    <div
      className={cn(
        "group inline-flex w-full items-center justify-between gap-2 overflow-hidden whitespace-nowrap rounded-lg border border-border bg-muted/10 px-3 py-2 text-xs text-muted-foreground transition-all hover:border-primary/40 hover:bg-muted/20 sm:text-sm",
        className,
      )}
    >
      <div className="flex min-w-0 items-center gap-2 text-muted-foreground">
        <span className={cn("truncate font-medium", textClassName)}>
          {renderedContent || "\u00A0"}
        </span>
      </div>
      {(cta || href) && (
        <span
          className={cn(
            "flex items-center gap-1 text-[11px] font-medium text-primary transition group-hover:text-primary/80 sm:text-xs",
            ctaClassName,
          )}
        >
          {cta ?? "Open"}
          <ArrowRight className="h-3.5 w-3.5" />
        </span>
      )}
    </div>
  )

  if (href) {
    return (
      <Link href={href} target={href.startsWith("http") ? "_blank" : undefined} rel="noreferrer">
        {content}
      </Link>
    )
  }

  return content
}
