import { i18n, localeForLanguage } from '../i18n';

/**
 * Textes importés du site WordPress : « [:fr]La Marsa[:en]La Marsa[:] ».
 * On garde la langue de l'interface, sinon le français, sinon le premier bloc.
 */
export function cleanCrmText(raw: string | null | undefined): string | null {
  const text = raw?.trim();
  if (!text) return null;
  if (!text.includes('[:')) return text;

  const blocks: Record<string, string> = {};
  const re = /\[:([a-z]{2})?\]([\s\S]*?)(?=\[:|$)/gi;
  let match: RegExpExecArray | null;
  while ((match = re.exec(text)) !== null) {
    const lang = (match[1] ?? '').toLowerCase();
    const value = match[2].trim();
    if (lang && value && !blocks[lang]) blocks[lang] = value;
  }
  const keys = Object.keys(blocks);
  if (!keys.length) return text.replace(/\[:[a-z]{0,2}\]/gi, '').trim() || null;
  const ui = (i18n.language ?? 'fr').toLowerCase().split('-')[0];
  return blocks[ui] || blocks.fr || blocks[keys[0]];
}

/**
 * Références du bien comme dans le CRM : référence métier puis référence interne
 * (« Ref254Ta / 14204 »), sans répéter la même valeur.
 */
export function propertyReferenceLabel(item: {
  reference?: string | null;
  referenceImmo?: string | null;
}): string {
  const parts = [item.referenceImmo, item.reference]
    .map((v) => v?.trim())
    .filter((v): v is string => !!v);
  return [...new Set(parts)].join(' / ');
}

/** « La Marsa » vs « la marsa » vs « La  Marsa » — same place, show it once. */
export function sameLocationText(a?: string | null, b?: string | null): boolean {
  const norm = (v?: string | null) =>
    (v ?? '')
      .toLowerCase()
      .normalize('NFD')
      .replace(/[\u0300-\u036f]/g, '')
      .replace(/[^a-z0-9]+/g, ' ')
      .trim();
  const left = norm(a);
  const right = norm(b);
  return left !== '' && left === right;
}

/** Rooms / bedrooms short label for lists & chips. */
export function formatRoomsAbbrev(count: number): string {
  return i18n.t('property.roomsAbbrev', { count });
}

/** Floor label — ground floor vs numbered étage. */
export function formatFloorLabel(floor: string | number | null | undefined): string | null {
  if (floor == null || String(floor).trim() === '') return null;
  const floorNum = Number(floor);
  if (Number.isFinite(floorNum) && floorNum === 0) {
    return i18n.t('property.groundFloor');
  }
  return i18n.t('property.floorWithNumber', { floor });
}

export function formatSurface(surface: number | string): string {
  return i18n.t('property.surfaceWithUnit', { surface });
}

export function formatMoney(
  amount: number,
  currency = 'TND',
  lang?: string,
): string {
  const locale = localeForLanguage(lang ?? i18n.language);
  return i18n.t('property.currencyAmount', {
    amount: amount.toLocaleString(locale),
    currency,
  });
}

export type PropertyMetaFields = {
  bedrooms?: number | null;
  rooms?: number | null;
  surface?: number | null;
  floor?: string | number | null;
};

/** Compact meta line: « 3 ch. · 120 m² · Étage 2 » (localized). */
export function formatPropertyMeta(item: PropertyMetaFields): string {
  const parts: string[] = [];
  const chambres =
    item.bedrooms != null && Number(item.bedrooms) > 0
      ? Number(item.bedrooms)
      : item.rooms != null && Number(item.rooms) > 0
        ? Number(item.rooms)
        : null;
  if (chambres != null) parts.push(formatRoomsAbbrev(chambres));
  if (item.surface != null && Number(item.surface) > 0) {
    parts.push(formatSurface(Number(item.surface)));
  }
  const floor = formatFloorLabel(item.floor);
  if (floor) parts.push(floor);
  return parts.join(' · ');
}
