/**
 * Build rows for the regional-picker country/city grid.
 *
 * Matches Angular `DictionariesService.handleLoading` logic:
 *   1. Countries in the region: alphabetical by localized name, RU first.
 *   2. Cities within a country: alphabetical, excluding MOW initially;
 *      MOW re-inserted at front for RU country.
 *   3. Row packing: city with >1 airport gets its own row (airports below);
 *      others paired into city1 + city2 columns.
 *   4. `countryName` set only on the first row of each country's block.
 */

import type {
  IAirport,
  ICity,
  IDictionaries,
} from "@/shared/dictionaries/index.js";

export interface ICountryCityRow {
  countryName?: string;
  city1: ICity | null;
  city2: ICity | null;
  city1Airports?: IAirport[];
}

export function buildCountryCityRows(
  dictionaries: IDictionaries,
  regionId: number,
): ICountryCityRow[] {
  const region = dictionaries.regions.find((r) => r.id === regionId);
  if (!region || region.countries.length === 0) return [];

  const countries = [...region.countries].sort((a, b) =>
    a.name.localeCompare(b.name),
  );
  const ruIdx = countries.findIndex((c) => c.code === "RU");
  if (ruIdx > 0) {
    const [ru] = countries.splice(ruIdx, 1);
    if (ru) countries.unshift(ru);
  }

  const rows: ICountryCityRow[] = [];

  for (const country of countries) {
    const cities = dictionaries.cities
      .filter((c) => c.country_code === country.code && c.code !== "MOW")
      .sort((a, b) => a.name.localeCompare(b.name));

    if (country.code === "RU") {
      const mow = dictionaries.cities.find((c) => c.code === "MOW");
      if (mow) cities.unshift(mow);
    }

    if (cities.length === 0) continue;

    let firstRow = true;
    let i = 0;
    while (i < cities.length) {
      const city1 = cities[i];
      if (!city1) break;
      const multiAirport = city1.airports.length > 1;

      if (multiAirport) {
        rows.push({
          ...(firstRow ? { countryName: country.name } : {}),
          city1,
          city2: null,
          city1Airports: city1.airports,
        });
        i += 1;
      } else {
        const city2 = cities[i + 1] ?? null;
        rows.push({
          ...(firstRow ? { countryName: country.name } : {}),
          city1,
          city2,
        });
        i += 2;
      }
      firstRow = false;
    }
  }

  return rows;
}
