import { i18n, t } from '../i18n.js'
import { router } from '../router.js'
import { auth } from '../services/auth.js'
import { notificationsService } from '../services/notifications.js'

class AppHeader extends HTMLElement {
    constructor() {
        super()
        this.langDropdownOpen = false
        this.profileDropdownOpen = false
        this.handleOutsideClick = this.handleOutsideClick.bind(this)
        this.handleKeydown = this.handleKeydown.bind(this)
        this.handleScroll = this.handleScroll.bind(this)
    }

    connectedCallback() {
        this.render()
        this.setupEventListeners()
        document.addEventListener('click', this.handleOutsideClick)
        document.addEventListener('keydown', this.handleKeydown)
        window.addEventListener('scroll', this.handleScroll, { passive: true })
        
        // Subscribe to auth changes (only once!)
        this.authUnsubscribe = auth.subscribe(() => {
            this.render()
            this.setupEventListeners()
        })

        this.notifUnsubscribe = notificationsService.subscribe(() => {
            this.updateNotificationBadge()
        })
    }

    disconnectedCallback() {
        document.removeEventListener('click', this.handleOutsideClick)
        document.removeEventListener('keydown', this.handleKeydown)
        window.removeEventListener('scroll', this.handleScroll)
        if (this.authUnsubscribe) this.authUnsubscribe()
        if (this.notifUnsubscribe) this.notifUnsubscribe()
    }

    handleScroll() {
        this.classList.toggle('scrolled', window.scrollY > 10)
    }

    handleOutsideClick() {
        if (this.langDropdownOpen) {
            this.closeLangDropdown()
        }
        if (this.profileDropdownOpen) {
            this.closeProfileDropdown()
        }
    }

    handleKeydown(e) {
        if (!this.langDropdownOpen) return
        
        const items = Array.from(this.querySelectorAll('.dropdown-item'))
        const currentIndex = items.findIndex(item => item === document.activeElement)
        
        switch (e.key) {
            case 'Escape':
                e.preventDefault()
                this.closeLangDropdown()
                this.querySelector('#lang-toggle')?.focus()
                break
            case 'ArrowDown':
                e.preventDefault()
                const nextIndex = currentIndex < items.length - 1 ? currentIndex + 1 : 0
                items[nextIndex]?.focus()
                break
            case 'ArrowUp':
                e.preventDefault()
                const prevIndex = currentIndex > 0 ? currentIndex - 1 : items.length - 1
                items[prevIndex]?.focus()
                break
        }
    }

    closeLangDropdown() {
        this.langDropdownOpen = false
        const langDropdown = this.querySelector('#lang-dropdown')
        const langToggle = this.querySelector('#lang-toggle')
        langDropdown?.classList.remove('open')
        langToggle?.setAttribute('aria-expanded', 'false')
    }

    openLangDropdown() {
        this.langDropdownOpen = true
        const langDropdown = this.querySelector('#lang-dropdown')
        const langToggle = this.querySelector('#lang-toggle')
        langDropdown?.classList.add('open')
        langToggle?.setAttribute('aria-expanded', 'true')
        this.querySelector('#lang-dropdown .dropdown-item.active')?.focus()
    }

    closeProfileDropdown() {
        this.profileDropdownOpen = false
        const dropdown = this.querySelector('#profile-dropdown')
        const toggle = this.querySelector('#profile-toggle')
        dropdown?.classList.remove('open')
        toggle?.setAttribute('aria-expanded', 'false')
    }

    openProfileDropdown() {
        this.profileDropdownOpen = true
        const dropdown = this.querySelector('#profile-dropdown')
        const toggle = this.querySelector('#profile-toggle')
        dropdown?.classList.add('open')
        toggle?.setAttribute('aria-expanded', 'true')
    }

