"use client";

// Topbar bell → offline-notification control. Click opens a small popover to enable/disable Web Push
// for this browser. The dot is lit when this browser is subscribed. Hidden entirely when push isn't
// available (demo mode, or a browser without ServiceWorker/PushManager).

import { useState } from "react";
import { Icon } from "./ui";
import { usePushNotifications } from "@/lib/push-notifications";

export function NotificationBell() {
  const push = usePushNotifications();
  const [open, setOpen] = useState(false);

  if (!push.supported) return null;

  const denied = push.permission === "denied";

  return (
    <div style={{ position: "relative" }}>
      <button
        className="ic-btn"
        aria-label="Notifications"
        aria-haspopup="menu"
        aria-expanded={open}
        style={{ position: "relative" }}
        onClick={() => setOpen((o) => !o)}
      >
        <Icon name="bell" size={18} />
        <span
          style={{
            position: "absolute",
            top: 9,
            right: 10,
            width: 7,
            height: 7,
            borderRadius: 99,
            background: push.subscribed ? "var(--orange)" : "var(--border)",
            border: "2px solid var(--panel)",
          }}
        />
      </button>
      {open && (
        <>
          <div className="tm-menu-scrim" onClick={() => setOpen(false)} />
          <div className="tm-menu-pop" role="menu" style={{ width: 260, padding: 14 }}>
            <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 4 }}>Offline notifications</div>
            <p style={{ fontSize: 12, color: "var(--muted)", margin: "0 0 12px", lineHeight: 1.4 }}>
              {push.subscribed
                ? "You'll get push notifications for new direct messages and mentions, even when this tab is closed."
                : "Get notified about direct messages and mentions when the CRM isn't open."}
            </p>

            {denied ? (
              <p style={{ fontSize: 12, color: "var(--danger, #c0392b)", margin: 0 }}>
                Notifications are blocked in your browser settings. Allow them for this site, then try again.
              </p>
            ) : push.subscribed ? (
              <button className="ds-btn v-ghost full" disabled={push.busy} onClick={() => push.disable()}>
                {push.busy ? "Turning off…" : "Turn off notifications"}
              </button>
            ) : (
              <button className="ds-btn v-primary full" disabled={push.busy} onClick={() => push.enable()}>
                {push.busy ? "Enabling…" : "Enable notifications"}
              </button>
            )}

            {push.error && <p style={{ fontSize: 11.5, color: "var(--danger, #c0392b)", margin: "10px 0 0" }}>{push.error}</p>}
          </div>
        </>
      )}
    </div>
  );
}
