<template>
  <div>
    <div style="white-space: pre-line">
      {{ formattedAddressLine1 }}
    </div>
    <div>
      {{ formattedAddressLine2 }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import type { NominatimResponse } from 'components/models';

const props = defineProps<{
  address?: NominatimResponse | undefined;
}>();

const formattedAddressLine1 = computed(() => {
  if (props.address) {
    const place = [props.address.leisure, props.address.shop].filter(Boolean);
    const addy = [props.address.house_number, props.address.road].filter(Boolean).join(' ');
    return [place, addy].filter(Boolean).join('\n');
  } else {
    return '';
  }
});

const formattedAddressLine2 = computed(() => {
  if (props.address) {
    const town = props.address.city ?? props.address.village ?? props.address.town;
    const stateAbbr = stateAbbrevMap[props.address.state] ?? props.address.state ?? ' ';
    const cityState = [town, stateAbbr].filter(Boolean).join(', ');
    return [cityState, props.address.postcode].filter(Boolean).join(' ');
  } else {
    return '';
  }
});

const stateAbbrevMap: Record<string, string> = {
  Alabama: 'AL',
  Alaska: 'AK',
  Arizona: 'AZ',
  Arkansas: 'AR',
  California: 'CA',
  Colorado: 'CO',
  Connecticut: 'CT',
  Delaware: 'DE',
  Florida: 'FL',
  Georgia: 'GA',
  Hawaii: 'HI',
  Idaho: 'ID',
  Illinois: 'IL',
  Indiana: 'IN',
  Iowa: 'IA',
  Kansas: 'KS',
  Kentucky: 'KY',
  Louisiana: 'LA',
  Maine: 'ME',
  Maryland: 'MD',
  Massachusetts: 'MA',
  Michigan: 'MI',
  Minnesota: 'MN',
  Mississippi: 'MS',
  Missouri: 'MO',
  Montana: 'MT',
  Nebraska: 'NE',
  Nevada: 'NV',
  'New Hampshire': 'NH',
  'New Jersey': 'NJ',
  'New Mexico': 'NM',
  'New York': 'NY',
  'North Carolina': 'NC',
  'North Dakota': 'ND',
  Ohio: 'OH',
  Oklahoma: 'OK',
  Oregon: 'OR',
  Pennsylvania: 'PA',
  'Rhode Island': 'RI',
  'South Carolina': 'SC',
  'South Dakota': 'SD',
  Tennessee: 'TN',
  Texas: 'TX',
  Utah: 'UT',
  Vermont: 'VT',
  Virginia: 'VA',
  Washington: 'WA',
  'West Virginia': 'WV',
  Wisconsin: 'WI',
  Wyoming: 'WY',
};
</script>
