// 通知中心组件
function NotificationCenter({ onClose }) {
  const { state, dispatch } = useStore();
  const [loading, setLoading] = React.useState(true);
  const [notifications, setNotifications] = React.useState([]);
  const [unreadCount, setUnreadCount] = React.useState(0);

  // 加载通知
  const loadNotifications = React.useCallback(async () => {
    if (!state.token) return;
    try {
      const resp = await fetch('/api/notifications', {
        headers: { Authorization: `Bearer ${state.token}` }
      });
      const data = await resp.json();
      if (data.success) {
        setNotifications(data.data.notifications || []);
        setUnreadCount(data.data.unreadCount || 0);
      }
    } catch (e) {
      console.error('加载通知失败:', e);
    } finally {
      setLoading(false);
    }
  }, [state.token]);

  React.useEffect(() => {
    loadNotifications();
  }, [loadNotifications]);

  // 标记为已读
  const markAsRead = async (id) => {
    try {
      const resp = await fetch(`/api/notifications/${id}/read`, {
        method: 'PUT',
        headers: { Authorization: `Bearer ${state.token}` }
      });
      const data = await resp.json();
      if (data.success) {
        setNotifications(prev => prev.map(n => n.id === id ? { ...n, read: true } : n));
        setUnreadCount(data.data.unreadCount);
      }
    } catch (e) {
      console.error('标记已读失败:', e);
    }
  };

  // 全部标为已读
  const markAllAsRead = async () => {
    try {
      const resp = await fetch('/api/notifications/mark-all-read', {
        method: 'POST',
        headers: { Authorization: `Bearer ${state.token}` }
      });
      const data = await resp.json();
      if (data.success) {
        setNotifications(prev => prev.map(n => ({ ...n, read: true })));
        setUnreadCount(0);
      }
    } catch (e) {
      console.error('标记全部已读失败:', e);
    }
  };

  // 删除通知
  const deleteNotification = async (id) => {
    try {
      const resp = await fetch(`/api/notifications/${id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${state.token}` }
      });
      const data = await resp.json();
      if (data.success) {
        setNotifications(prev => prev.filter(n => n.id !== id));
        setUnreadCount(data.data.unreadCount);
      }
    } catch (e) {
      console.error('删除通知失败:', e);
    }
  };

  // 图标映射
  const getTypeIcon = (type) => {
    switch (type) {
      case 'achievement': return '🏆';
      case 'exam': return '📝';
      case 'suggestion': return '💡';
      case 'system': return '📢';
      default: return '📌';
    }
  };

  return (
    <Modal open={true} onClose={onClose} title="通知中心">
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 14, color: 'var(--ink-3)' }}>
          {unreadCount > 0 ? `你有 ${unreadCount} 条未读通知` : '暂无新通知'}
        </span>
        {unreadCount > 0 && (
          <Button variant="soft" size="sm" onClick={markAllAsRead}>全部标为已读</Button>
        )}
      </div>

      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px 0', color: 'var(--ink-3)' }}>加载中...</div>
      ) : notifications.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '40px 0', color: 'var(--ink-3)' }}>
          <div style={{ fontSize: 48, marginBottom: 12 }}>📭</div>
          <div>暂无通知</div>
        </div>
      ) : (
        <div style={{ maxHeight: 400, overflowY: 'auto' }}>
          {notifications.map(n => (
            <div
              key={n.id}
              style={{
                padding: 12,
                borderBottom: '1px solid var(--line)',
                display: 'flex',
                gap: 12,
                backgroundColor: !n.read ? 'var(--blue-5)' : 'transparent',
                borderRadius: 8,
                marginBottom: 8
              }}
            >
              <div style={{ fontSize: 24 }}>{getTypeIcon(n.type)}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, marginBottom: 4, fontSize: 14 }}>{n.title}</div>
                <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>{n.content}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 6 }}>
                  {new Date(n.created_at).toLocaleString()}
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {!n.read && (
                  <div
                    style={{
                      fontSize: 12,
                      color: 'var(--blue-6)',
                      cursor: 'pointer',
                      fontWeight: 600
                    }}
                    onClick={() => markAsRead(n.id)}
                  >
                    标为已读
                  </div>
                )}
                <div
                  style={{
                    fontSize: 12,
                    color: 'var(--coral)',
                    cursor: 'pointer'
                  }}
                  onClick={() => deleteNotification(n.id)}
                >
                  删除
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </Modal>
  );
}

Object.assign(window, { NotificationCenter });
