package com.tt.honeyDue.network

import io.ktor.client.*
import io.ktor.client.engine.js.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.browser.window
import kotlinx.serialization.json.Json

actual fun getLocalhostAddress(): String = "127.0.0.1"

actual fun getDeviceLanguage(): String {
    return window.navigator.language.split("-").firstOrNull() ?: "en"
}

actual fun getDeviceTimezone(): String {
    // Use Intl API to get IANA timezone name (e.g., "America/Los_Angeles")
    return js("Intl.DateTimeFormat().resolvedOptions().timeZone") as String
}

actual fun createHttpClient(): HttpClient {
    return HttpClient(Js) {
        install(ContentNegotiation) {
            json(Json {
                ignoreUnknownKeys = true
                isLenient = true
                prettyPrint = true
            })
        }

        install(Logging) {
            logger = Logger.DEFAULT
            level = LogLevel.ALL
        }

        install(DefaultRequest) {
            headers.append("Accept-Language", getDeviceLanguage())
            headers.append("X-Timezone", getDeviceTimezone())
        }

        // Shared plugins: gzip, retry with backoff, timeouts, token refresh
        installCommonPlugins()
    }
}
