import './bootstrap';
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

document.addEventListener('DOMContentLoaded', () => {
    const content = document.getElementById('app-content');
    const sidebar = document.getElementById('sidebar');
    const isDesktop = window.matchMedia('(min-width: 1024px)').matches;
    const sidebarStorageKey = 'sidebar_hidden';
    const notifStorageKey = 'order_notifications';
    const notifUnreadKey = 'order_notifications_unread';
    const notifButton = document.getElementById('notif-button');
    const notifCount = document.getElementById('notif-count');
    const notifList = document.getElementById('notif-list');

    function setContentPadding() {
        if (!content || !sidebar) {
            return;
        }
        const isHidden = sidebar.classList.contains('-translate-x-full');
        content.classList.toggle('lg:pl-64', !isHidden);
    }

    function setSidebarHidden(hidden) {
        if (!sidebar) {
            return;
        }
        sidebar.classList.toggle('-translate-x-full', hidden);
        setContentPadding();
        try {
            localStorage.setItem(sidebarStorageKey, hidden ? '1' : '0');
        } catch (error) {
            // ignore storage errors
        }
    }

    document.querySelectorAll('[data-drawer-toggle]').forEach((trigger) => {
        trigger.addEventListener('click', () => {
            const targetId = trigger.getAttribute('data-drawer-target');
            const target = document.getElementById(targetId);
            if (!target) {
                return;
            }
            const willHide = !target.classList.contains('-translate-x-full');
            setSidebarHidden(willHide);
        });
    });

    const dropdownTriggers = document.querySelectorAll('[data-dropdown-toggle]');
    dropdownTriggers.forEach((trigger) => {
        trigger.addEventListener('click', () => {
            const targetId = trigger.getAttribute('data-dropdown-toggle');
            const target = document.getElementById(targetId);
            if (!target) {
                return;
            }
            target.classList.toggle('hidden');
        });
    });

    document.addEventListener('click', (event) => {
        dropdownTriggers.forEach((trigger) => {
            const targetId = trigger.getAttribute('data-dropdown-toggle');
            const target = document.getElementById(targetId);
            if (!target || target.classList.contains('hidden')) {
                return;
            }
            const clickedInside = trigger.contains(event.target) || target.contains(event.target);
            if (!clickedInside) {
                target.classList.add('hidden');
            }
        });
    });

    document.querySelectorAll('[data-dismiss-target]').forEach((trigger) => {
        trigger.addEventListener('click', () => {
            const targetId = trigger.getAttribute('data-dismiss-target');
            const target = document.querySelector(targetId);
            if (target) {
                target.remove();
            }
        });
    });

    if (sidebar && content) {
        const stored = (() => {
            try {
                return localStorage.getItem(sidebarStorageKey);
            } catch (error) {
                return null;
            }
        })();
        if (isDesktop) {
            setSidebarHidden(stored === '1');
        } else {
            sidebar.classList.add('-translate-x-full');
            setContentPadding();
        }
    }

    function loadNotifications() {
        if (!notifList || !notifCount) {
            return [];
        }
        try {
            const raw = localStorage.getItem(notifStorageKey);
            return raw ? JSON.parse(raw) : [];
        } catch (error) {
            return [];
        }
    }

    function saveNotifications(list, unread) {
        try {
            localStorage.setItem(notifStorageKey, JSON.stringify(list));
            localStorage.setItem(notifUnreadKey, String(unread));
        } catch (error) {
            // ignore storage errors
        }
    }

    function renderNotifications(list) {
        if (!notifList || !notifCount) {
            return;
        }
        notifList.innerHTML = '';
        if (list.length === 0) {
            notifList.innerHTML = '<div class="px-4 py-4 text-xs text-slate-500">Belum ada notifikasi.</div>';
            return;
        }
        list.forEach((item) => {
            const row = document.createElement('div');
            row.className = 'border-b border-slate-100 px-4 py-3 last:border-b-0';
            const wrapperOpen = item.url ? `<a href="${item.url}" class="block rounded-lg -m-2 p-2 hover:bg-slate-50">` : '<div>';
            const wrapperClose = item.url ? '</a>' : '</div>';
            row.innerHTML = `
                ${wrapperOpen}
                    <div class="flex items-center justify-between gap-2">
                        <div class="text-sm font-semibold text-slate-800">${item.title}</div>
                        <div class="text-[11px] text-slate-400">${item.time}</div>
                    </div>
                    <div class="text-xs text-slate-500">${item.body}</div>
                ${wrapperClose}
            `;
            notifList.appendChild(row);
        });
    }

    function updateUnread(count) {
        if (!notifCount) {
            return;
        }
        notifCount.textContent = String(count);
        notifCount.classList.toggle('hidden', count === 0);
    }

    function addNotification(detail) {
        if (!notifList || !notifCount) {
            return;
        }
        const list = loadNotifications();
        const now = new Date();
        const orderNo = detail?.order_no ? `#${detail.order_no}` : 'Order baru';
        const title = detail?.status === 'open' ? 'Order Masuk' : 'Order Diperbarui';
        const body = `${orderNo} ${detail?.type ? `(${detail.type})` : ''}`.trim();
        const orderId = detail?.id ?? null;
        const orderUrl = orderId ? `/orders/${orderId}` : null;
        list.unshift({
            title,
            body,
            time: now.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }),
            url: orderUrl,
        });
        const trimmed = list.slice(0, 10);
        const unread = Math.min((parseInt(localStorage.getItem(notifUnreadKey) || '0', 10) || 0) + 1, 99);
        saveNotifications(trimmed, unread);
        renderNotifications(trimmed);
        updateUnread(unread);
    }

    if (notifButton) {
        const list = loadNotifications();
        renderNotifications(list);
        updateUnread(parseInt(localStorage.getItem(notifUnreadKey) || '0', 10) || 0);
        notifButton.addEventListener('click', () => {
            updateUnread(0);
            saveNotifications(loadNotifications(), 0);
        });
    }

    window.addEventListener('orders-realtime', (event) => {
        addNotification(event.detail);
    });
});

if (import.meta.env.VITE_PUSHER_APP_KEY) {
    window.Pusher = Pusher;
    window.Echo = new Echo({
        broadcaster: 'pusher',
        key: import.meta.env.VITE_PUSHER_APP_KEY,
        cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'ap1',
        forceTLS: true,
    });

    window.Echo.channel('orders')
        .listen('.order.created', (data) => {
            window.dispatchEvent(new CustomEvent('orders-realtime', { detail: data }));
        })
        .listen('.order.updated', (data) => {
            window.dispatchEvent(new CustomEvent('orders-realtime', { detail: data }));
        });
}
