import { getAuthRoleLabel } from '@/business/auth/selectors';
import { APP_ROUTE_PATHS } from '@/shared/constants/routes';
import { DEFAULT_CAMPUS_LABEL } from '@/shared/constants/campusDisplay';
import type {
  CampusInfo,
  UserRole,
} from '@/shared/types/app';
import type { TopBarNotification } from '@/business/top-bar/types';
import type { CommunicationEventDto } from '@/shared/types/communications';
import type { PolicyViewModel } from '@/business/policies/types';
import type { SafetyProtocolViewModel } from '@/business/safety-protocols/types';
import type { PolicyAcknowledgmentDto } from '@/shared/types/policyDocuments';
import { isPolicyDocumentAcknowledged } from '@/business/policies/selectors';

export function getTopBarInitials(name: string): string {
  return name
    .trim()
    .split(/\s+/u)
    .filter(Boolean)
    .map((part) => part[0])
    .join('')
    .slice(0, 2)
    .toUpperCase();
}

export function getTopBarCampusLabel(campusInfo?: CampusInfo): string {
  return campusInfo?.fullName ?? DEFAULT_CAMPUS_LABEL;
}

export function getTopBarRoleLabel(role: UserRole): string {
  return getAuthRoleLabel(role);
}

export function countUnreadTopBarNotifications(
  notifications: readonly TopBarNotification[],
): number {
  return notifications.filter((notification) => notification.unread).length;
}

const ZONE_CHECKIN_NOTIFICATION_ID = 'zone-checkin-today';

/**
 * Builds the top-bar notification list from derived app state (there is no
 * backend notifications store yet). Currently surfaces a single nudge when an
 * eligible user has not logged today's Zone.
 */
export function buildTopBarNotifications(input: {
  readonly needsZoneCheckIn: boolean;
  readonly communicationEvents?: readonly CommunicationEventDto[];
  readonly acknowledgedCommunicationEventIds?: ReadonlySet<string>;
  readonly handbookPolicies?: readonly PolicyViewModel[];
  readonly safetyProtocols?: readonly SafetyProtocolViewModel[];
  readonly policyAcknowledgments?: readonly PolicyAcknowledgmentDto[];
}): readonly TopBarNotification[] {
  const notifications: TopBarNotification[] = [];

  if (input.needsZoneCheckIn) {
    notifications.push({
      id: ZONE_CHECKIN_NOTIFICATION_ID,
      text: "You haven't logged your Emotional Zone today",
      time: 'Today',
      unread: true,
      href: APP_ROUTE_PATHS.zones,
    });
  }

  for (const event of input.communicationEvents ?? []) {
    if (input.acknowledgedCommunicationEventIds?.has(event.id)) {
      continue;
    }

    notifications.push({
      id: `internal-alert-${event.id}`,
      text: `Internal alert: ${event.title}`,
      time: new Date(event.date).toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
      }),
      unread: true,
      href: APP_ROUTE_PATHS.internalComm,
    });
  }

  for (const policy of input.handbookPolicies ?? []) {
    if (isPolicyDocumentAcknowledged(input.policyAcknowledgments ?? [], policy.id, policy.version)) {
      continue;
    }

    notifications.push({
      id: `handbook-policy-${policy.id}-v${policy.version}`,
      text: `Unread handbook policy: ${policy.title}`,
      time: `Version ${policy.version}`,
      unread: true,
      href: APP_ROUTE_PATHS.handbook,
    });
  }

  for (const protocol of input.safetyProtocols ?? []) {
    if (isPolicyDocumentAcknowledged(input.policyAcknowledgments ?? [], protocol.id, protocol.version)) {
      continue;
    }

    notifications.push({
      id: `safety-protocol-${protocol.id}-v${protocol.version}`,
      text: `Unread safety protocol: ${protocol.title}`,
      time: `Version ${protocol.version}`,
      unread: true,
      href: APP_ROUTE_PATHS.safety,
    });
  }

  return notifications;
}
