// Notifications screen — expanded feed of event, social, system and quiz alerts

const NOTIFICATIONS = [
  {
    id: 'n1', kind: 'event-starting', time: 'agora',
    title: 'Workshop de Portfólio começa em 10 min',
    body: 'Sala B204 · Pedro Hanazaki apresenta. Você confirmou presença.',
    accent: 'amber', actionLabel: 'Ver sala',
    eventId: 'e2', unread: true,
  },
  {
    id: 'n2', kind: 'quiz', time: '2 min',
    title: 'Quiz do Dia está ao vivo',
    body: 'Entre agora e dispute uma mentoria 1:1 com ex-aluno. Encerra em 47s.',
    accent: 'amber', actionLabel: 'Jogar',
    unread: true,
  },
  {
    id: 'n3', kind: 'dm', time: '14 min',
    title: 'Marina Castro te mandou mensagem',
    body: '"cê vai no workshop de portfólio amanhã?"',
    user: { name: 'Marina Castro', avatar: 'MC', color: '#F5A623' },
    actionLabel: 'Responder',
    threadId: 'dm1', unread: true,
  },
  {
    id: 'n4', kind: 'room', time: '22 min',
    title: '5 novas mensagens na sala "Abertura — De onde vim, pra onde vou"',
    body: 'Luna Ferraz, Thiago Nunes e Beatriz Lima estão conversando.',
    accent: 'blue', actionLabel: 'Abrir sala',
    eventId: 'e1', unread: true,
  },
  {
    id: 'n5', kind: 'like', time: '1 h',
    title: 'Júlia Arruda e mais 12 curtiram seu post',
    body: '"primeiro dia de Forma Tour, e já valeu"',
    user: { name: 'Júlia Arruda', avatar: 'JA', color: '#E0457B' },
    unread: false,
  },
  {
    id: 'n7', kind: 'event-reminder', time: '3 h',
    title: 'Amanhã: Tour pelo Campus',
    body: 'Ponto de encontro: recepção principal, 14:00. Leve água.',
    accent: 'green', actionLabel: 'Ver detalhes',
    eventId: 'e10', unread: false,
  },
  {
    id: 'n8', kind: 'mention', time: '5 h',
    title: 'Você foi mencionado na sala "Keynote: Três empresas em 4 anos"',
    body: 'Pedro Hanazaki: "@aluno concorda com o ponto da Luna sobre o primeiro fracasso?"',
    user: { name: 'Pedro Hanazaki', avatar: 'PH', color: '#3A56B0' },
    actionLabel: 'Ir para a mensagem',
    eventId: 'e8', unread: false,
  },
  {
    id: 'n9', kind: 'quiz-result', time: 'ontem',
    title: 'Resultado: Quiz das Profissões',
    body: 'Você venceu! Retire seu livro "Do Sonho ao Plano" no balcão principal.',
    accent: 'amber', actionLabel: 'Ver placar',
    unread: false,
  },
  {
    id: 'n10', kind: 'system', time: 'seg',
    title: 'Bem-vindo ao Forma Tour',
    body: 'Ative notificações para não perder as talks que você marcou.',
    unread: false,
  },
];

