package com.jiooption.trading.webview

import android.content.Context
import android.content.Intent
import android.util.Log
import android.webkit.JavascriptInterface
import android.widget.Toast
import com.jiooption.trading.App
import com.jiooption.trading.ui.deposit.DepositActivity

/**
 * JavaScript ↔ Native bridge for WebView communication
 *
 * JavaScript in the web pages can call these methods via:
 *   BinaryProApp.openDeposit()
 *   BinaryProApp.showToast("message")
 *   etc.
 */
class JsBridge(private val context: Context) {

    companion object {
        const val BRIDGE_NAME = "BinaryProApp"
        private const val TAG = "JsBridge"
    }

    /**
     * Open the native deposit activity (Google Play Billing)
     */
    @JavascriptInterface
    fun openDeposit() {
        Log.d(TAG, "openDeposit called from JS")
        val intent = Intent(context, DepositActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    }

    /**
     * Show a native toast message
     */
    @JavascriptInterface
    fun showToast(message: String) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }

    /**
     * Get the current user's name
     */
    @JavascriptInterface
    fun getUserName(): String {
        return App.getSecureStorage().getUserName()
    }

    /**
     * Get the current user's email
     */
    @JavascriptInterface
    fun getUserEmail(): String {
        return App.getSecureStorage().getUserEmail()
    }

    /**
     * Check if user is logged in
     */
    @JavascriptInterface
    fun isLoggedIn(): Boolean {
        return App.getSecureStorage().isLoggedIn()
    }

    /**
     * Get the app version
     */
    @JavascriptInterface
    fun getAppVersion(): String {
        return try {
            val pInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            pInfo.versionName ?: "1.0.0"
        } catch (e: Exception) {
            "1.0.0"
        }
    }

    /**
     * Get the platform identifier
     */
    @JavascriptInterface
    fun getPlatform(): String {
        return "android"
    }

    /**
     * Log out from the app
     */
    @JavascriptInterface
    fun logout() {
        Log.d(TAG, "logout called from JS")
        App.getSecureStorage().clearAuth()
    }

    /**
     * Share content via native share sheet
     */
    @JavascriptInterface
    fun share(title: String, text: String) {
        val shareIntent = Intent(Intent.ACTION_SEND).apply {
            type = "text/plain"
            putExtra(Intent.EXTRA_SUBJECT, title)
            putExtra(Intent.EXTRA_TEXT, text)
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        context.startActivity(Intent.createChooser(shareIntent, "Share via").apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        })
    }
}
