import './bootstrap';

import Alpine from 'alpinejs';

window.Alpine = Alpine;

document.addEventListener('alpine:init', () => {
    Alpine.data('filePreviewModal', () => ({
        open: false,
        url: '',
        title: '',
        kind: 'none',
        openPreview({ url, title, mime }) {
            this.url = url || '';
            this.title = title || '';
            const m = mime || '';
            if (m.startsWith('image/')) {
                this.kind = 'image';
            } else if (m === 'application/pdf') {
                this.kind = 'pdf';
            } else if (m.startsWith('video/')) {
                this.kind = 'video';
            } else {
                this.kind = 'other';
            }
            this.open = true;
            document.body.classList.add('overflow-y-hidden');
        },
        closePreview() {
            this.open = false;
            this.kind = 'none';
            this.url = '';
            this.title = '';
            document.body.classList.remove('overflow-y-hidden');
        },
    }));

    Alpine.data('reservationBuilder', (products, initialItems = []) => ({
        products: Array.isArray(products) ? products : [],
        query: '',
        open: false,
        lines: Array.isArray(initialItems) && initialItems.length > 0
            ? initialItems.map((it) => ({
                product_id: Number(it.product_id),
                quantity: Number(it.quantity) > 0 ? Number(it.quantity) : 1,
            }))
            : [],

        get filteredProducts() {
            const q = this.query.trim().toLowerCase();
            const selected = new Set(this.lines.map((l) => Number(l.product_id)));
            return this.products
                .filter((p) => !selected.has(Number(p.id)))
                .filter((p) => {
                    if (!q) {
                        return true;
                    }
                    return (
                        String(p.name || '').toLowerCase().includes(q)
                        || String(p.sku || '').toLowerCase().includes(q)
                        || String(p.barcode || '').toLowerCase().includes(q)
                    );
                })
                .slice(0, 8);
        },

        addProduct(product) {
            if (!product || !product.id) {
                return;
            }
            if (this.lines.some((l) => Number(l.product_id) === Number(product.id))) {
                this.query = '';
                this.open = false;
                return;
            }
            this.lines.push({ product_id: Number(product.id), quantity: 1 });
            this.query = '';
            this.open = false;
        },

        removeLine(index) {
            this.lines.splice(index, 1);
        },

        getProduct(id) {
            return this.products.find((p) => Number(p.id) === Number(id));
        },
    }));
});

Alpine.start();
