import { t } from '../i18n.js'
import { getXmrRates, formatFiat } from '../services/currency.js'

class AppFooter extends HTMLElement {
    constructor() {
        super()
        this.rates = null
        this.handleCurrencyChange = this.handleCurrencyChange.bind(this)
    }

    async connectedCallback() {
        this.render()
        await this.loadXmrRates()
        window.addEventListener('currency-changed', this.handleCurrencyChange)
    }

    disconnectedCallback() {
        window.removeEventListener('currency-changed', this.handleCurrencyChange)
    }

    handleCurrencyChange() {
        this.updateRateDisplay()
    }

    getCurrency() {
        return localStorage.getItem('dgray_currency') || 'USD'
    }

    async loadXmrRates() {
        try {
            this.rates = await getXmrRates()
            this.updateRateDisplay()
        } catch (e) {
            console.error('Failed to load XMR rates:', e)
        }
    }

    updateRateDisplay() {
        const rateEl = this.querySelector('.xmr-rate')
        if (rateEl && this.rates) {
            const currency = this.getCurrency()
            const rate = this.rates[currency] || this.rates.USD
            rateEl.textContent = `1 XMR ≈ ${formatFiat(rate, currency)}`
            rateEl.classList.add('loaded')
        }
    }

    render() {
        const year = new Date().getFullYear()
        
        this.innerHTML = /* html */`
            <div class="footer-inner container">
                <p class="footer-copyright">
                    &copy; ${year} dgray.io - <span data-i18n="footer.rights">${t('footer.rights')}</span>
                    <span class="footer-swiss">🇨🇭 Made in Switzerland</span>
                </p>
                <span class="xmr-rate" title="CoinGecko">1 XMR ≈ ...</span>
                <nav class="footer-links">
                    <a href="#/about" data-i18n="footer.about">${t('footer.about')}</a>
                    <a href="#/privacy" data-i18n="footer.privacy">${t('footer.privacy')}</a>
                    <a href="#/terms" data-i18n="footer.terms">${t('footer.terms')}</a>
                    <a href="#/contact" data-i18n="footer.contact">${t('footer.contact')}</a>
                </nav>
            </div>
        `
    }

    updateTranslations() {
        this.render()
        if (this.rates) this.updateRateDisplay()
    }
}

customElements.define('app-footer', AppFooter)
