/*
 Refactored Dashboard JS (dashboard-refactor.js)
 - Safe DOM access
 - Single DOMContentLoaded handler
 - Delegated event handling for dynamic elements
 - CSS-injected reusable animations & hover (you can move to a .css file later)
 - Modular init functions
 - Chart.js initialization guarded by element checks

 Drop this file into your project and remove the old inline script.
*/

(function () {
    'use strict';

    /* --------------------
       Utilities
    -------------------- */
    const $ = (sel, root = document) => root.querySelector(sel);
    const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
    const on = (el, ev, fn) => el && el.addEventListener(ev, fn);
    const onDelegated = (root, selector, ev, fn) => {
        if (!root) return;
        root.addEventListener(ev, function (e) {
            const match = e.target.closest(selector);
            if (match && root.contains(match)) fn.call(match, e);
        });
    };

    /* --------------------
       Inject lightweight CSS (optional)
       Move this to an external stylesheet in production
    -------------------- */
    const injectCSS = () => {
        const css = `
        /* Button hover */
        button { transition: transform 0.18s ease, opacity 0.18s ease; }
        button:hover { transform: translateY(-2px); }

        /* reusable bounce animation */
        @keyframes _db_bounce { 0%, 20%, 50%, 80%, 100% { transform: translateY(0);} 40% { transform: translateY(-10px);} 60% { transform: translateY(-6px);} }
        ._db-bounce { animation: _db_bounce 1.8s ease-in-out; }

        /* fadeOut row removal */
        @keyframes _db_fadeOut { from { opacity: 1; transform: translateX(0);} to { opacity: 0; transform: translateX(20px); }}
        ._db-fadeOut { animation: _db_fadeOut 0.45s forwards; }

        /* modal active state */
        .modal { display: none; }
        .modal.active { display: block; }

        /* small utility classes */
        .hidden { display: none !important; }
        `;

        const style = document.createElement('style');
        style.setAttribute('data-generated-by', 'dashboard-refactor');
        style.textContent = css;
        document.head.appendChild(style);
    };

    /* --------------------
       Theme (dark mode) handling
    -------------------- */
    const Theme = (() => {
        const KEY = 'darkMode';
        const init = () => {
            const saved = localStorage.getItem(KEY);
            if (saved === 'true') document.body.classList.add('dark-mode');

            const toggle = $('#theme-toggle');
            on(toggle, 'click', () => {
                document.body.classList.toggle('dark-mode');
                localStorage.setItem(KEY, document.body.classList.contains('dark-mode'));
            });
        };
        return { init };
    })();

    /* --------------------
       Sidebar
    -------------------- */
    const Sidebar = (() => {
        const init = () => {
            const toggle = $('.toggle-sidebar');
            on(toggle, 'click', () => {
                const sb = $('.sidebar');
                if (sb) sb.classList.toggle('collapsed');
            });
        };
        return { init };
    })();

    /* --------------------
       Charts (Chart.js) - safe init
    -------------------- */
    const Charts = (() => {
        let appointmentsChart = null;

        const createAppointmentsChart = () => {
            const canvas = $('#appointmentsChart');
            if (!canvas || typeof Chart === 'undefined') return null;

            const ctx = canvas.getContext('2d');
            return new Chart(ctx, {
                type: 'line',
                data: {
                    labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                    datasets: [{
                        label: 'Appointments',
                        data: [85, 112, 94, 126, 142, 98, 75],
                        borderColor: '#2563eb',
                        backgroundColor: 'rgba(37, 99, 235, 0.08)',
                        borderWidth: 3,
                        pointBackgroundColor: '#fff',
                        pointBorderWidth: 2,
                        pointRadius: 5,
                        tension: 0.3,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: {
                        y: { beginAtZero: true, grid: { color: 'rgba(0, 0, 0, 0.05)' } },
                        x: { grid: { display: false } }
                    },
                    animation: { duration: 900, easing: 'easeOutQuart' }
                }
            });
        };

        const init = () => { appointmentsChart = createAppointmentsChart(); };

        const update = (dataset) => {
            if (!appointmentsChart) return;
            appointmentsChart.data.datasets[0].data = dataset;
            appointmentsChart.update();
        };

        return { init, update };
    })();

    /* --------------------
       Animations (cards etc.)
    -------------------- */
    const Animations = (() => {
        const init = () => {
            const cards = $$('.stat-card, .chart-container, .activity-container, .status-card, .analytics-card, .patients-table-container');
            cards.forEach((card, i) => card.style.setProperty('animation-delay', `${i * 0.08}s`));

            // bounce logo and add-patient button if present
            const logo = $('.logo-icon');
            if (logo) setTimeout(() => logo.classList.add('_db-bounce'), 900);

            const addBtn = $('#add-patient-btn');
            if (addBtn) setTimeout(() => addBtn.classList.add('_db-bounce'), 900);
        };
        return { init };
    })();

    /* --------------------
       Messaging Module
    -------------------- */
    const Messaging = (() => {
        const init = () => {
            const module = $('#messaging-module');
            const toggle = $('#messaging-toggle');
            const minimize = $('#minimize-chat');
            const closeBtn = $('#close-chat');

            on(toggle, 'click', () => module && module.classList.toggle('active'));
            on(minimize, 'click', () => module && module.classList.remove('active'));
            on(closeBtn, 'click', () => module && module.classList.remove('active'));

            // close single message buttons (delegated in case messages are dynamic)
            onDelegated(document, '.close-message', 'click', function () {
                const message = this.closest('.message');
                if (!message) return;
                message.style.opacity = '0';
                message.style.transform = 'translateX(20px)';
                setTimeout(() => { if (message) message.style.display = 'none'; }, 320);
            });
        };
        return { init };
    })();

    /* --------------------
       Notifications
    -------------------- */
    const Notifications = (() => {
        const init = () => {
            const tray = $('#notification-tray');
            const toggle = $('#notification-toggle');
            const closeBtn = $('#close-notifications');
            const clearBtn = $('#clear-notifications');

            on(toggle, 'click', () => tray && tray.classList.toggle('active'));
            on(closeBtn, 'click', () => tray && tray.classList.remove('active'));

            on(clearBtn, 'click', () => {
                const unreadItems = $$('.notification-item.unread');
                unreadItems.forEach(item => {
                    item.classList.remove('unread');
                    const dot = item.querySelector('.notification-unread');
                    if (dot) dot.style.display = 'none';
                });
                const badge = $('.notification-badge');
                if (badge) badge.textContent = '0';
            });
        };
        return { init };
    })();

    /* --------------------
       Modal handling
    -------------------- */
    const Modal = (() => {
        let patientModal = null;
        const init = () => {
            patientModal = $('#patient-modal');
            const addBtn = $('#add-patient-btn');
            const closeBtns = $$('.close-modal, #cancel-btn');

            const open = () => { if (!patientModal) return; patientModal.classList.add('active'); document.body.style.overflow = 'hidden'; };
            const close = () => { if (!patientModal) return; patientModal.classList.remove('active'); document.body.style.overflow = 'auto'; };

            on(addBtn, 'click', open);
            closeBtns.forEach(b => on(b, 'click', close));

            // click outside to close
            if (patientModal) {
                patientModal.addEventListener('click', function (e) {
                    if (e.target === patientModal) close();
                });
            }

            // expose for other modules
            return { open, close };
        };

        return { init };
    })();

    /* --------------------
       Chart action buttons (Week / Month toggles)
    -------------------- */
    const ChartActions = (() => {
        const init = () => {
            const container = $('.chart-actions');
            if (!container) return;

            onDelegated(container, 'button', 'click', function () {
                const buttons = $$('.chart-actions button');
                buttons.forEach(b => b.classList.remove('active'));
                this.classList.add('active');

                let data = [85, 112, 94, 126, 142, 98, 75];
                const txt = this.textContent.trim().toLowerCase();
                if (txt === 'week') data = [102, 98, 112, 124, 142, 135, 120];
                else if (txt === 'month') data = [1200, 1320, 1400, 1250, 1480, 1360, 1420];

                Charts.update(data);
            });
        };

        return { init };
    })();

    /* --------------------
       Initialization
    -------------------- */
    document.addEventListener('DOMContentLoaded', function () {
        injectCSS();

        // initialize modules (safe even if elements missing)
        Theme.init();
        Sidebar.init();
        Charts.init();
        Animations.init();
        Messaging.init();
        Notifications.init();
        Modal.init();
        TableActions.init();
        ChartActions.init();

        // Graceful logging in dev -- remove in production
        if (window.location.hash === '#debug') console.info('Dashboard refactor initialized');
    });

})();
// Auto-generate a random userID (prefix + timestamp)
document.getElementById('userID').value = 'HB-' + Math.floor(10000 + Math.random() * 90000) + '-PT';