// page-notifications.jsx — Central de notificações do usuário

const { useState: usN, useEffect: ueN } = React;

const TYPE_ICON  = { info: 'lucide:info', warning: 'lucide:alert-triangle', error: 'lucide:x-circle', promotion: 'lucide:tag', trial: 'lucide:clock', billing: 'lucide:credit-card' };
const TYPE_COLOR = { info: 'var(--accent)', warning: 'var(--warn)', error: 'var(--err)', promotion: 'var(--cyan)', trial: 'var(--warn)', billing: 'var(--pink)' };
const TYPE_LABEL = { info: 'Informação', warning: 'Aviso', error: 'Erro', promotion: 'Promoção', trial: 'Trial', billing: 'Cobrança' };

function PageNotifications({ tenant }) {
  const [notifs, setNotifs] = usN([]);
  const [loading, setLoading] = usN(true);
  const [filter, setFilter] = usN('all');

  const tenantId = tenant?.id;

  ueN(() => {
    if (!tenantId) { setLoading(false); return; }
    SB.getNotifications(tenantId)
      .then(setNotifs)
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [tenantId]);

  async function markRead(n) {
    if (n.is_read) return;
    await SB.markNotificationRead(n.id, tenantId).catch(() => {});
    setNotifs(prev => prev.map(x => x.id === n.id ? { ...x, is_read: true } : x));
  }

  async function markAll() {
    await SB.markAllNotificationsRead(tenantId).catch(() => {});
    setNotifs(prev => prev.map(n => ({ ...n, is_read: true })));
  }

  const filtered = filter === 'all' ? notifs : notifs.filter(n => n.type === filter);
  const unread = notifs.filter(n => !n.is_read).length;

  return (
    <div className="fade-up">
      <div className="page-head">
        <div>
          <h1 className="page-title">Central de notificações</h1>
          <p className="page-sub">{unread > 0 ? `${unread} não lida${unread > 1 ? 's' : ''}` : 'Tudo em dia'}</p>
        </div>
        {unread > 0 && (
          <div className="page-actions">
            <button className="btn" onClick={markAll}>
              <iconify-icon icon="lucide:check-check" />Marcar todas como lidas
            </button>
          </div>
        )}
      </div>

      {/* Filtros */}
      <div className="row gap-sm" style={{ marginBottom: 'var(--gap)', flexWrap: 'wrap' }}>
        {['all', 'info', 'warning', 'error', 'promotion', 'trial', 'billing'].map(t => (
          <button key={t}
            className={'btn btn-sm' + (filter === t ? ' btn-primary' : '')}
            onClick={() => setFilter(t)}>
            {t === 'all' ? 'Todas' : TYPE_LABEL[t]}
          </button>
        ))}
      </div>

      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        {loading
          ? <div style={{ padding: 40, textAlign: 'center' }}>
              <iconify-icon icon="lucide:loader-circle" style={{ animation: 'spin 1s linear infinite', fontSize: 24 }} />
            </div>
          : filtered.length === 0
            ? <div style={{ padding: '48px 24px', textAlign: 'center' }}>
                <iconify-icon icon="lucide:inbox" style={{ fontSize: 40, color: 'var(--text-muted)', display: 'block', marginBottom: 12 }} />
                <div style={{ color: 'var(--text-muted)', fontSize: 14 }}>Nenhuma notificação encontrada</div>
              </div>
            : filtered.map(n => (
                <div key={n.id}
                  onClick={() => markRead(n)}
                  style={{
                    display: 'flex', gap: 14, padding: '14px 20px', cursor: 'pointer',
                    background: n.is_read ? 'transparent' : 'var(--accent-subtle)',
                    borderBottom: '1px solid var(--border-subtle)',
                    transition: 'background 0.15s',
                  }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: '50%', flexShrink: 0,
                    background: 'var(--bg-base)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <iconify-icon
                      icon={TYPE_ICON[n.type] ?? 'lucide:bell'}
                      style={{ color: TYPE_COLOR[n.type] ?? 'var(--accent)', fontSize: 16 }}
                    />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                      <span style={{ fontSize: 13, fontWeight: n.is_read ? 500 : 700 }}>{n.title}</span>
                      <span className="tag" style={{ fontSize: 10 }}>{n.origin === 'admin' ? 'Comunicado' : 'Sistema'}</span>
                      {!n.is_read && (
                        <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', flexShrink: 0 }} />
                      )}
                    </div>
                    {n.body && (
                      <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 6, lineHeight: 1.5 }}>{n.body}</div>
                    )}
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                      <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                        {new Date(n.created_at).toLocaleString('pt-BR', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })}
                      </span>
                      {n.action_url && n.action_label && (
                        <a href={n.action_url} style={{ fontSize: 11, color: 'var(--accent)', fontWeight: 600 }}
                          onClick={e => e.stopPropagation()}>
                          {n.action_label} →
                        </a>
                      )}
                    </div>
                  </div>
                </div>
              ))
        }
      </div>
    </div>
  );
}

Object.assign(window, { PageNotifications });
