import React, { useState, useEffect } from 'react';
import styles from './styles.module.css';

const STORAGE_PREFIX = 'announcement_closed_';

export default function AnnouncementBanner() {
  const [announcement, setAnnouncement] = useState(null);
  const [closed, setClosed] = useState(false);

  useEffect(() => {
    fetch('/announcement.json')
      .then((res) => res.json())
      .then((data) => {
        if (!data || !data.id || !data.text) return;
        const wasClosed = localStorage.getItem(STORAGE_PREFIX + data.id);
        if (wasClosed) return;
        setAnnouncement(data);
      })
      .catch(() => {});
  }, []);

  function handleClose() {
    if (announcement) {
      localStorage.setItem(STORAGE_PREFIX + announcement.id, 'true');
    }
    setClosed(true);
  }

  if (!announcement || closed) return null;

  return (
    <div className={styles.banner}>
      <div className={styles.content}>
        <span className={styles.text}>{announcement.text}</span>
        {announcement.link && announcement.linkText && (
          <a href={announcement.link} className={styles.link} target="_blank" rel="noopener noreferrer">
            {announcement.linkText}
          </a>
        )}
      </div>
      <button className={styles.closeBtn} onClick={handleClose} aria-label="关闭公告">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <line x1="18" y1="6" x2="6" y2="18" />
          <line x1="6" y1="6" x2="18" y2="18" />
        </svg>
      </button>
    </div>
  );
}
