import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = Pusher;
window.Echo = new Echo({
    broadcaster: 'reverb',
    key: import.meta.env.VITE_REVERB_APP_KEY,
    wsHost: import.meta.env.VITE_REVERB_HOST,
    wsPort: 443,
    wssPort: 443,
    forceTLS: true,
    enabledTransports: ['ws', 'wss'],
});

import QRCode from 'qrcode';
window.QRCode = QRCode;

import {
    Chart,
    LineController, LineElement,
    BarController, BarElement,
    DoughnutController, ArcElement,
    PointElement, LinearScale, CategoryScale,
    Tooltip, Legend, Filler,
    TimeScale,
} from 'chart.js';

Chart.register(
    LineController, LineElement,
    BarController, BarElement,
    DoughnutController, ArcElement,
    PointElement, LinearScale, CategoryScale,
    Tooltip, Legend, Filler, TimeScale
);

window.Chart = Chart;

// Alpine stores registered via alpine:init — Livewire v3 owns Alpine lifecycle
document.addEventListener('alpine:init', () => {
    Alpine.store('theme', {
        current: localStorage.getItem('nimuli_theme') || document.documentElement.dataset.theme || 'dark',
        init() { this.apply(this.current); },
        apply(theme) {
            this.current = theme;
            const actual = theme === 'system'
                ? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
                : theme;
            document.documentElement.dataset.theme = actual;
            localStorage.setItem('nimuli_theme', theme);
            document.cookie = 'nimuli_theme=' + actual + '; path=/; max-age=31536000; SameSite=Lax';
        },
        cycle() {
            const order = ['dark', 'light', 'system'];
            this.apply(order[(order.indexOf(this.current) + 1) % order.length]);
        },
    });

    Alpine.store('sidebar', {
        mobileOpen: false,
        collapsed: localStorage.getItem('sidebarCollapsed') === 'true',
        init() { this._syncDataset(); },
        _syncDataset() {
            if (this.collapsed) {
                document.documentElement.dataset.sidebarCollapsed = '1';
            } else {
                delete document.documentElement.dataset.sidebarCollapsed;
            }
        },
        toggle() {
            this.collapsed = ! this.collapsed;
            localStorage.setItem('sidebarCollapsed', this.collapsed);
            this._syncDataset();
            window.dispatchEvent(new CustomEvent('sidebar-toggled', { detail: { collapsed: this.collapsed } }));
        },
        toggleMobile() { this.mobileOpen = ! this.mobileOpen; },
        closeMobile() { this.mobileOpen = false; },
    });
});
