package com.dtourolle.jellytau

import android.app.Activity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat

/**
 * Hides and restores the Android system bars for full-screen video.
 *
 * TRACES: UR-066 | DR-157
 *
 * ## Why the web layer cannot do this
 *
 * `document.documentElement.requestFullscreen()` is the only fullscreen control
 * the frontend has, and inside an Android WebView it does nothing to the
 * *Activity*: it expands the fullscreen element within the web viewport and
 * leaves the window exactly as it was. Combined with `enableEdgeToEdge()` — which
 * MainActivity must call, and which SDK 36 makes non-optional — the WebView
 * already spans the whole window, so "fullscreen" was a no-op that changed
 * nothing on screen while the status bar and navigation/gesture bar stayed
 * painted over the video.
 *
 * Hiding them requires `WindowInsetsControllerCompat` on the Activity's window,
 * which is reachable only from native code. Hence this bridge.
 *
 * ## Behaviour
 *
 * [enter] hides both bars and selects `BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE`, so
 * a swipe from either edge brings them back *transiently* — over the video,
 * auto-hiding again — rather than permanently resizing the window mid-playback.
 * That is the standard behaviour for immersive video and keeps the system's own
 * back/home gestures reachable.
 *
 * [exit] restores them. It must be called when leaving fullscreen **and** when
 * the player is torn down, or the bars stay hidden on the library screens behind
 * it.
 *
 * Both must run on the main thread; the callers in MainActivity post them there,
 * since `@JavascriptInterface` methods arrive on a WebView binder thread.
 *
 * Note the `--jt-inset-*` custom properties follow automatically: hiding the bars
 * fires the decor view's inset listener with zeroes, so [WindowInsetsBridge]
 * republishes them and the player's control layer stops reserving space it no
 * longer needs.
 */
object ImmersiveModeBridge {

    private fun controller(activity: Activity): WindowInsetsControllerCompat =
        WindowCompat.getInsetsController(activity.window, activity.window.decorView)

    /** Hide the status and navigation bars, swipe-to-reveal transiently. */
    fun enter(activity: Activity) {
        controller(activity).apply {
            systemBarsBehavior =
                WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            hide(WindowInsetsCompat.Type.systemBars())
        }
        android.util.Log.d("ImmersiveMode", "system bars hidden")
    }

    /** Restore the system bars. Safe to call when they are already showing. */
    fun exit(activity: Activity) {
        controller(activity).show(WindowInsetsCompat.Type.systemBars())
        android.util.Log.d("ImmersiveMode", "system bars restored")
    }
}
