/* Hostiva v6 — unified layout with mode switching (STR / Hotel / Both) */
(function () {
    'use strict';
    const MODE_KEY = 'hostiva_mode';
    const getMode = () => localStorage.getItem(MODE_KEY) || 'both';
    const setMode = (m) => {
        localStorage.setItem(MODE_KEY, m);
        document.body.setAttribute('data-mode', m);
        document.querySelectorAll('.mode-toggle .mt-btn').forEach(b => {
            b.classList.toggle('active', b.dataset.mode === m);
        });
    };

    const menuItems = [
        { group: 'Main' },
        { label: 'Dashboard', icon: 'fa-gauge-high', href: 'dashboard.html', match: 'dashboard' },
        { label: 'Front Desk', icon: 'fa-concierge-bell', href: 'front-desk.html', match: 'front-desk', mode: 'hotel' },
        { label: 'Calendar', icon: 'fa-calendar', href: 'calendar.html', match: 'calendar' },
        { label: 'Bookings', icon: 'fa-bookmark', href: 'bookings.html', match: 'bookings' },
        { label: 'Inbox', icon: 'fa-inbox', href: 'inbox.html', match: 'inbox' },
        { group: 'Inventory' },
        { label: 'Properties', icon: 'fa-building', href: 'properties.html', match: 'properties' },
        { label: 'Room Types', icon: 'fa-bed', href: 'room-types.html', match: 'room-types', mode: 'hotel' },
        { label: 'Rooms', icon: 'fa-door-open', href: 'rooms.html', match: 'rooms', mode: 'hotel' },
        { label: 'Housekeeping', icon: 'fa-broom', href: 'housekeeping.html', match: 'housekeeping', mode: 'hotel' },
        { label: 'Channels', icon: 'fa-share-nodes', href: 'channels.html', match: 'channels', mode: 'str' },
        { group: 'Finance' },
        { label: 'Finance', icon: 'fa-money-bill', href: 'finance.html', match: 'finance' },
        { label: 'Reports', icon: 'fa-chart-line', href: 'reports.html', match: 'reports' },
        { group: 'Operations' },
        { label: 'Tickets', icon: 'fa-ticket', href: 'tickets.html', match: 'tickets' },
        { label: 'Automations', icon: 'fa-bolt', href: 'automations.html', match: 'automations' },
        { label: 'Activity', icon: 'fa-clock-rotate-left', href: 'activity.html', match: 'activity' },
        { group: 'Admin' },
        { label: 'Team', icon: 'fa-users', href: 'users.html', match: 'users' },
        { label: 'Settings', icon: 'fa-gear', href: 'settings.html', match: 'settings' },
    ];

    function currentPage() {
        const path = window.location.pathname.split('/').pop() || 'dashboard.html';
        return path.replace('.html', '');
    }
    function initials(name) {
        if (!name) return 'U';
        return name.split(' ').map(p => p[0]).slice(0, 2).join('').toUpperCase();
    }

    function buildSidebar(cur, mode) {
        let html = `<div class="sidebar" id="hostivaSidebar">
            <div class="sidebar-brand"><div class="logo">H</div><div class="name">Hostiva<small>Property Suite</small></div></div>
            <div class="mode-toggle">
                <div class="mt-btn ${mode==='str'?'active':''}" data-mode="str">STR</div>
                <div class="mt-btn ${mode==='hotel'?'active':''}" data-mode="hotel">Hotel</div>
                <div class="mt-btn ${mode==='both'?'active':''}" data-mode="both">Both</div>
            </div>`;
        let inGroup = false;
        for (const it of menuItems) {
            if (it.group) {
                if (inGroup) html += '</ul>';
                html += `<div class="sidebar-group">${it.group}</div><ul class="sidebar-menu">`;
                inGroup = true;
            } else {
                const cls = it.mode === 'hotel' ? 'mode-hotel' : (it.mode === 'str' ? 'mode-str' : '');
                const active = (it.match === cur) ? 'active' : '';
                html += `<li class="${cls} ${active}"><a href="${it.href}" class="${active}"><i class="fa-solid ${it.icon}"></i><span>${it.label}</span></a></li>`;
            }
        }
        if (inGroup) html += '</ul>';
        html += '</div>';
        return html;
    }

    function buildTopbar(me) {
        const pageTitle = document.title.replace(' · Hostiva', '') || 'Dashboard';
        return `<header class="topbar">
            <button class="menu-toggle" onclick="document.getElementById('hostivaSidebar').classList.toggle('open')"><i class="fa-solid fa-bars"></i></button>
            <div class="page-title-bar">${pageTitle}</div>
            <div class="topbar-actions">
                <button class="icon-btn" title="Notifications" onclick="location.href='inbox.html'">
                    <i class="fa-regular fa-bell"></i><span class="dot" id="notifDot" style="display:none"></span>
                </button>
                <div class="user-chip" onclick="window.Hostiva && window.Hostiva.logoutMenu()">
                    <div class="avatar">${initials(me.name)}</div>
                    <div class="info"><span class="name">${me.name || 'Guest'}</span><span class="role">${me.role_name || 'staff'}</span></div>
                </div>
            </div>
        </header>`;
    }

    function buildLayout() {
        const me = window.HOSTIVA_USER || {};
        const cur = currentPage();
        const mode = getMode();
        const sidebarHtml = buildSidebar(cur, mode);
        const topbarHtml = buildTopbar(me);
        const container = document.createElement('div');
        container.className = 'app-layout';
        container.innerHTML = sidebarHtml + `<div class="main">${topbarHtml}<main class="content" id="hostivaContent"></main></div>`;
        const existingContent = document.body.querySelector('main, .content, .page-content, #app-shell');
        const innerHtml = existingContent ? existingContent.innerHTML : document.body.innerHTML;
        document.body.innerHTML = '';
        document.body.appendChild(container);
        document.getElementById('hostivaContent').innerHTML = innerHtml;
        setMode(mode);
        document.querySelectorAll('.mode-toggle .mt-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                setMode(btn.dataset.mode);
                window.dispatchEvent(new Event('hostiva:modeChange'));
            });
        });
        document.dispatchEvent(new CustomEvent('hostiva:ready'));
    }

    async function loadUserAndBuild() {
        const path = window.location.pathname;
        if (path.includes('login') || path.includes('register')) {
            buildLayout(); return;
        }
        try {
            const r = await fetch('../api/?r=auth/me', { credentials: 'same-origin' });
            const j = await r.json();
            if (j.success && j.data) {
                window.HOSTIVA_USER = j.data;
            } else {
                window.location.href = 'login.html'; return;
            }
        } catch (e) {
            console.warn('auth check failed', e);
        }
        buildLayout();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', loadUserAndBuild);
    } else {
        loadUserAndBuild();
    }

    window.Hostiva = window.Hostiva || {};
    window.Hostiva.logoutMenu = async function () {
        if (!confirm('Log out?')) return;
        try { await fetch('../api/?r=auth/logout', { method: 'POST', credentials: 'same-origin' }); } catch {}
        window.location.href = 'login.html';
    };
})();
