import { writable } from 'svelte/store';

export interface Region {
    id: string;
    name: string;
    currency_code: string;
    tax_rate: number;
    tax_code: string | null;
    countries: {
        id: number;
        iso_2: string;
        iso_3: string;
        name: string;
        display_name: string;
        region_id: string | null;
        num_iso: string;
    }[];
}

function createRegionStore() {
    // Initialize with default region
    const defaultRegion = {
        id: 'reg_01JXB17SNW6VA5WJVV8QPHKAY3',
        name: 'EU',
        currency_code: 'eur',
        tax_rate: 0,
        tax_code: null,
        countries: []
    };

    let initialRegion = defaultRegion;

    // Only try to get from localStorage if we're in the browser
    if (typeof window !== 'undefined') {
        const savedRegion = localStorage.getItem('selectedRegion');
        if (savedRegion) {
            try {
                const parsed = JSON.parse(savedRegion);
                if (parsed && typeof parsed === 'object' && 'id' in parsed) {
                    initialRegion = parsed;
                }
            } catch (e) {
                console.warn('Failed to parse stored region, using default', e);
                localStorage.removeItem('selectedRegion'); // Clear invalid data
            }
        }
    }

    const { subscribe, set, update } = writable<Region>(initialRegion);

    return {
        subscribe,
        setRegion: (region: Region) => {
            if (typeof window !== 'undefined') {
                try {
                    localStorage.setItem('selectedRegion', JSON.stringify(region));
                } catch (e) {
                    console.error('Failed to save region to localStorage', e);
                }
            }
            set(region);
        },
        getRegion: () => {
            if (typeof window !== 'undefined') {
                const savedRegion = localStorage.getItem('selectedRegion');
                if (savedRegion) {
                    try {
                        const parsed = JSON.parse(savedRegion);
                        if (parsed && typeof parsed === 'object' && 'id' in parsed) {
                            return parsed;
                        }
                    } catch (e) {
                        console.warn('Failed to parse stored region, using default', e);
                    }
                }
            }
            return defaultRegion;
        }
    };
}

export const region = createRegionStore(); 