import type { TenantEvent } from '../api';

function isTranslatableName(value: unknown): value is Record<string, string> {
  return Boolean(value && typeof value === 'object');
}

export function resolveEventDisplayName(event?: TenantEvent | null): string {
  if (!event) {
    return 'Event';
  }

  const { name, slug } = event;

  if (typeof name === 'string' && name.trim().length > 0) {
    return name;
  }

  if (isTranslatableName(name)) {
    const match = Object.values(name).find(
      (entry) => typeof entry === 'string' && entry.trim().length > 0,
    );
    if (match) {
      return match;
    }
  }

  return slug ?? 'Event';
}

export function formatEventDate(value?: string | null, locale = 'de-DE'): string | null {
  if (!value) {
    return null;
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return null;
  }

  try {
    return new Intl.DateTimeFormat(locale, {
      day: '2-digit',
      month: 'short',
      year: 'numeric',
    }).format(date);
  } catch {
    return date.toISOString().slice(0, 10);
  }
}

export function resolveEngagementMode(event?: TenantEvent | null): 'tasks' | 'photo_only' | null {
  if (!event) {
    return null;
  }

  if (event.engagement_mode) {
    return event.engagement_mode;
  }

  if (event.settings && typeof event.settings === 'object') {
    const mode = event.settings.engagement_mode;
    if (mode === 'tasks' || mode === 'photo_only') {
      return mode;
    }
  }

  return null;
}

export function formatEventStatusLabel(
  status: TenantEvent['status'] | null,
  t: (key: string, options?: Record<string, unknown>) => string,
): string {
  const map: Record<string, { key: string; fallback: string }> = {
    published: { key: 'events.status.published', fallback: 'Veröffentlicht' },
    draft: { key: 'events.status.draft', fallback: 'Entwurf' },
    archived: { key: 'events.status.archived', fallback: 'Archiviert' },
  };

  const target = map[status ?? 'draft'] ?? map.draft;
  return t(target.key, { defaultValue: target.fallback });
}