    render() {
        this.innerHTML = /* html */`
            <div class="header-inner container">
                <a href="#/" class="logo" aria-label="dgray.io ${t('common.home')}">
                    <img src="assets/logo-light.svg" alt="dgray.io" class="logo-img logo-light" width="100" height="28">
                    <img src="assets/logo-dark.svg" alt="dgray.io" class="logo-img logo-dark" width="100" height="28">
                </a>
                
                <div class="header-actions">
                    <a href="#/create" class="btn btn-primary btn-create" title="${t('header.createListing')}" data-i18n-title="header.createListing">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                            <line x1="12" y1="5" x2="12" y2="19"></line>
                            <line x1="5" y1="12" x2="19" y2="12"></line>
                        </svg>
                        <span class="btn-create-text" data-i18n="header.createListing">${t('header.createListing')}</span>
                    </a>
                    
                    ${!auth.isLoggedIn() ? `
                        <button 
                            class="btn btn-icon btn-outline" 
                            id="theme-toggle"
                            data-i18n-title="header.toggleTheme"
                            title="${t('header.toggleTheme')}"
                        >
                            <svg class="icon-sun" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="12" r="5"></circle>
                                <line x1="12" y1="1" x2="12" y2="3"></line>
                                <line x1="12" y1="21" x2="12" y2="23"></line>
                                <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
                                <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
                                <line x1="1" y1="12" x2="3" y2="12"></line>
                                <line x1="21" y1="12" x2="23" y2="12"></line>
                                <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
                                <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
                            </svg>
                            <svg class="icon-moon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:none;">
                                <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
                            </svg>
                        </button>
                        
                        <div class="dropdown" id="lang-dropdown">
                            <button 
                                class="btn btn-icon btn-outline" 
                                id="lang-toggle"
                                aria-haspopup="listbox"
                                aria-expanded="${this.langDropdownOpen}"
                                aria-label="${t('header.selectLanguage')}"
                                title="${t('header.selectLanguage')}"
                            >
                                <svg width="20" height="20" viewBox="0 0 16 16" fill="currentColor">
                                    <path d="M8 .25a7.77 7.77 0 0 1 7.75 7.78 7.75 7.75 0 0 1-7.52 7.72h-.25A7.75 7.75 0 0 1 .25 8.24v-.25A7.75 7.75 0 0 1 8 .25zm1.95 8.5h-3.9c.15 2.9 1.17 5.34 1.88 5.5H8c.68 0 1.72-2.37 1.93-5.23zm4.26 0h-2.76c-.09 1.96-.53 3.78-1.18 5.08A6.26 6.26 0 0 0 14.17 9zm-9.67 0H1.8a6.26 6.26 0 0 0 3.94 5.08 12.59 12.59 0 0 1-1.16-4.7l-.03-.38zm1.2-6.58-.12.05a6.26 6.26 0 0 0-3.83 5.03h2.75c.09-1.83.48-3.54 1.06-4.81zm2.25-.42c-.7 0-1.78 2.51-1.94 5.5h3.9c-.15-2.9-1.18-5.34-1.89-5.5h-.07zm2.28.43.03.05a12.95 12.95 0 0 1 1.15 5.02h2.75a6.28 6.28 0 0 0-3.93-5.07z"></path>
                                </svg>
                            </button>
                            <div class="dropdown-menu" role="listbox" aria-label="${t('header.selectLanguage')}">
                                ${i18n.getSupportedLocales().map(locale => `
                                    <button 
                                        class="dropdown-item ${locale === i18n.getLocale() ? 'active' : ''}" 
                                        data-locale="${locale}"
                                        role="option"
                                        aria-selected="${locale === i18n.getLocale()}"
                                    >
                                        ${i18n.getLocaleDisplayName(locale)}
                                    </button>
                                `).join('')}
                            </div>
                        </div>
                    ` : ''}
                    
                    ${auth.isLoggedIn() ? `
                        <a href="#/notifications" class="btn btn-icon btn-outline notification-bell" title="${t('notifications.title')}">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path>
                                <path d="M13.73 21a2 2 0 0 1-3.46 0"></path>
                            </svg>
                            ${notificationsService.unreadCount > 0 ? `<span class="notification-badge">${notificationsService.unreadCount}</span>` : ''}
                        </a>
                        <div class="dropdown" id="profile-dropdown">
                            <button 
                                class="btn btn-icon btn-outline" 
                                id="profile-toggle"
                                aria-haspopup="menu"
                                aria-expanded="${this.profileDropdownOpen}"
                                aria-label="${t('header.profile')}"
                                title="${t('header.profile')}"
                            >
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                    <circle cx="12" cy="7" r="4"></circle>
                                </svg>
                            </button>
                            <div class="dropdown-menu dropdown-menu-right" role="menu">
                                <a href="#/my-listings" class="dropdown-item" role="menuitem">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <rect x="3" y="3" width="7" height="7"></rect>
                                        <rect x="14" y="3" width="7" height="7"></rect>
                                        <rect x="14" y="14" width="7" height="7"></rect>
                                        <rect x="3" y="14" width="7" height="7"></rect>
                                    </svg>
                                    ${t('profile.myListings')}
                                </a>
                                <a href="#/messages" class="dropdown-item" role="menuitem">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                                    </svg>
                                    ${t('profile.messages')}
                                </a>
                                <a href="#/favorites" class="dropdown-item" role="menuitem">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                                    </svg>
                                    ${t('profile.favorites')}
                                </a>
                                <div class="dropdown-divider"></div>
                                <a href="#/settings" class="dropdown-item" role="menuitem">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <circle cx="12" cy="12" r="3"></circle>
                                        <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
                                    </svg>
                                    ${t('profile.settings')}
                                </a>
                                <button class="dropdown-item dropdown-item-danger" id="logout-btn" role="menuitem">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                                        <polyline points="16 17 21 12 16 7"></polyline>
                                        <line x1="21" y1="12" x2="9" y2="12"></line>
                                    </svg>
                                    ${t('auth.logout')}
                                </button>
                            </div>
                        </div>
                    ` : `
                        <button class="btn btn-outline btn-login" id="login-btn" title="${t('auth.login')}">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                <circle cx="12" cy="7" r="4"></circle>
                            </svg>
                            <span class="btn-login-text">${t('auth.login')}</span>
                        </button>
                    `}
                </div>
            </div>
        `
    }

