document.addEventListener('DOMContentLoaded', () => {
    const clinicSelects = document.querySelectorAll('.js-clinic-select');
    clinicSelects.forEach((clinicSelect) => {
        const form = clinicSelect.closest('form');
        if (!form) return;
        const doctorSelect = form.querySelector('.js-doctor-select');
        if (!doctorSelect) return;

        const syncDoctors = () => {
            const clinicId = clinicSelect.value;
            Array.from(doctorSelect.options).forEach((option) => {
                if (!option.value) {
                    option.hidden = false;
                    return;
                }
                const visible = option.dataset.clinicId === clinicId;
                option.hidden = !visible;
                if (!visible && option.selected) {
                    doctorSelect.value = '';
                }
            });
        };

        clinicSelect.addEventListener('change', syncDoctors);
        syncDoctors();
    });

    const ticketPrintButton = document.querySelector('.js-print-ticket');
    if (ticketPrintButton) {
        ticketPrintButton.addEventListener('click', () => window.print());
    }

    document.querySelectorAll('.js-app-toast').forEach((toastNode) => {
        if (window.bootstrap && bootstrap.Toast) {
            bootstrap.Toast.getOrCreateInstance(toastNode, { delay: 3200 }).show();
        }
    });

    const locale = document.body.dataset.locale || 'en';
    const timeZone = document.body.dataset.timezone || 'UTC';
    const liveClock = document.querySelector('.js-live-clock');
    if (liveClock) {
        const renderClock = () => {
            const now = new Date();
            const opts = { hour: '2-digit', minute: '2-digit' };
            if (timeZone) opts.timeZone = timeZone;
            try {
                liveClock.textContent = now.toLocaleTimeString(locale === 'ar' ? 'ar-SA' : 'en-US', opts);
            } catch (e) {
                opts.timeZone = undefined;
                liveClock.textContent = now.toLocaleTimeString(locale === 'ar' ? 'ar-SA' : 'en-US', opts);
            }
        };
        renderClock();
        window.setInterval(renderClock, 1000 * 30);
    }

    if (document.body.dataset.page === 'display') {
        const fullscreenButton = document.querySelector('.js-fullscreen-toggle');
        const syncFullscreenButton = () => {
            if (!fullscreenButton) return;
            const isFullscreen = !!document.fullscreenElement;
            fullscreenButton.textContent = isFullscreen
                ? (fullscreenButton.dataset.labelExit || 'Exit full display')
                : (fullscreenButton.dataset.labelEnter || 'Full display');
            fullscreenButton.setAttribute('aria-pressed', isFullscreen ? 'true' : 'false');
        };

        if (fullscreenButton && document.fullscreenEnabled) {
            fullscreenButton.addEventListener('click', async () => {
                try {
                    if (document.fullscreenElement) {
                        await document.exitFullscreen();
                    } else {
                        await document.documentElement.requestFullscreen();
                    }
                } catch (error) {
                    console.warn('Fullscreen toggle failed', error);
                }
            });
            document.addEventListener('fullscreenchange', syncFullscreenButton);
            syncFullscreenButton();
        } else if (fullscreenButton) {
            fullscreenButton.hidden = true;
        }

        const cards = Array.from(document.querySelectorAll('.announcement-card'));
        const latest = cards[0];
        if (latest && 'speechSynthesis' in window) {
            const announcementKey = latest.dataset.announcementKey || '';
            const storageKey = `hospitalQueue:lastAnnouncement:${locale}`;
            const storedKey = window.localStorage.getItem(storageKey) || '';
            if (announcementKey && announcementKey !== storedKey) {
                const text = locale === 'ar' ? (latest.dataset.announcementAr || '') : (latest.dataset.announcementEn || '');
                const utterance = new SpeechSynthesisUtterance(text);
                utterance.lang = locale === 'ar' ? 'ar-SA' : 'en-US';
                const voices = window.speechSynthesis.getVoices();
                const preferredVoice = voices.find((voice) => voice.lang.toLowerCase().startsWith(locale === 'ar' ? 'ar' : 'en'));
                if (preferredVoice) utterance.voice = preferredVoice;
                window.speechSynthesis.cancel();
                if (text) {
                    window.speechSynthesis.speak(utterance);
                    window.localStorage.setItem(storageKey, announcementKey);
                }
            }
        }

        const autoRefreshSeconds = parseInt(document.querySelector('[data-auto-refresh]')?.dataset.autoRefresh || '0', 10);
        if (autoRefreshSeconds > 0) {
            window.setTimeout(() => window.location.reload(), autoRefreshSeconds * 1000);
        }
    }
});
