"use client";

import { useState, useEffect } from "react";
import Link from "next/link";

interface AnnouncementBarProps {
  text: string;
  bgColor: string;
  textColor: string;
  linkUrl?: string;
  dismissible?: boolean;
}

export default function AnnouncementBar({
  text,
  bgColor,
  textColor,
  linkUrl,
  dismissible = true,
}: AnnouncementBarProps) {
  const [visible, setVisible] = useState(true);

  // Check if user already dismissed this exact message
  useEffect(() => {
    const dismissed = localStorage.getItem("sellzaki_announcement");
    if (dismissed === text) setVisible(false);
  }, [text]);

  const dismiss = () => {
    localStorage.setItem("sellzaki_announcement", text);
    setVisible(false);
  };

  if (!visible) return null;

  const content = (
    <span className="text-xs sm:text-sm font-medium tracking-wide">{text}</span>
  );

  return (
    <div
      className="relative flex items-center justify-center px-10 py-2.5 text-center"
      style={{ backgroundColor: bgColor, color: textColor }}
    >
      {linkUrl ? (
        <Link href={linkUrl} className="hover:opacity-80 transition-opacity">
          {content}
        </Link>
      ) : (
        content
      )}

      {dismissible && (
        <button
          onClick={dismiss}
          className="absolute right-3 top-1/2 -translate-y-1/2 w-7 h-7 flex items-center justify-center rounded-full opacity-60 hover:opacity-100 hover:bg-black/10 transition-all"
          aria-label="Dismiss"
        >
          <svg
            className="h-3.5 w-3.5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2.5}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </button>
      )}
    </div>
  );
}
