<script lang="ts">
    import { onMount } from 'svelte';
    import { region } from '$lib/stores/region';
    import type { Region } from '$lib/stores/region';
    import { PUBLIC_MEDUSA_KEY } from '$env/static/public';

    let regions: Region[] = [];
    let selectedRegion: Region;
    let loading = true;

    onMount(async () => {
        try {
            const response = await fetch('http://localhost:9000/store/regions', {
                headers: {
                    'x-publishable-api-key': PUBLIC_MEDUSA_KEY,
                }
            });
            
            if (!response.ok) {
                throw new Error('Failed to fetch regions');
            }

            const data = await response.json();
            console.log(data);
            regions = data.regions;
            
            // Set the selected region from the store
            selectedRegion = $region;
        } catch (error) {
            console.error('Error fetching regions:', error);
        } finally {
            loading = false;
        }
    });

    function handleRegionChange(event: Event) {
        const select = event.target as HTMLSelectElement;
        const newRegion = regions.find(r => r.id === select.value);
        if (newRegion) {
            region.setRegion(newRegion);
            selectedRegion = newRegion;
            
            // Set cookie for server-side access
            document.cookie = `selectedRegion=${newRegion.id}; path=/; max-age=31536000`; // 1 year expiry
            
            // Reload the page to fetch products with new region
            window.location.reload();
        }
    }
</script>

<div class="form-control w-full">
    <label class="label" for="region-select">
        <span class="label-text text-neutral-content">Region</span>
    </label>
    <select 
        id="region-select"
        class="select select-bordered w-full bg-neutral text-neutral-content border-neutral-content/20"
        value={selectedRegion?.id}
        on:change={handleRegionChange}
        disabled={loading}
    >
        {#if loading}
            <option value="">Loading regions...</option>
        {:else}
            {#each regions as region}
                <option value={region.id}>
                    {region.name} ({region.currency_code.toUpperCase()})
                </option>
            {/each}
        {/if}
    </select>
</div> 