/* Permanent notifications bell. Shows for every role. Fetches the unread
   count + full history on load; on open, marks all read (badge -> 0) via
   POST /api/clients/:id/notifications/seen. Items with a ticket_id call
   onOpenTicket(ticketId) and close the panel.

   Props:
     clientId    {string}   — active client id; required.
     onOpenTicket {fn}      — called with ticket id when a linked item is clicked.

   Globals consumed: window.useApi (GET), window.apiSend (POST mutate). */

function NotificationBell({ clientId, onOpenTicket }) {
  const [open, setOpen] = React.useState(false);
  const [version, setVersion] = React.useState(0);
  const { data } = window.useApi(
    clientId ? `/api/clients/${clientId}/notifications` : null,
    [clientId, version]
  );
  const items = (data && data.items) || [];
  const unread = (data && data.unreadCount) || 0;

  const rel = (iso) => {
    const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
    if (s < 60) return 'just now';
    if (s < 3600) return `${Math.floor(s / 60)}m`;
    if (s < 86400) return `${Math.floor(s / 3600)}h`;
    return `${Math.floor(s / 86400)}d`;
  };

  const toggle = () => {
    const next = !open;
    setOpen(next);
    if (next && unread > 0 && clientId) {
      window.apiSend(`/api/clients/${clientId}/notifications/seen`, 'POST', {})
        .then(() => setVersion(v => v + 1))
        .catch(() => {});
    }
  };

  return (
    <div className="notif-wrap">
      <button className="notif-bell" onClick={toggle} aria-label="Notifications">
        <span className="notif-icon">🔔</span>
        {unread > 0 && (
          <span className="notif-badge">{unread > 9 ? '9+' : unread}</span>
        )}
      </button>
      {open && (
        <>
          <div className="notif-scrim" onClick={() => setOpen(false)} />
          <div className="notif-panel">
            <div className="notif-head">Notifications</div>
            <div className="notif-list">
              {items.length === 0
                ? <div className="notif-empty">No notifications yet.</div>
                : items.map(it => (
                  <div
                    key={it.id}
                    className={`notif-item${it.ticket_id ? ' clickable' : ''}`}
                    onClick={() => {
                      if (it.ticket_id && onOpenTicket) {
                        onOpenTicket(it.ticket_id, it.client_id);
                        setOpen(false);
                      }
                    }}
                  >
                    <div className="notif-msg">{it.message}</div>
                    <div className="notif-meta">
                      {it.audience === 'agency' && it.client_id ? `${it.client_id} · ` : ''}{rel(it.created_at)}
                    </div>
                  </div>
                ))
              }
            </div>
          </div>
        </>
      )}
    </div>
  );
}

window.NotificationBell = NotificationBell;
