"use client";

import { useEffect, useState } from "react";

const STORAGE_KEY = "sohbetegir-announcement-dismissed";

export function AnnouncementBar({ text }: { text: string }) {
  const [dismissed, setDismissed] = useState(true);

  useEffect(() => {
    // localStorage okuması bir mikrogörev içine alınıyor — dış sistemden okunan değeri
    // bir callback'te set etmek için (bkz. react-hooks/set-state-in-effect kuralı).
    Promise.resolve().then(() => {
      try {
        setDismissed(localStorage.getItem(STORAGE_KEY) === text);
      } catch {
        setDismissed(false);
      }
    });
  }, [text]);

  function close() {
    setDismissed(true);
    try {
      localStorage.setItem(STORAGE_KEY, text);
    } catch {
      // localStorage kullanılamıyor olabilir (gizli sekme vb.) — sorun değil, sadece bu oturumda kapanır.
    }
  }

  if (dismissed) return null;

  return (
    <div className="relative flex items-center justify-center gap-3 bg-gradient-to-r from-accent to-accent-2 px-9 py-2.5 text-center text-[12px] font-semibold leading-snug text-white sm:px-10 sm:text-[12.5px]">
      <span className="max-w-[calc(100%-1rem)]">{text}</span>
      <button
        type="button"
        onClick={close}
        className="absolute right-1.5 top-1/2 -translate-y-1/2 rounded-full p-1 text-white/80 hover:bg-white/15 hover:text-white sm:right-3"
        title="Kapat"
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.2} strokeLinecap="round" strokeLinejoin="round">
          <path d="M18 6L6 18M6 6l12 12" />
        </svg>
      </button>
    </div>
  );
}
