const BTN_BASE = 'env-btn px-5 py-2 font-black uppercase text-xs tracking-widest transition-all cursor-pointer '

function getEnvs(host) {
    return {
        sandbox: {
            prefix: '/api/sandbox',
            baseUrl: host + '/api/sandbox',
            color: 'text-orange-400',
            btnBg: 'bg-orange-500',
            desc: 'Environnement de test. Les donnees ne sont pas modifiees.',
        },
        live: {
            prefix: '/api/live',
            baseUrl: host + '/api/live',
            color: 'text-green-400',
            btnBg: 'bg-green-600',
            desc: 'Environnement de production. Les donnees sont reelles.',
        },
    }
}

function switchEnv(env, envs) {
    const config = envs[env]
    if (!config) return

    document.querySelectorAll('.env-btn').forEach(btn => {
        const isActive = btn.dataset.env === env
        btn.className = BTN_BASE + (isActive ? config.btnBg + ' text-white' : 'bg-gray-800 text-gray-400 hover:text-white')
    })

    const baseUrlEl = document.getElementById('env-base-url')
    if (baseUrlEl) baseUrlEl.textContent = config.baseUrl

    const descEl = document.getElementById('env-description')
    if (descEl) descEl.textContent = config.desc

    document.querySelectorAll('.api-env-prefix').forEach(el => {
        el.textContent = config.prefix
        el.className = 'api-env-prefix ' + config.color
    })
}

export function initApiEnvSwitcher() {
    const switcher = document.getElementById('env-switcher')
    if (!switcher) return

    const hostEl = document.querySelector('[data-host]')
    const host = hostEl ? hostEl.dataset.host : globalThis.location.origin
    const envs = getEnvs(host)

    document.querySelectorAll('.env-btn').forEach(btn => {
        btn.addEventListener('click', () => switchEnv(btn.dataset.env, envs))
    })
}
