class MainNavbar extends HTMLElement { constructor() { super(); this.currentPage = 'today'; } connectedCallback() { this.attachShadow({ mode: 'open' }); this.render(); this.setupEventListeners(); } render() { this.shadowRoot.innerHTML = ` `; } setupEventListeners() { try { const navItems = this.shadowRoot.querySelectorAll('.nav-item'); // Set active page based on current URL const currentPath = window.location.pathname; const pageMap = { '/index.html': 'today', '/sleep.html': 'sleep', '/activity.html': 'activity', '/nutrition.html': 'nutrition', '/profile.html': 'profile' }; const currentPage = pageMap[currentPath] || 'today'; this.setActivePage(currentPage); navItems.forEach(item => { item.addEventListener('click', (e) => { try { const page = item.dataset.page; // Dispatch custom event for other components this.dispatchEvent(new CustomEvent('page-change', { detail: { page }, bubbles: true, composed: true })); // Log navigation (in production, this would be analytics) console.log(`เปลี่ยนหน้าไปที่: ${page}`); } catch (error) { console.error('Navigation error:', error); } }); }); } catch (error) { console.error('Setup navbar listeners error:', error); } } setActivePage(page) { try { const navItems = this.shadowRoot.querySelectorAll('.nav-item'); navItems.forEach(item => { if (item.dataset.page === page) { item.classList.add('active'); } else { item.classList.remove('active'); } }); this.currentPage = page; } catch (error) { console.error('Set active page error:', error); } } // Public method to set page from outside navigate(page) { this.setActivePage(page); } // Auto-detect current page on first load detectCurrentPage() { const currentPath = window.location.pathname; const pageMap = { '/index.html': 'today', '/sleep.html': 'sleep', '/activity.html': 'activity', '/nutrition.html': 'nutrition', '/profile.html': 'profile' }; const currentPage = pageMap[currentPath] || 'today'; this.setActivePage(currentPage); } connectedCallback() { this.attachShadow({ mode: 'open' }); this.currentPage = 'today'; this.render(); this.setupEventListeners(); this.detectCurrentPage(); // Auto-detect current page } } customElements.define('main-navbar', MainNavbar);