import './bootstrap';
import Alpine from 'alpinejs';

window.Alpine = Alpine;

Alpine.store('toast', {
    show: false,
    message: '',
    type: 'success',
    timer: null,
    notify(message, type = 'success') {
        clearTimeout(this.timer);
        this.show = true;
        this.message = message;
        this.type = type;
        
        try {
            const soundFile = type === 'error' ? '/assets/sounds/error.mp3' : '/assets/sounds/success.mp3';
            const audio = new Audio(soundFile);
            audio.play().catch(err => {
                // Ignore autoplay policy restriction errors quietly
            });
        } catch (e) {
            // Silently catch audio play issues
        }

        this.timer = setTimeout(() => (this.show = false), 3500);
    },
});

// Global shortcut: notify('Saved', 'success')
window.notify = (message, type = 'success') => Alpine.store('toast').notify(message, type);

/**
 * Central fetch wrapper — CSRF, JSON headers, error toast, 422 pass-through.
 * Usage: await apiFetch('/items', { method: 'POST', body: {...} })
 */
window.apiFetch = async function (url, options = {}) {
    const headers = {
        Accept: 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content ?? '',
        ...(options.headers || {}),
    };

    if (options.body && typeof options.body === 'object' && !(options.body instanceof FormData)) {
        headers['Content-Type'] = 'application/json';
        options.body = JSON.stringify(options.body);
    } else if (options.body && typeof options.body === 'string') {
        headers['Content-Type'] = 'application/json';
    }

    let res;
    try {
        res = await fetch(url, { ...options, headers });
    } catch (e) {
        window.notify('Server se connect nahi ho saka.', 'error');
        throw e;
    }

    let data = null;
    try {
        data = await res.json();
    } catch (e) {
        /* empty body, e.g. 204 */
    }

    if (!res.ok) {
        if (res.status === 422 && data?.errors) {
            const err = new Error(data.message ?? 'Validation failed');
            err.status = 422;
            err.errors = data.errors;
            throw err;
        }
        window.notify(data?.message ?? `Request failed (${res.status})`, 'error');
        const err = new Error(data?.message ?? 'Request failed');
        err.status = res.status;
        err.data = data;
        throw err;
    }

    return data;
};

// Flash toast across redirects (create/edit -> index)
document.addEventListener('alpine:init', () => {
    const flash = sessionStorage.getItem('flash');
    if (flash) {
        sessionStorage.removeItem('flash');
        try {
            const { message, type } = JSON.parse(flash);
            Alpine.store('toast').notify(message, type);
        } catch (e) {}
    }
});

window.flashAndRedirect = (message, type, url) => {
    sessionStorage.setItem('flash', JSON.stringify({ message, type }));
    window.location.href = url;
};

Alpine.directive('flatpickr', (el, { expression }, { evaluateLater, cleanup }) => {
    const config = expression ? evaluateLater(expression) : (cb) => cb({});
    config(configObj => {
        const picker = flatpickr(el, {
            dateFormat: 'Y-m-d',
            allowInput: true,
            ...configObj,
            onChange: (selectedDates, dateStr) => {
                el.value = dateStr;
                el.dispatchEvent(new Event('input', { bubbles: true }));
            }
        });
        cleanup(() => picker.destroy());
    });
});

Alpine.start();