const { useState: useSt, useEffect: useEff, useRef, useContext: useCtx } = React;

const NOTIF_ICONS = {
  live_new:      '📡',
  live_1day:     '📅',
  live_3h:       '🔴',
  recording:     '📹',
  comment_reply: '💬',
};

const tAgo = (d) => {
  const diff = Date.now() - new Date(d).getTime();
  const m = Math.floor(diff / 60000);
  if (m < 1)  return 'agora';
  if (m < 60) return `${m}min atrás`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h atrás`;
  return `${Math.floor(h / 24)}d atrás`;
};

/* ── NotificationBell ────────────────────────────────────────────── */
const NotificationBell = () => {
  const { user } = useCtx(UserCtx);
  const [notifs, setNotifs] = useSt([]);
  const [open,   setOpen]   = useSt(false);
  const wrapRef = useRef(null);

  /* Carrega notificações do banco */
  const load = async () => {
    if (!user?.id) return;
    const { data } = await _supabase
      .from('notifications')
      .select('*')
      .eq('user_id', user.id)
      .order('created_at', { ascending: false })
      .limit(30);
    setNotifs(data || []);
  };

  /* Cria notificação se ainda não existe (unique constraint evita duplicatas) */
  const push = async (type, refId, title, body) => {
    if (!user?.id) return;
    await _supabase.from('notifications').upsert(
      { user_id: user.id, type, ref_id: refId, title, body },
      { onConflict: 'user_id,type,ref_id', ignoreDuplicates: true }
    );
  };

  /* Verifica e cria todas as notificações pertinentes */
  const check = async () => {
    if (!user?.id) return;
    const now = new Date();

    /* ── Aulas ao vivo ── */
    for (const ev of LIVE_EVENTS) {
      if (ev.status === 'upcoming' || ev.status === 'live') {
        /* Nova live adicionada */
        await push('live_new', ev.id,
          '📡 Nova aula ao vivo agendada',
          `"${ev.title}" — ${ev.date} às ${ev.time}h`
        );

        const evTime = new Date(`${ev.date}T${ev.time}:00`);
        const hLeft  = (evTime - now) / 3600000;

        /* Falta 1 dia */
        if (hLeft > 0 && hLeft <= 24) {
          await push('live_1day', ev.id,
            '📅 Aula ao vivo amanhã!',
            `"${ev.title}" está chegando. Reserve seu horário!`
          );
        }
        /* Falta 3 horas */
        if (hLeft > 0 && hLeft <= 3) {
          await push('live_3h', ev.id,
            '🔴 Aula ao vivo em menos de 3h!',
            `"${ev.title}" começa em breve. Não perca!`
          );
        }
      }

      /* Gravação disponível */
      if (ev.status === 'recorded') {
        await push('recording', ev.id,
          '📹 Gravação disponível!',
          `A gravação de "${ev.title}" já está no módulo Ao Vivo.`
        );
      }
    }

    /* ── Respostas em comentários ── */
    const { data: myComments } = await _supabase
      .from('comments')
      .select('id')
      .eq('user_id', user.id);

    if (myComments?.length) {
      const ids = myComments.map(c => c.id);
      const { data: replies } = await _supabase
        .from('comments')
        .select('id, user_name, content')
        .in('parent_id', ids)
        .neq('user_id', user.id);

      for (const r of (replies || [])) {
        await push('comment_reply', r.id,
          `💬 ${r.user_name} respondeu seu comentário`,
          r.content.slice(0, 100) + (r.content.length > 100 ? '…' : '')
        );
      }
    }

    load();
  };

  useEff(() => {
    if (user?.id) { load(); check(); }
  }, [user?.id]);

  /* Fecha ao clicar fora */
  useEff(() => {
    if (!open) return;
    const fn = e => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', fn);
    return () => document.removeEventListener('mousedown', fn);
  }, [open]);

  const unread = notifs.filter(n => !n.read).length;

  const markAllRead = async () => {
    const ids = notifs.filter(n => !n.read).map(n => n.id);
    if (!ids.length) return;
    await _supabase.from('notifications').update({ read: true }).in('id', ids);
    setNotifs(prev => prev.map(n => ({ ...n, read: true })));
  };

  const handleOpen = () => {
    setOpen(o => !o);
    if (!open && unread > 0) setTimeout(markAllRead, 2500);
  };

  if (!user) return null;

  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      {/* ── Botão sininho ── */}
      <button
        onClick={handleOpen}
        title="Notificações"
        style={{
          width: 34, height: 34, borderRadius: '50%', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: open ? 'var(--gold-bg)' : 'none',
          border: `1px solid ${open ? 'var(--border-h)' : 'var(--border)'}`,
          color: open ? 'var(--gold)' : 'var(--text2)',
          position: 'relative', transition: 'all 0.15s',
        }}
      >
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
          strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/>
          <path d="M13.73 21a2 2 0 0 1-3.46 0"/>
        </svg>
        {unread > 0 && (
          <div style={{
            position: 'absolute', top: -3, right: -3,
            minWidth: 16, height: 16, borderRadius: 20, padding: '0 4px',
            background: '#dc2626', border: '2px solid var(--bg)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 9, fontWeight: 800, color: '#fff', boxSizing: 'border-box',
          }}>
            {unread > 9 ? '9+' : unread}
          </div>
        )}
      </button>

      {/* ── Dropdown ── */}
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 8px)', right: 0,
          width: 340, maxHeight: 460, overflowY: 'auto',
          background: 'var(--card)', border: '1px solid var(--border)',
          borderRadius: 12, boxShadow: '0 8px 32px rgba(0,0,0,0.38)',
          zIndex: 300,
        }}>
          {/* Header sticky */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '12px 14px', borderBottom: '1px solid var(--border)',
            position: 'sticky', top: 0, background: 'var(--card)', zIndex: 1,
          }}>
            <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--text)' }}>
              Notificações {unread > 0 && <span style={{ color: 'var(--gold)', fontWeight: 400 }}>({unread} novas)</span>}
            </span>
            {unread > 0 && (
              <button onClick={markAllRead} style={{
                background: 'none', fontSize: 11, color: 'var(--text3)', transition: 'color 0.15s',
              }}
                onMouseEnter={e => e.currentTarget.style.color = 'var(--gold)'}
                onMouseLeave={e => e.currentTarget.style.color = 'var(--text3)'}
              >
                Marcar todas como lidas
              </button>
            )}
          </div>

          {/* Lista */}
          {notifs.length === 0 ? (
            <div style={{ padding: '36px 16px', textAlign: 'center', color: 'var(--text3)', fontSize: 13 }}>
              <div style={{ fontSize: 28, marginBottom: 8 }}>🔔</div>
              Nenhuma notificação ainda
            </div>
          ) : notifs.map(n => (
            <div key={n.id} style={{
              display: 'flex', alignItems: 'flex-start', gap: 10,
              padding: '12px 14px', borderBottom: '1px solid var(--border)',
              background: n.read ? 'none' : 'var(--gold-bg)',
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: '50%', flexShrink: 0,
                background: 'var(--bg)', border: '1px solid var(--border)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16,
              }}>
                {NOTIF_ICONS[n.type] || '🔔'}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <p style={{ fontSize: 12.5, fontWeight: n.read ? 400 : 600, color: 'var(--text)', marginBottom: 3, lineHeight: 1.4 }}>
                  {n.title}
                </p>
                {n.body && (
                  <p style={{
                    fontSize: 11.5, color: 'var(--text2)', lineHeight: 1.5, marginBottom: 4,
                    overflow: 'hidden', display: '-webkit-box',
                    WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
                  }}>
                    {n.body}
                  </p>
                )}
                <p style={{ fontSize: 10.5, color: 'var(--text3)' }}>{tAgo(n.created_at)}</p>
              </div>
              {!n.read && (
                <div style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--gold)', flexShrink: 0, marginTop: 6 }}/>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

window.NotificationBell = NotificationBell;
