// @design-system: notification/NotificationBell
/**
 * NotificationBell — top-bar bell button with unread count badge.
 *
 * Opens a Popover containing NotificationList.
 * Accepts an initial `unreadCount` from SSR; updates live via react-query.
 * Optionally shows a LiveBadge for WebSocket connection state.
 *
 * @wave 2c - UI components
 */
import { useState, useCallback } from 'react';
import { useT } from '@/lib/i18n/react';
import { Icon } from '@/components/ui/icons/Icon';
import { Badge } from '@/components/ui/primitives/Badge';
import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/overlays/Popover';
import { NotificationList } from './NotificationList';
import { LiveBadge } from './LiveBadge';

export interface NotificationBellProps {
  /**
   * Server-rendered initial unread count. Updated live by NotificationList
   * once hydrated.
   */
  unreadCount?: number;
  /**
   * Whether the WebSocket is currently connected.
   * Pass `undefined` to hide the LiveBadge entirely.
   * Wave 7: wired from useLiveNotifications() via HydratedIsland.
   */
  connected?: boolean;
  /** When set (admin shell), footer links to the full admin notifications inbox. */
  inboxHref?: string;
}

function BellInner({ unreadCount: initialCount = 0, connected, inboxHref }: NotificationBellProps) {
  const t = useT('notif');
  const [count, setCount] = useState(initialCount);

  const handleUnreadChange = useCallback((n: number) => setCount(n), []);

  const displayCount = count > 99 ? '99+' : count > 0 ? String(count) : null;

  return (
    <Popover>
      <PopoverTrigger asChild>
        <button
          type="button"
          aria-label={t('bell_aria')}
          aria-haspopup="dialog"
          className={[
            'relative inline-flex items-center justify-center',
            'size-10 rounded-full',
            'text-text-secondary hover:bg-surface-raised hover:text-text-primary',
            'transition-colors',
            'focus-visible:ring-brand-primary-500 focus-visible:ring-2 focus-visible:outline-none',
          ].join(' ')}
        >
          <Icon name="Bell" size="md" />

          {/* Unread count badge */}
          {displayCount !== null && (
            <Badge
              tone="brand"
              size="sm"
              aria-label={`${displayCount} ${t('bell_aria')}`}
              className="absolute -end-1 -top-1 min-w-[1.25rem] px-1 py-0"
            >
              {displayCount}
            </Badge>
          )}

          {/* Pulse dot when unread > 0 and no numeric badge */}
          {count > 0 && displayCount === null && (
            <span
              aria-hidden
              className="bg-brand-primary-500 absolute end-1.5 top-1.5 size-2 rounded-full"
            />
          )}
        </button>
      </PopoverTrigger>

      <PopoverContent
        align="end"
        className="w-80 p-0"
        aria-label={t('bell_aria')}
        role="dialog"
        aria-modal="true"
      >
        {/* Header row */}
        <div className="border-border-default flex items-center justify-between border-b px-4 py-3">
          <h2 className="text-text-primary text-sm font-semibold">{t('bell_aria')}</h2>
          {connected !== undefined && <LiveBadge connected={connected} />}
        </div>

        {/* Notification list */}
        <NotificationList onUnreadCountChange={handleUnreadChange} />

        {inboxHref ? (
          <div className="border-border-default border-t px-4 py-3">
            <a
              href={inboxHref}
              className="text-brand-primary-600 hover:text-brand-primary-700 text-sm font-medium hover:underline"
            >
              {t('bell_view_inbox')}
            </a>
          </div>
        ) : null}
      </PopoverContent>
    </Popover>
  );
}

/**
 * NotificationBell — must be rendered inside a HydratedIsland (shares its QueryClient).
 * Use directly inside SiteNav or VendorTopbar — both are inside HydratedIsland.
 */
export function NotificationBell(props: NotificationBellProps) {
  return <BellInner {...props} />;
}
