/**
 * 通知中心 — 烽火台
 * 数据来源：SSE 实时事件（store.sseEvents）
 * 按 topic7-9 设计：按级别分组、操作按钮、任务链接、全部已读
 * 邮件数据不在此展示（飞鸽传书 Tab 独立展示）
 */

import { useEffect } from 'react';
import { useStore } from '../store';

interface NotifItem {
  id: string;
  type: 'info' | 'warning' | 'success' | 'error';
  title: string;
  message: string;
  time: string;
  read: boolean;
  source: 'mail' | 'event';
  taskId?: string;
  projectId?: string;
}

const LEVEL_ORDER: NotifItem['type'][] = ['error', 'warning', 'success', 'info'];
const TYPE_STYLES: Record<string, { icon: string; color: string; label: string }> = {
  error:   { icon: '🚨', color: '#ff5270', label: '🔴 紧急' },
  warning: { icon: '⚠️', color: '#f5c842', label: '🟡 警告' },
  success: { icon: '✅', color: '#2ecc8a', label: '🟢 完成' },
  info:    { icon: 'ℹ️', color: '#6a9eff', label: '🔵 通知' },
};

export default function NotificationCenter({ onClose }: { onClose: () => void }) {
  const sseEvents = (useStore(s => s.sseEvents) || []) as NotifItem[];
  const unread = sseEvents.filter(n => !n.read).length;

  const grouped = LEVEL_ORDER.map(type => ({
    type,
    label: TYPE_STYLES[type].label,
    items: sseEvents.filter(n => n.type === type),
  })).filter(g => g.items.length > 0);

  const handleMarkRead = (notif: NotifItem) => {
    useStore.setState({
      sseEvents: (useStore.getState().sseEvents as NotifItem[]).map(
        n => n.id === notif.id ? { ...n, read: true } : n
      ),
    });
  };

  const handleMarkAllRead = () => {
    useStore.setState({
      sseEvents: (useStore.getState().sseEvents as NotifItem[]).map(n => ({ ...n, read: true })),
    });
  };

  const handleViewTask = (notif: NotifItem) => {
    if (notif.taskId) {
      useStore.getState().setModalTaskId(notif.taskId);
      if (notif.projectId) useStore.getState().setSelectedProjectId(notif.projectId);
      onClose();
    }
  };

  return (
    <div className="confirm-bg open" onClick={onClose}>
      <div className="confirm-box" style={{ maxWidth: 420, maxHeight: 520 }} onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <span style={{ fontSize: 14, fontWeight: 700 }}>🔔 烽火台</span>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            {unread > 0 && (
              <>
                <span style={{ fontSize: 10, padding: '2px 8px', borderRadius: 10, background: '#ff5270', color: '#fff', fontWeight: 600 }}>{unread}</span>
                <button onClick={handleMarkAllRead} style={{ fontSize: 10, padding: '2px 8px', borderRadius: 6, border: '1px solid var(--line)', background: 'transparent', color: 'var(--muted)', cursor: 'pointer' }}>全部已读</button>
              </>
            )}
            <span style={{ fontSize: 13, color: 'var(--muted)', cursor: 'pointer' }} onClick={onClose}>✕</span>
          </div>
        </div>

        {sseEvents.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <div style={{ fontSize: 28, marginBottom: 8 }}>🔕</div>
            <div style={{ fontSize: 12, color: 'var(--muted)' }}>暂无烽火</div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 400, overflow: 'auto' }}>
            {grouped.map(g => (
              <div key={g.type}>
                <div style={{ fontSize: 11, fontWeight: 600, color: TYPE_STYLES[g.type].color, marginBottom: 4 }}>{g.label} ({g.items.length})</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  {g.items.map(n => {
                    const s = TYPE_STYLES[n.type];
                    return (
                      <div key={n.id} onClick={() => {
                        if (n.taskId) { handleViewTask(n); }
                        else if (!n.read) { handleMarkRead(n); }
                      }} style={{
                        padding: '8px 10px', borderRadius: 8,
                        background: 'var(--panel2)', border: `1px solid ${n.read ? 'var(--line)' : s.color + '44'}`,
                        opacity: n.read ? 0.5 : 1, cursor: 'pointer',
                      }}>
                        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                          <span style={{ fontSize: 12 }}>{s.icon}</span>
                          <span style={{ fontSize: 11, fontWeight: 600, flex: 1 }}>{n.title}</span>
                          {!n.read && <span style={{ width: 6, height: 6, borderRadius: 3, background: s.color, display: 'inline-block' }} />}
                        </div>
                        <div style={{ fontSize: 10, color: 'var(--muted)', marginTop: 2 }}>{n.message}</div>
                        <div style={{ fontSize: 9, color: 'var(--muted)', marginTop: 2, opacity: 0.6 }}>
                          {n.taskId ? '👆 点击查看任务' : !n.read ? '👆 点击标记已读' : ''}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