    setupEventListeners() {
        const themeToggle = this.querySelector('#theme-toggle')
        themeToggle?.addEventListener('click', () => this.toggleTheme())

        const langDropdown = this.querySelector('#lang-dropdown')
        const langToggle = this.querySelector('#lang-toggle')
        
        langToggle?.addEventListener('click', (e) => {
            e.stopPropagation()
            if (this.langDropdownOpen) {
                this.closeLangDropdown()
            } else {
                this.openLangDropdown()
            }
        })

        langDropdown?.querySelectorAll('[data-locale]').forEach(btn => {
            btn.addEventListener('click', async () => {
                await i18n.setLocale(btn.dataset.locale)
            })
        })

        // Login button
        const loginBtn = this.querySelector('#login-btn')
        loginBtn?.addEventListener('click', () => {
            const authModal = document.querySelector('auth-modal')
            if (authModal) {
                authModal.show('login')
            }
        })

        // Profile dropdown
        const profileDropdown = this.querySelector('#profile-dropdown')
        const profileToggle = this.querySelector('#profile-toggle')
        
        profileToggle?.addEventListener('click', (e) => {
            e.stopPropagation()
            if (this.profileDropdownOpen) {
                this.closeProfileDropdown()
            } else {
                this.openProfileDropdown()
            }
        })

        // Close dropdown when clicking menu items
        profileDropdown?.querySelectorAll('.dropdown-item').forEach(item => {
            item.addEventListener('click', () => {
                this.closeProfileDropdown()
            })
        })

        // Logout button
        const logoutBtn = this.querySelector('#logout-btn')
        logoutBtn?.addEventListener('click', async () => {
            await auth.logout()
            router.navigate('/')
        })

        this.updateThemeIcon()
    }

    toggleTheme() {
        const currentTheme = document.documentElement.dataset.theme
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
        
        let newTheme
        if (!currentTheme) {
            newTheme = prefersDark ? 'light' : 'dark'
        } else if (currentTheme === 'dark') {
            newTheme = 'light'
        } else {
            newTheme = 'dark'
        }
        
        document.documentElement.dataset.theme = newTheme
        localStorage.setItem('theme', newTheme)
        this.updateThemeIcon()
    }

    updateThemeIcon() {
        const theme = document.documentElement.dataset.theme
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
        const isDark = theme === 'dark' || (!theme && prefersDark)
        
        const sunIcon = this.querySelector('.icon-sun')
        const moonIcon = this.querySelector('.icon-moon')
        
        if (sunIcon && moonIcon) {
            sunIcon.style.display = isDark ? 'block' : 'none'
            moonIcon.style.display = isDark ? 'none' : 'block'
        }
    }

    updateNotificationBadge() {
        const bell = this.querySelector('.notification-bell')
        if (!bell) return

        const existing = bell.querySelector('.notification-badge')
        if (notificationsService.unreadCount > 0) {
            if (existing) {
                existing.textContent = notificationsService.unreadCount
            } else {
                const badge = document.createElement('span')
                badge.className = 'notification-badge'
                badge.textContent = notificationsService.unreadCount
                bell.appendChild(badge)
            }
        } else if (existing) {
            existing.remove()
        }
    }

    updateTranslations() {
        this.render()
        this.setupEventListeners()
    }
}

customElements.define('app-header', AppHeader)
