import ApexCharts from 'apexcharts';

const sidebar = document.querySelector('[data-admin-sidebar]');
const overlay = document.querySelector('.ac-overlay');
const desktopQuery = window.matchMedia('(min-width: 1181px)');

const closeMobileSidebar = () => {
    sidebar?.classList.remove('open');
    overlay?.classList.remove('open');
};

document.querySelectorAll('[data-admin-sidebar-toggle]:not(.ac-collapse-pill)').forEach((trigger) => {
    trigger.addEventListener('click', () => {
        if (desktopQuery.matches) {
            document.body.classList.toggle('ac-sidebar-expanded');
            return;
        }

        sidebar?.classList.toggle('open');
        overlay?.classList.toggle('open');
    });
});

document.querySelectorAll('.ac-collapse-pill').forEach((trigger) => {
    trigger.addEventListener('click', () => {
        if (desktopQuery.matches) {
            document.body.classList.toggle('ac-sidebar-expanded');
            trigger.setAttribute('aria-expanded', document.body.classList.contains('ac-sidebar-expanded') ? 'true' : 'false');
            return;
        }

        sidebar?.classList.toggle('open');
        overlay?.classList.toggle('open');
    });
});

overlay?.addEventListener('click', closeMobileSidebar);
desktopQuery.addEventListener?.('change', () => {
    closeMobileSidebar();
});

document.querySelectorAll('[data-admin-chart]').forEach((element) => {
    const key = element.getAttribute('data-admin-chart');
    const source = document.querySelector(`[data-admin-chart-source="${key}"]`);

    if (!source) {
        return;
    }

    try {
        const payload = JSON.parse(source.textContent || '{}');
        const type = element.getAttribute('data-chart-type') || 'line';
        element.innerHTML = '';
        const chart = new ApexCharts(element, {
            chart: {
                type,
                height: Number(element.getAttribute('data-chart-height') || 320),
                toolbar: { show: false },
                fontFamily: '"IBM Plex Sans Arabic", Alexandria, system-ui, sans-serif',
                foreColor: '#667085',
                animations: { enabled: true, easing: 'easeinout', speed: 450 },
            },
            colors: ['#0F9F98', '#475467', '#F79009', '#D92D20'],
            dataLabels: { enabled: false },
            stroke: { curve: 'smooth', width: 2 },
            grid: { borderColor: '#E4E7EC', strokeDashArray: 4 },
            series: payload.series || [],
            xaxis: {
                categories: payload.labels || [],
                labels: { style: { colors: '#667085', fontWeight: 500 } },
                axisBorder: { color: '#E4E7EC' },
                axisTicks: { color: '#E4E7EC' },
            },
            yaxis: {
                labels: { style: { colors: '#667085', fontWeight: 500 } },
            },
            legend: {
                position: 'top',
                horizontalAlign: 'right',
                labels: { colors: '#344054' },
                fontWeight: 600,
            },
            fill: { type: 'solid', opacity: type === 'area' ? 0.12 : 1 },
            tooltip: { theme: 'light', shared: true, intersect: false },
        });

        chart.render().then(() => {
            element.classList.add('is-loaded');
        });
    } catch (error) {
        element.innerHTML = '<div class="ad-empty-state compact"><strong>تعذر تحميل الرسم</strong><span>راجع بيانات الفترة ثم حاول مرة أخرى.</span></div>';
    }
});
