// notifications.jsx — header "bell" + dropdown listing recent CLIENT review
// comments across ALL of the signed-in owner's shot lists. Loaded on every page
// (after auth.jsx) so it works site-wide. Self-gates: renders nothing when
// signed out. Data + read-state come from review_owner_notifications /
// review_mark_notifications_seen (see shot-list/MIGRATION_REVIEW_3.sql).
//
// Wrapped in an IIFE; exposes window.NotificationBell for the shared Headers.
(function () {
  const { useState, useEffect, useRef } = React;

  function NBIconBell(props) {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"
           strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...props}>
        <path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" />
        <path d="M13.73 21a2 2 0 0 1-3.46 0" />
      </svg>
    );
  }

  function agoShort(ms) {
    const s = Math.max(0, Math.floor(ms / 1000));
    if (s < 60) return 'now';
    const m = Math.floor(s / 60); if (m < 60) return m + 'm';
    const h = Math.floor(m / 60); if (h < 24) return h + 'h';
    const d = Math.floor(h / 24); if (d < 7) return d + 'd';
    return Math.floor(d / 7) + 'w';
  }

  function NotificationBell() {
    const sb = window.supabaseClient || null;
    const [user, setUser] = useState(null);
    const [items, setItems] = useState([]);
    const [open, setOpen] = useState(false);
    const [loading, setLoading] = useState(false);
    const ref = useRef(null);

    // Track auth so the bell only exists for signed-in owners.
    useEffect(() => {
      if (!sb) return;
      sb.auth.getUser().then(({ data }) => setUser(data && data.user ? data.user : null)).catch(() => {});
      const { data: sub } = sb.auth.onAuthStateChange((_e, session) => setUser(session && session.user ? session.user : null));
      return () => { try { sub.subscription.unsubscribe(); } catch (e) {} };
    }, []);

    const load = async () => {
      if (!sb || !user) return;
      setLoading(true);
      try {
        const { data, error } = await sb.rpc('review_owner_notifications', { p_limit: 30 });
        if (!error) setItems(data || []);
      } catch (e) {}
      setLoading(false);
    };

    // Load on sign-in, poll while signed in, and refresh on tab refocus.
    useEffect(() => {
      if (!user) { setItems([]); return; }
      load();
      const t = setInterval(load, 60000);
      const onFocus = () => load();
      window.addEventListener('focus', onFocus);
      return () => { clearInterval(t); window.removeEventListener('focus', onFocus); };
    }, [user && user.id]);

    // Close the dropdown on outside click.
    useEffect(() => {
      const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
      document.addEventListener('mousedown', onDoc);
      return () => document.removeEventListener('mousedown', onDoc);
    }, []);

    if (!sb || !user) return null;

    const unread = items.reduce((n, i) => n + (i.is_unread ? 1 : 0), 0);

    const markSeen = async () => {
      try { await sb.rpc('review_mark_notifications_seen'); } catch (e) {}
      setItems((prev) => prev.map((i) => ({ ...i, is_unread: false })));
    };
    const goTo = (it) => {
      markSeen();
      window.location.href = '/shot-list/?id=' + encodeURIComponent(it.shot_list_id) +
        '&csShot=' + encodeURIComponent(it.shot_id);
    };

    return (
      <div className="notif-wrap" ref={ref}>
        <button
          className="icon-btn notif-btn"
          title="Comment notifications"
          aria-label="Comment notifications"
          onClick={() => { const willOpen = !open; setOpen(willOpen); if (willOpen) load(); }}
        >
          <NBIconBell />
          {unread > 0 && <span className="notif-dot">{unread > 9 ? '9+' : unread}</span>}
        </button>

        {open && (
          <div className="notif-menu">
            <div className="notif-head">
              <span>Comments</span>
              {unread > 0 && <button className="notif-markread" onClick={markSeen}>Mark all read</button>}
            </div>
            <div className="notif-list">
              {items.length === 0 && (
                <div className="notif-empty">{loading ? 'Loading…' : 'No client comments yet.'}</div>
              )}
              {items.map((it) => (
                <button
                  key={it.comment_id}
                  className={`notif-item ${it.is_unread ? 'unread' : ''}`}
                  onClick={() => goTo(it)}
                >
                  <span className="notif-item-dot" />
                  <span className="notif-item-main">
                    <span className="notif-item-top">
                      <strong>{it.author_name || 'Someone'}</strong>
                      <span className="notif-item-time">{agoShort(Date.now() - new Date(it.created_at).getTime())}</span>
                    </span>
                    <span className="notif-item-text">{it.is_reply ? '↳ ' : ''}{it.body}</span>
                    <span className="notif-item-ctx">
                      {it.shot_list_title || 'Shot list'}{it.resolved ? ' · resolved' : ''}
                      <span className="notif-item-open">Open ›</span>
                    </span>
                  </span>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  }

  window.NotificationBell = NotificationBell;
})();
