'use client'
import React, { useState, useEffect } from 'react'

type LinkGroup = {
  type?: 'reference' | 'custom' | null
  reference?: { slug?: string | null; relationTo?: string } | null
  url?: string | null
  newTab?: boolean | null
}

type Props = {
  text?: string | null
  buttonLabel?: string | null
  buttonLink?: LinkGroup | null
  dismissible?: boolean | null
  backgroundColor?: 'yellow' | 'navy' | 'mint' | null
}

function resolveUrl(link?: LinkGroup | null): string | null {
  if (!link) return null
  if (link.type === 'reference' && link.reference) {
    const slug = link.reference.slug
    return slug ? `/${slug}` : null
  }
  return link.url ?? null
}

export const AnnouncementBarComponent: React.FC<Props> = ({
  text,
  buttonLabel,
  buttonLink,
  dismissible = true,
  backgroundColor = 'yellow',
}) => {
  const [dismissed, setDismissed] = useState(false)

  useEffect(() => {
    const key = `fd-announcement-${text?.slice(0, 20)}`
    if (typeof window !== 'undefined' && localStorage.getItem(key) === 'dismissed') {
      setDismissed(true)
    }
  }, [text])

  if (dismissed || !text) return null

  const bgClass =
    backgroundColor === 'navy' ? 'bg-fd-navy text-white' :
    backgroundColor === 'mint' ? 'bg-fd-mint text-fd-navy' :
    'bg-fd-yellow text-fd-navy'

  const handleDismiss = () => {
    const key = `fd-announcement-${text?.slice(0, 20)}`
    if (typeof window !== 'undefined') localStorage.setItem(key, 'dismissed')
    setDismissed(true)
  }

  const href = resolveUrl(buttonLink)
  const newTab = buttonLink?.newTab ?? false

  return (
    <div
      className={`w-full px-10 py-2 relative flex items-center justify-center ${bgClass}`}
      role="status"
    >
      {/* Centered content — px-10 leaves room for the dismiss button on both sides */}
      <div className="flex items-center justify-center gap-3 text-sm font-joey text-center flex-wrap">
        <span>{text}</span>
        {buttonLabel && href && (
          <a
            href={href}
            target={newTab ? '_blank' : undefined}
            rel={newTab ? 'noopener noreferrer' : undefined}
            className="underline font-joey-bold hover:opacity-70 transition-opacity whitespace-nowrap"
          >
            {buttonLabel}
          </a>
        )}
      </div>

      {/* Dismiss — truly absolute so it doesn't affect centering */}
      {dismissible && (
        <button
          onClick={handleDismiss}
          className="absolute right-4 top-1/2 -translate-y-1/2 opacity-60 hover:opacity-100 transition-opacity"
          aria-label="Stäng notis"
        >
          ✕
        </button>
      )}
    </div>
  )
}
