// ─────────────────────────────────────────────────────────────
// NOTIFICATION BELL — realtime, unread highlight, mark read
// ─────────────────────────────────────────────────────────────
function NotificationBell({ profile, onOpenTask }) {
  const [items, setItems] = React.useState([]);
  const [open, setOpen] = React.useState(false);
  const unread = items.filter(n => !n.read).length;

  const load = React.useCallback(async () => {
    const { data } = await sb.from("notifications").select("*")
      .eq("user_id", profile.id).order("created_at", { ascending: false }).limit(30);
    setItems(data || []);
  }, [profile.id]);

  React.useEffect(() => {
    load();
    const ch = sb.channel("notif-" + profile.id)
      .on("postgres_changes", { event: "INSERT", schema: "public", table: "notifications", filter: "user_id=eq." + profile.id },
        (payload) => setItems(prev => [payload.new, ...prev]))
      .subscribe();
    return () => sb.removeChannel(ch);
  }, [load, profile.id]);

  const markAllRead = async () => {
    await sb.from("notifications").update({ read: true }).eq("user_id", profile.id).eq("read", false);
    setItems(prev => prev.map(n => ({ ...n, read: true })));
  };

  const clickItem = async (n) => {
    if (!n.read) {
      await sb.from("notifications").update({ read: true }).eq("id", n.id);
      setItems(prev => prev.map(x => x.id === n.id ? { ...x, read: true } : x));
    }
    setOpen(false);
    if (n.task_id && onOpenTask) onOpenTask(n.task_id);
  };

  const TYPE_ICON = {
    task_assigned: "◈", task_updated: "✎", status_changed: "⇄",
    deadline_changed: "◷", new_comment: "💬", revision_requested: "↺", task_completed: "✓",
  };

  return (
    <div style={{ position: "relative" }}>
      <button onClick={() => setOpen(!open)} aria-label="Notifications" style={{
        width: 40, height: 40, borderRadius: 10, border: "1px solid var(--border-default)",
        background: "transparent", color: unread ? "var(--gold-400)" : "var(--text-secondary)",
        cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", position: "relative",
      }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><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 && <span style={{
          position: "absolute", top: -5, right: -5, minWidth: 18, height: 18, borderRadius: 99,
          background: "var(--gold-500)", color: "#08080A", fontSize: 10, fontWeight: 800,
          display: "flex", alignItems: "center", justifyContent: "center", padding: "0 4px",
        }}>{unread > 9 ? "9+" : unread}</span>}
      </button>

      {open && (
        <React.Fragment>
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 400 }} />
          <div style={{
            position: "absolute", right: 0, top: 48, width: 360, maxHeight: 460, overflowY: "auto",
            background: "var(--surface-raised)", border: "1px solid var(--border-default)",
            borderRadius: 16, zIndex: 401, boxShadow: "0 16px 48px rgba(0,0,0,0.5)",
          }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 18px", borderBottom: "1px solid var(--border-subtle)" }}>
              <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15 }}>Notifications</span>
              {unread > 0 && <button onClick={markAllRead} style={{ background: "none", border: "none", color: "var(--gold-400)", fontSize: 12, fontWeight: 700, cursor: "pointer" }}>Mark all read</button>}
            </div>
            {items.length === 0
              ? <div style={{ padding: "36px 20px", textAlign: "center", fontSize: 13, color: "var(--text-tertiary)" }}>No notifications yet.</div>
              : items.map(n => (
                <div key={n.id} onClick={() => clickItem(n)} style={{
                  display: "flex", gap: 12, padding: "14px 18px", cursor: "pointer",
                  background: n.read ? "transparent" : "rgba(251,208,40,0.05)",
                  borderBottom: "1px solid var(--border-subtle)", transition: "background .15s",
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = "rgba(255,255,255,0.03)"}
                onMouseLeave={(e) => e.currentTarget.style.background = n.read ? "transparent" : "rgba(251,208,40,0.05)"}>
                  <span style={{ fontSize: 16, color: "var(--gold-400)", flexShrink: 0 }}>{TYPE_ICON[n.type] || "•"}</span>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: n.read ? 500 : 700, color: n.read ? "var(--text-secondary)" : "var(--text-primary)", lineHeight: 1.45 }}>{n.title}</div>
                    {n.body && <div style={{ fontSize: 12, color: "var(--text-tertiary)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{n.body}</div>}
                    <div style={{ fontSize: 11, color: "var(--text-tertiary)", marginTop: 4 }}>{window.PORTAL.timeAgo(n.created_at)}</div>
                  </div>
                  {!n.read && <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--gold-500)", marginLeft: "auto", flexShrink: 0, marginTop: 4 }} />}
                </div>
              ))}
          </div>
        </React.Fragment>
      )}
    </div>
  );
}
window.NotificationBell = NotificationBell;
