// src/features/messages/ui/messages-nav-button.jsx
//
// Small nav button that goes to /?page=messages with a live unread badge.
// Drop-in for student-home + instructor-schedule-list headers.

const MessagesNavButton = () => {
  const auth = window.useAuth ? window.useAuth() : { user: null };
  const [unread, setUnread] = React.useState(0);

  const refresh = React.useCallback(async () => {
    if (!auth.user?.id) { setUnread(0); return; }
    try { setUnread(await window.Messages.db.totalUnread(auth.user.id)); }
    catch (e) { /* swallow — the nav badge isn't worth a console spam */ }
  }, [auth.user?.id]);

  React.useEffect(() => {
    if (!auth.user?.id) return;
    refresh();
    const sub = window.Messages.db.subscribeToInbox(() => refresh());
    return () => sub.unsubscribe();
  }, [auth.user?.id, refresh]);

  const goToMessages = () => {
    // Client-side route when the app router handle is up — avoids a full page
    // reload (which re-downloads + re-parses the whole CDN-Babel app and
    // re-fetches the dashboard before Messages even mounts). The hard-nav
    // fallback keeps the button working if the global isn't ready yet.
    if (window.MASTERY && typeof window.MASTERY.navigate === 'function') {
      window.MASTERY.navigate('messages');
      return;
    }
    const sp = new URLSearchParams(location.search);
    sp.set('page', 'messages');
    window.location.search = sp.toString();
  };

  // Warm the inbox cache the moment the user signals intent (hover / focus /
  // touch) so the conversation list paints instantly on click.
  const prefetch = () => {
    if (auth.user?.id) window.Messages.db.prefetchConversations?.(auth.user.id);
  };

  if (!auth.user) return null;

  return (
    <button onClick={goToMessages}
      onMouseEnter={prefetch} onFocus={prefetch} onTouchStart={prefetch}
      title="Messages"
      style={{ position:'relative', background:'none', border:'none', cursor:'pointer',
               fontSize:13, color:'oklch(40% 0.04 265)', padding:'4px 8px',
               fontFamily:"'Plus Jakarta Sans', sans-serif", fontWeight:600,
               display:'inline-flex', alignItems:'center', gap:4 }}>
      Messages
      {unread > 0 && (
        <span style={{ marginLeft:2, minWidth:18, height:18, padding:'0 5px',
                        borderRadius:9, background:'oklch(56% 0.18 25)',
                        color:'#fff', fontSize:10, fontWeight:700,
                        display:'inline-flex', alignItems:'center', justifyContent:'center' }}>
          {unread > 99 ? '99+' : unread}
        </span>
      )}
    </button>
  );
};

window.Messages.ui.MessagesNavButton = MessagesNavButton;
window.MessagesNavButton             = MessagesNavButton;
