<script lang="ts">
	import type { CityBasic, ComboOption, CountryBasic } from '$lib/types';
    import ComboBox from './ComboBox.svelte';
    let selectedFirstCity: CityBasic | null = $state(null);
	let selectedSecondCity: CityBasic | null = $state(null);

    let { cities }: { cities: CityBasic[] } = $props();
    
    const isCityBasic = (city: CityBasic | ComboOption | CountryBasic): city is CityBasic => {
		return 'country_id' in city;
	};
    let comboFirstFilteredCities: CityBasic[] = $derived(
		selectedSecondCity ? 
		cities.filter((c) => c.id !== selectedSecondCity?.id) : 
		cities
	);
	let comboSecondFilteredCities: CityBasic[] = $derived(
		selectedFirstCity ? 
		cities.filter((c) => c.id !== selectedFirstCity?.id) : 
		cities
	);

    const onFirstCitySelect = (city: CityBasic | ComboOption | CountryBasic) => {
		if (isCityBasic(city)) {
			selectedFirstCity = city;
		}
	};

	const onSecondCitySelect = (city: CityBasic | ComboOption | CountryBasic) => {
		if (isCityBasic(city)) {
			selectedSecondCity = city;
		}
	};
   
</script>
<section class="grid grid-cols-1 md:grid-cols-2 gap-5">
    <div>
        <ComboBox
            options={comboFirstFilteredCities}
            onSelect={onFirstCitySelect}
            onClear={() => (selectedFirstCity = null)}
        />
    </div>
    <div>
        <ComboBox
            options={comboSecondFilteredCities}
            onSelect={onSecondCitySelect}
            onClear={() => selectedSecondCity = null}
        />
    </div>
</section>