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

export type BuildInitialTextFieldsParams = {
  customization: Record<string, unknown> | null | undefined;
  layoutDefaults: EventQrInviteLayout | null | undefined;
  eventName?: string | null;
};

export function buildInitialTextFields({
  customization,
  layoutDefaults,
  eventName,
}: BuildInitialTextFieldsParams): { headline: string; subtitle: string; description: string; instructions: string[] } {
  const initialInstructions =
    Array.isArray(customization?.instructions) && customization.instructions.length
      ? customization.instructions
          .map((item: unknown) => String(item ?? ''))
          .filter((item: string) => item.length > 0)
      : [
          'QR-Code scannen\nKamera-App öffnen und auf den Code richten.',
          'Webseite öffnen\nDer Link öffnet direkt das gemeinsame Jubiläumsalbum.',
          'Fotos hochladen\nZeigt eure Lieblingsmomente oder erfüllt kleine Fotoaufgaben, um besondere Erinnerungen beizusteuern.',
        ];

  return {
    headline:
      (typeof customization?.headline === 'string' && customization.headline.length ? customization.headline : null) ??
      (typeof eventName === 'string' && eventName.length ? eventName : null) ??
      (typeof layoutDefaults?.name === 'string' ? layoutDefaults.name : '') ??
      '',
    subtitle: typeof customization?.subtitle === 'string' ? customization.subtitle : '',
    description:
      (typeof customization?.description === 'string' && customization.description.length ? customization.description : null) ??
      (typeof layoutDefaults?.description === 'string' ? layoutDefaults.description : null) ??
      'Helft uns, diesen besonderen Tag mit euren schönen Momenten festzuhalten.',
    instructions: initialInstructions,
  };
}

export function resolveLayoutForFormat(
  format: 'a4-poster' | 'a5-foldable',
  layouts: EventQrInviteLayout[],
): string | null {
  const formatKey = format === 'a4-poster' ? 'poster-a4' : 'foldable-a5';

  const byHint = layouts.find((layout) => (layout as any)?.format_hint === formatKey);
  if (byHint?.id) {
    return byHint.id;
  }

  const match = layouts.find((layout) => {
    const paper = (layout.paper || '').toLowerCase();
    const orientation = (layout.orientation || '').toLowerCase();
    const panel = (layout.panel_mode || '').toLowerCase();
    if (format === 'a4-poster') {
      return paper === 'a4' && orientation === 'portrait' && panel !== 'double-mirror';
    }

    return paper === 'a4' && orientation === 'landscape' && panel === 'double-mirror';
  });

  if (match?.id) {
    return match.id;
  }

  if (format === 'a5-foldable') {
    const fallback = layouts.find((layout) => (layout.id || '').includes('foldable'));

    return fallback?.id ?? layouts[0]?.id ?? null;
  }

  return layouts[0]?.id ?? null;
}
