package com.example.design_system.util

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import java.util.Stack

@SuppressLint("StaticFieldLeak")
object WebViewManager {

    private const val POOL_SIZE = 1
    private val webViewPool = Stack<WebView>()

    fun preload(context: Context) {
        if (webViewPool.isEmpty()) {
            repeat(POOL_SIZE) {
                val webView = createWebView(context)
                webViewPool.push(webView)
            }
        }
    }

    fun getWebView(context: Context): WebView {
        return if (webViewPool.isNotEmpty()) {
            webViewPool.pop()
        } else {
            createWebView(context)
        }
    }

    fun releaseWebView(webView: WebView) {
        if (webViewPool.size < POOL_SIZE) {
            webViewPool.push(webView)
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun createWebView(context: Context): WebView {
        return WebView(context).apply {
            setLayerType(View.LAYER_TYPE_HARDWARE, null)
            settings.apply {
                javaScriptEnabled = true
                domStorageEnabled = true
                databaseEnabled = true
                cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
                loadsImagesAutomatically = true
                allowFileAccess = false
                useWideViewPort = true
                loadWithOverviewMode = true
                mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
                setSupportZoom(false)
                builtInZoomControls = false
                displayZoomControls = false
                userAgentString = "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome/120.0 Mobile Safari/537.36"
            }
        }
    }
}