package com.fmdxconnector

import android.annotation.SuppressLint
import android.net.Uri
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView

/**
 * Vollbild-WebView-Overlay für https://servers.fmdx.org
 * - visible = true  → WebView sichtbar & klickbar
 * - visible = false → WebView unsichtbar & blockiert keine Touches mehr
 *
 * Bei Klick auf "Connect" wird NICHT der Browser geöffnet, sondern
 * onServerSelected(url, name) mit Webserver-URL und Name (z.B. "FM Monitor Suedniedersachsen").
 */
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun ServersMapOverlay(
    modifier: Modifier = Modifier,
    visible: Boolean,
    onServerSelected: (url: String, name: String) -> Unit
) {
    AndroidView(
        modifier = modifier,
        factory = { context ->
            WebView(context).apply {
                layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
                settings.javaScriptEnabled = true
                settings.domStorageEnabled = true

                // Bridge Android <-> JavaScript
                addJavascriptInterface(object {
                    @JavascriptInterface
                    fun onConnectClicked(url: String, name: String) {
                        // Sicher ins UI-Thread posten
                        post {
                            onServerSelected(url, name)
                        }
                    }
                }, "AndroidConnector")

                webViewClient = object : WebViewClient() {

                    override fun onPageFinished(view: WebView?, url: String?) {
                        super.onPageFinished(view, url)

                        // JS injizieren, um den "Connect"-Button zu hooken
                        view?.evaluateJavascript(
                            """
                            (function() {
                                function hookConnect() {
                                    try {
                                        var btn = document.querySelector('.panel-current-connect .current-tuner-link.button');
                                        if (!btn) return;
                                        if (btn._fmdxHooked) return;
                                        btn._fmdxHooked = true;
                                        
                                        btn.addEventListener('click', function(e) {
                                            e.preventDefault();
                                            var url = btn.href || '';
                                            var nameEl = document.getElementById('current-tuner-name');
                                            var name = nameEl ? nameEl.textContent.trim() : '';
                                            if (window.AndroidConnector && AndroidConnector.onConnectClicked) {
                                                AndroidConnector.onConnectClicked(url, name);
                                            }
                                        }, true);
                                    } catch (e) {
                                        console.log('FMDXConnector hook error', e);
                                    }
                                }
                                hookConnect();
                            })();
                            """.trimIndent(),
                            null
                        )
                    }

                    override fun shouldOverrideUrlLoading(
                        view: WebView?,
                        request: WebResourceRequest?
                    ): Boolean {
                        // Andere Links (Doku, GitHub etc.) normal lassen
                        val url = request?.url?.toString() ?: return false
                        val uri = try { Uri.parse(url) } catch (_: Exception) { null }
                        val host = uri?.host ?: return false
                        // alles, was nicht servers.fmdx.org ist, normal dem System überlassen
                        return !host.contains("servers.fmdx.org")
                    }

                    @Suppress("OverridingDeprecatedMember")
                    override fun shouldOverrideUrlLoading(
                        view: WebView?,
                        url: String?
                    ): Boolean {
                        val u = url ?: return false
                        val uri = try { Uri.parse(u) } catch (_: Exception) { null }
                        val host = uri?.host ?: return false
                        return !host.contains("servers.fmdx.org")
                    }
                }

                webChromeClient = WebChromeClient()

                loadUrl("https://servers.fmdx.org")
            }
        },
        update = { webView ->
            // Sichtbarkeit steuern: GONE blockiert keine Touches
            webView.visibility = if (visible) View.VISIBLE else View.GONE

            if (webView.url == null ||
                !webView.url!!.startsWith("https://servers.fmdx.org")
            ) {
                webView.loadUrl("https://servers.fmdx.org")
            }
        }
    )
}