const NotificationsScreen = ({ onBack, onOpenEvent, onOpenThread, onOpenQuiz }) => {
  const [items, setItems] = React.useState(NOTIFICATIONS);
  const [filter, setFilter] = React.useState('all');

  const filters = [
    { id: 'all', label: 'Todas' },
    { id: 'event', label: 'Eventos', kinds: ['event-starting', 'event-reminder', 'room', 'mention'] },
    { id: 'social', label: 'Social', kinds: ['dm', 'like'] },
    { id: 'quiz', label: 'Quiz', kinds: ['quiz', 'quiz-result'] },
  ];
  const active = filters.find(f => f.id === filter);
  const list = filter === 'all' ? items : items.filter(n => active.kinds.includes(n.kind));
  const unreadCount = items.filter(i => i.unread).length;

  const markAllRead = () => setItems(items.map(i => ({ ...i, unread: false })));

  const handleClick = (n) => {
    setItems(items.map(i => i.id === n.id ? { ...i, unread: false } : i));
    if (n.eventId) onOpenEvent(n.eventId);
    else if (n.threadId) onOpenThread(n.threadId);
    else if (n.kind === 'quiz') onOpenQuiz();
  };

  return (
    <div className="screen">
      <StatusBar />
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '8px 20px 14px',
      }}>
        <button className="btn btn-nav" onClick={onBack}><IconChevronLeft size={20} /></button>
        <div style={{ fontSize: 16, fontWeight: 600 }}>Notificações</div>
        <button onClick={markAllRead} style={{
          background: 'none', border: 'none', color: 'var(--amber)',
          font: 'inherit', fontSize: 12, fontWeight: 500, cursor: 'pointer',
          padding: 8,
        }}>Ler tudo</button>
      </div>

      <div style={{ padding: '0 20px 6px' }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', color: 'var(--text-mute)', marginBottom: 6 }}>
          {unreadCount > 0 ? `${unreadCount} NÃO LIDAS` : 'TUDO EM DIA'}
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6, padding: '10px 20px 14px', overflowX: 'auto', scrollbarWidth: 'none' }}>
        {filters.map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            padding: '7px 14px', cursor: 'pointer', font: 'inherit', flexShrink: 0,
            background: filter === f.id ? 'rgba(255,255,255,0.08)' : 'transparent',
            border: `1px solid ${filter === f.id ? 'var(--line-strong)' : 'var(--line)'}`,
            color: filter === f.id ? '#fff' : 'var(--text-dim)',
            borderRadius: 999, fontSize: 12, fontWeight: 500,
          }}>{f.label}</button>
        ))}
      </div>

      <div style={{ paddingBottom: 32 }}>
        {list.map(n => <NotificationRow key={n.id} n={n} onClick={() => handleClick(n)} />)}
        {list.length === 0 && (
          <div style={{ padding: '40px 32px', textAlign: 'center', color: 'var(--text-mute)', fontSize: 13 }}>
            Nada por aqui.
          </div>
        )}
      </div>
    </div>
  );
};

const NotificationRow = ({ n, onClick }) => {
  const kindIcon = {
    'event-starting': { Icon: IconClock, bg: 'rgba(245,166,35,0.14)', color: 'var(--amber)' },
    'event-reminder': { Icon: IconCalendar, bg: 'rgba(74,222,128,0.12)', color: '#4ADE80' },
    'quiz': { Icon: null, emoji: '🏆', bg: 'rgba(245,166,35,0.14)', color: 'var(--amber)' },
    'quiz-result': { Icon: null, emoji: '🥇', bg: 'rgba(245,166,35,0.14)', color: 'var(--amber)' },
    'room': { Icon: IconMessage, bg: 'rgba(58,86,176,0.2)', color: '#8EAAFF' },
    'mention': { Icon: IconMessage, bg: 'rgba(224,69,123,0.2)', color: '#E0457B' },
    'system': { Icon: IconBell, bg: 'rgba(255,255,255,0.05)', color: 'var(--text-dim)' },
  };

  const useUserAvatar = ['dm', 'like'].includes(n.kind);
  const cfg = kindIcon[n.kind];

  return (
    <button onClick={onClick} style={{
      width: '100%', padding: '14px 20px', textAlign: 'left', color: '#fff',
      background: n.unread ? 'rgba(245,166,35,0.04)' : 'transparent',
      border: 'none', borderBottom: '1px solid var(--line)',
      cursor: 'pointer', font: 'inherit',
      display: 'flex', gap: 12, alignItems: 'flex-start', position: 'relative',
    }}>
      {n.unread && <span style={{
        position: 'absolute', left: 8, top: 22,
        width: 6, height: 6, borderRadius: '50%', background: 'var(--amber)',
      }} />}
      {useUserAvatar && n.user ? (
        <Avatar user={n.user} size={40} />
      ) : cfg ? (
        <div style={{
          width: 40, height: 40, borderRadius: 12, flexShrink: 0,
          background: cfg.bg, color: cfg.color,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: cfg.emoji ? 20 : 16,
        }}>
          {cfg.emoji || (cfg.Icon && <cfg.Icon size={18} stroke={1.8} />)}
        </div>
      ) : null}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, marginBottom: 2 }}>
          <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.35, flex: 1 }}>{n.title}</div>
          <span className="mono" style={{ fontSize: 10, color: 'var(--text-mute)', flexShrink: 0, marginTop: 2 }}>
            {n.time}
          </span>
        </div>
        <div style={{ fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.45, marginBottom: n.actionLabel ? 8 : 0 }}>
          {n.body}
        </div>
        {n.actionLabel && (
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            fontSize: 11, fontWeight: 600, color: 'var(--amber)',
            padding: '4px 10px', borderRadius: 999,
            background: 'rgba(245,166,35,0.1)',
            border: '1px solid rgba(245,166,35,0.2)',
          }}>{n.actionLabel} <IconArrowRight size={11} stroke={2} /></span>
        )}
      </div>
    </button>
  );
};

Object.assign(window, { NOTIFICATIONS, NotificationsScreen });
