import { writable } from 'svelte/store';
import type { MedusaProduct, MedusaVariant } from '$lib/types/medusa';

export interface CartItem {
    product: MedusaProduct;
    variant: MedusaVariant;
    quantity: number;
}

function createCartStore() {
    const { subscribe, set, update } = writable<CartItem[]>([]);
    const isOpenStore = writable<boolean>(false);
    let autoCloseTimeout: number | undefined;

    // Load initial state from localStorage
    if (typeof window !== 'undefined') {
        const savedCart = localStorage.getItem('cart');
        if (savedCart) {
            set(JSON.parse(savedCart));
        }
    }

    return {
        subscribe,
        subscribeToOpen: isOpenStore.subscribe,
        toggleCart: () => {
            // Clear any existing auto-close timeout
            if (autoCloseTimeout) {
                clearTimeout(autoCloseTimeout);
                autoCloseTimeout = undefined;
            }
            isOpenStore.update(state => !state);
        },
        addToCart: (product: MedusaProduct, variant: MedusaVariant) => {
            update(items => {
                const existingItem = items.find(item => 
                    item.product.id === product.id && item.variant.id === variant.id
                );

                if (existingItem) {
                    existingItem.quantity += 1;
                    return [...items];
                }

                const newItems = [...items, { product, variant, quantity: 1 }];
                localStorage.setItem('cart', JSON.stringify(newItems));
                return newItems;
            });

            // Clear any existing timeout
            if (autoCloseTimeout) {
                clearTimeout(autoCloseTimeout);
            }

            // Open cart
            isOpenStore.set(true);

            // Auto close after 2 seconds
            autoCloseTimeout = window.setTimeout(() => {
                isOpenStore.set(false);
                autoCloseTimeout = undefined;
            }, 2000);
        },
        updateQuantity: (index: number, quantity: number) => {
            update(items => {
                if (quantity < 1) {
                    const newItems = items.filter((_, i) => i !== index);
                    localStorage.setItem('cart', JSON.stringify(newItems));
                    return newItems;
                }

                items[index].quantity = quantity;
                localStorage.setItem('cart', JSON.stringify(items));
                return [...items];
            });
        },
        removeItem: (index: number) => {
            update(items => {
                const newItems = items.filter((_, i) => i !== index);
                localStorage.setItem('cart', JSON.stringify(newItems));
                return newItems;
            });
        }
    };
}

export const cart = createCartStore(); 