/**
 * Cincinnati Fire Department Portal — Core JavaScript
 * Sidebar toggle, user menu, modal system, API helper.
 */
(function() {
    'use strict';

    const P = window.CFD_PORTAL || {};

    // ─── Sidebar Toggle ─────────────────────────────────
    const sidebar = document.getElementById('sidebar');
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebarOverlay = document.getElementById('sidebarOverlay');

    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', () => {
            sidebar.classList.toggle('open');
            sidebarOverlay.classList.toggle('open');
        });
    }
    if (sidebarOverlay) {
        sidebarOverlay.addEventListener('click', () => {
            sidebar.classList.remove('open');
            sidebarOverlay.classList.remove('open');
        });
    }

    // ─── User Dropdown Menu ─────────────────────────────
    const userMenuTrigger = document.getElementById('userMenuTrigger');
    const userDropdown = document.getElementById('userDropdown');

    if (userMenuTrigger && userDropdown) {
        userMenuTrigger.addEventListener('click', (e) => {
            e.stopPropagation();
            userDropdown.classList.toggle('open');
        });
        document.addEventListener('click', () => {
            userDropdown.classList.remove('open');
        });
    }

    // ─── API Helper ─────────────────────────────────────
    window.portalAPI = async function(endpoint, options = {}) {
        const url = P.apiPath + '/' + endpoint;
        const config = {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': P.csrfToken
            },
            ...options
        };

        if (options.body instanceof FormData) {
            config.body.append('csrf_token', P.csrfToken);
        } else if (options.method === 'POST' && options.body) {
            config.headers['Content-Type'] = 'application/json';
        }

        try {
            const resp = await fetch(url, config);
            if (resp.status === 401) {
                window.location.href = 'index.php?expired=1';
                return null;
            }
            return await resp.json();
        } catch (err) {
            console.error('API call failed:', endpoint, err);
            return null;
        }
    };

    // ─── Modal System ───────────────────────────────────
    window.openModal = function(id) {
        const modal = document.getElementById(id);
        if (modal) modal.classList.add('open');
    };
    window.closeModal = function(id) {
        const modal = document.getElementById(id);
        if (modal) modal.classList.remove('open');
    };

    // Close modals on overlay click
    document.querySelectorAll('.modal-overlay').forEach(overlay => {
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) overlay.classList.remove('open');
        });
    });

    // Close modals on Escape
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            document.querySelectorAll('.modal-overlay.open').forEach(m => m.classList.remove('open'));
            userDropdown && userDropdown.classList.remove('open');
        }
    });

    // ─── Tab Switching ──────────────────────────────────
    window.switchTab = function(tabGroup, tabId) {
        const group = document.querySelectorAll(`[data-tab-group="${tabGroup}"]`);
        const contents = document.querySelectorAll(`[data-tab-content="${tabGroup}"]`);

        group.forEach(btn => btn.classList.remove('active'));
        contents.forEach(content => content.classList.remove('active'));

        const activeBtn = document.querySelector(`[data-tab-group="${tabGroup}"][data-tab="${tabId}"]`);
        const activeContent = document.getElementById(tabId);

        if (activeBtn) activeBtn.classList.add('active');
        if (activeContent) activeContent.classList.add('active');
    };

    // ─── Header Clock + Holiday ─────────────────────────
    const dateEl = document.getElementById('headerDate');
    const timeEl = document.getElementById('headerTime');
    const holidayEl = document.getElementById('headerHoliday');

    function getFederalHolidays(year) {
        const holidays = {};
        // Fixed-date holidays
        holidays[`${year}-01-01`] = "New Year's Day";
        holidays[`${year}-06-19`] = 'Juneteenth';
        holidays[`${year}-07-04`] = 'Independence Day';
        holidays[`${year}-11-11`] = "Veterans Day";
        holidays[`${year}-12-25`] = 'Christmas Day';

        // MLK Day: 3rd Monday of January
        holidays[nthWeekday(year, 0, 1, 3)] = 'MLK Jr. Day';
        // Presidents' Day: 3rd Monday of February
        holidays[nthWeekday(year, 1, 1, 3)] = "Presidents' Day";
        // Memorial Day: last Monday of May
        holidays[lastWeekday(year, 4, 1)] = 'Memorial Day';
        // Labor Day: 1st Monday of September
        holidays[nthWeekday(year, 8, 1, 1)] = 'Labor Day';
        // Columbus Day: 2nd Monday of October
        holidays[nthWeekday(year, 9, 1, 2)] = 'Columbus Day';
        // Thanksgiving: 4th Thursday of November
        holidays[nthWeekday(year, 10, 4, 4)] = 'Thanksgiving';

        return holidays;
    }

    function nthWeekday(year, month, dayOfWeek, n) {
        let count = 0;
        for (let d = 1; d <= 31; d++) {
            const dt = new Date(year, month, d);
            if (dt.getMonth() !== month) break;
            if (dt.getDay() === dayOfWeek) {
                count++;
                if (count === n) return fmt(dt);
            }
        }
        return '';
    }

    function lastWeekday(year, month, dayOfWeek) {
        let last = null;
        for (let d = 1; d <= 31; d++) {
            const dt = new Date(year, month, d);
            if (dt.getMonth() !== month) break;
            if (dt.getDay() === dayOfWeek) last = dt;
        }
        return last ? fmt(last) : '';
    }

    function fmt(dt) {
        const y = dt.getFullYear();
        const m = String(dt.getMonth() + 1).padStart(2, '0');
        const d = String(dt.getDate()).padStart(2, '0');
        return `${y}-${m}-${d}`;
    }

    function updateClock() {
        const now = new Date();

        if (dateEl) {
            dateEl.textContent = now.toLocaleDateString('en-US', {
                weekday: 'long', month: 'long', day: 'numeric', year: 'numeric'
            });
        }

        if (timeEl) {
            timeEl.textContent = now.toLocaleTimeString('en-US', {
                hour: 'numeric', minute: '2-digit', second: '2-digit'
            });
        }

        if (holidayEl) {
            const todayStr = fmt(now);
            const holidays = getFederalHolidays(now.getFullYear());
            const holiday = holidays[todayStr];
            if (holiday) {
                holidayEl.textContent = holiday;
                holidayEl.style.display = '';
            } else {
                holidayEl.textContent = '';
                holidayEl.style.display = 'none';
            }
        }
    }

    updateClock();
    setInterval(updateClock, 1000);

    // ─── River Level ────────────────────────────────────
    const riverEl = document.getElementById('riverLevel');
    const riverValueEl = document.getElementById('riverValue');

    async function fetchRiver() {
        if (!riverEl || !riverValueEl) return;
        try {
            const data = await window.portalAPI('river.php');
            if (!data || data.error) return;

            riverValueEl.textContent = data.level.toFixed(1);
            riverEl.dataset.status = data.status;
            riverEl.title = `${data.site_name}: ${data.level} ft — ${data.status_label}`;
        } catch (e) {}
    }

    fetchRiver();
    setInterval(fetchRiver, 900000); // 15 min

    // ─── Format Helpers ─────────────────────────────────
    window.formatTime = function(date) {
        return new Date(date).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
    };

    window.formatDate = function(date) {
        return new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
    };

    window.timeAgo = function(date) {
        const seconds = Math.floor((Date.now() - new Date(date).getTime()) / 1000);
        if (seconds < 60) return 'just now';
        if (seconds < 3600) return Math.floor(seconds / 60) + 'm ago';
        if (seconds < 86400) return Math.floor(seconds / 3600) + 'h ago';
        return Math.floor(seconds / 86400) + 'd ago';
    };

})();
