/*
 * 알림 벨 — 미확인 개수 배지 + 목록 드롭다운. 공통 notification 채널(§7-6) 소비.
 */
import { useCallback, useEffect, useState } from 'react';
import { notificationApi, type NotificationDto } from '@/api/common';

export function NotificationBell(): JSX.Element {
  const [unread, setUnread] = useState<number>(0);
  const [open, setOpen] = useState<boolean>(false);
  const [items, setItems] = useState<NotificationDto[]>([]);

  const refreshCount = useCallback(async (): Promise<void> => {
    try {
      const r = await notificationApi.unreadCount();
      setUnread(r.unread);
    } catch {
      /* 무음 실패 — 벨 배지는 비필수 */
    }
  }, []);

  useEffect(() => {
    void refreshCount();
    const t = setInterval(() => void refreshCount(), 60000);
    return () => clearInterval(t);
  }, [refreshCount]);

  const toggle = async (): Promise<void> => {
    const next = !open;
    setOpen(next);
    if (next) {
      try {
        const page = await notificationApi.list(false, 0, 20);
        setItems(page.items);
      } catch {
        setItems([]);
      }
    }
  };

  const markAll = async (): Promise<void> => {
    await notificationApi.readAll();
    setUnread(0);
    setItems((prev) => prev.map((n) => ({ ...n, readAt: n.readAt ?? new Date().toISOString() })));
  };

  return (
    <div className="notification-bell">
      <button type="button" onClick={() => void toggle()} aria-label="알림">
        알림{unread > 0 ? ` (${unread})` : ''}
      </button>
      {open && (
        <div className="notification-dropdown" role="menu">
          <div className="notification-dropdown__head">
            <span>알림</span>
            <button type="button" onClick={() => void markAll()}>
              모두 읽음
            </button>
          </div>
          {items.length === 0 ? (
            <p className="notification-empty">새 알림이 없습니다.</p>
          ) : (
            <ul>
              {items.map((n) => (
                <li key={n.id} className={n.readAt ? 'read' : 'unread'}>
                  <strong>{n.title}</strong>
                  {n.message && <span>{n.message}</span>}
                </li>
              ))}
            </ul>
          )}
        </div>
      )}
    </div>
  );
}
