package com.freeexile.arpg import android.app.Activity import android.os.Build import android.webkit.JavascriptInterface import android.webkit.WebView import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.json.JSONObject /** * High-performance WebKit JavaScript Native Bridge Interface for FreeExile. * Exposed to JavaScript under `window.NativeBridge`. */ class NativeBridgeInterface( private val activity: Activity, private val webView: WebView, private val hapticManager: HapticFeedbackManager, private val billingManager: PlayBillingManager, private val integrityManager: PlayIntegrityManager, private val scope: CoroutineScope ) { /** * Triggers tactile vibration using Android VibrationEffect. */ @JavascriptInterface fun triggerHaptic(type: String) { hapticManager.triggerHaptic(type) } /** * Requests Google Play Integrity API token with cryptographic nonce. * Evaluates `window.onPlayIntegrityToken(resultJson)` upon completion. */ @JavascriptInterface fun requestPlayIntegrityToken(nonce: String) { scope.launch(Dispatchers.IO) { val result = integrityManager.requestToken(nonce) val json = JSONObject() if (result.isSuccess) { json.put("success", true) json.put("token", result.getOrNull()) json.put("nonce", nonce) } else { json.put("success", false) json.put("error", result.exceptionOrNull()?.message ?: "Integrity check failed") } scope.launch(Dispatchers.Main) { val script = "if (window.onPlayIntegrityToken) { window.onPlayIntegrityToken(${json}); }" webView.evaluateJavascript(script, null) } } } /** * Initiates Google Play Billing purchase flow for the specified in-app SKU. */ @JavascriptInterface fun launchBillingFlow(sku: String) { activity.runOnUiThread { billingManager.launchBillingFlow(activity, sku) } } /** * Returns hardware specifications and OS version info for graphics performance tuning. */ @JavascriptInterface fun getDeviceInfo(): String { val info = JSONObject() info.put("platform", "Android") info.put("model", Build.MODEL) info.put("manufacturer", Build.MANUFACTURER) info.put("osVersion", Build.VERSION.RELEASE) info.put("sdkInt", Build.VERSION.SDK_INT) return info.toString() } /** * Helper to dispatch generic JSON messages from native layers back to JavaScript. */ fun dispatchToWeb(callbackName: String, jsonPayload: String) { activity.runOnUiThread { val script = "if (window.$callbackName) { window.$callbackName($jsonPayload); }" webView.evaluateJavascript(script, null) } } }