import { Component, computed, inject, input } from '@angular/core';
import { CountryResource } from '@isa/crm/data-access';
import { Address } from './types';

@Component({
  selector: 'shared-inline-address',
  standalone: true,
  template: `
    @if (addressLine()) {
      {{ addressLine() }}
    }
  `,
})
export class InlineAddressComponent {
  #countryResource = inject(CountryResource);

  address = input<Address>();

  addressLine = computed(() => {
    const a = this.address();
    if (!a) return '';

    const parts: string[] = [];

    // Street and number without comma between them
    const streetPart = [a.street, a.streetNumber].filter(Boolean).join(' ');
    if (streetPart) parts.push(streetPart);

    // Zip and city
    const cityPart = [a.zipCode, a.city].filter(Boolean).join(' ');
    if (cityPart) parts.push(cityPart);

    const baseLine = parts.join(', ');

    // Display country only if it exists and is not Germany
    if (a.country && a.country !== 'DEU') {
      const countryName = this.#getCountryName(a.country);
      return baseLine ? `${baseLine}, ${countryName}` : countryName;
    }

    return baseLine;
  });

  #getCountryName(countryCode: string): string {
    const countries = this.#countryResource.resource.value();
    if (!countries || !Array.isArray(countries)) return countryCode;

    const country = countries.find((c) => c.isO3166_A_3 === countryCode);
    return country?.name || countryCode;
  }
}
