package com.dtourolle.jellytau

import android.app.Activity
import android.view.TextureView
import android.view.ViewGroup
import android.widget.FrameLayout
import com.dtourolle.jellytau.player.JellyTauPlayer

/**
 * Manages the video SurfaceView overlay in the Activity's view hierarchy.
 *
 * This class handles attaching and detaching the native ExoPlayer SurfaceView
 * so that it renders video content behind the WebView.
 */
object VideoOverlayManager {

    private var attachedSurfaceView: TextureView? = null
    private var contentLayoutListener: android.view.View.OnLayoutChangeListener? = null
    private var listenerContentView: ViewGroup? = null

    /**
     * Attach the video view to the Activity's content view.
     *
     * Added at index 0 (bottom of the z-order) so it renders behind the Tauri
     * WebView, allowing the Svelte controls to overlay on top. Since DR-192 this
     * is a TextureView, so "behind" is ordinary view z-order within one window
     * rather than a separate surface punched through it — which is what makes
     * the overlay above it repaint reliably.
     *
     * @param activity The Activity to attach the surface to
     */
    fun attachVideoSurface(activity: Activity) {
        try {
            // Get the SurfaceView from JellyTauPlayer
            val player = JellyTauPlayer.getInstance()
            val surfaceView = player.getSurfaceView()

            if (surfaceView == null) {
                android.util.Log.w("VideoOverlayManager", "No SurfaceView available to attach")
                return
            }

            // Get the root content view
            val contentView = activity.window.decorView.findViewById<ViewGroup>(android.R.id.content)

            // Remove from parent if already attached elsewhere
            (surfaceView.parent as? ViewGroup)?.removeView(surfaceView)

            // Configure layout params to fill the screen
            val layoutParams = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )

            // Add to content view at index 0 (behind WebView)
            contentView.addView(surfaceView, 0, layoutParams)
            attachedSurfaceView = surfaceView

            // Re-fit the video whenever the content view's bounds change (e.g. on
            // device rotation) so the video is letterboxed to fit instead of being
            // stretched/cropped by the MATCH_PARENT surface.
            removeLayoutListener()
            val listener = android.view.View.OnLayoutChangeListener {
                _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
                if (right - left != oldRight - oldLeft || bottom - top != oldBottom - oldTop) {
                    player.fitSurfaceToScreen()
                }
            }
            contentView.addOnLayoutChangeListener(listener)
            contentLayoutListener = listener
            listenerContentView = contentView

            // Fit once now that the surface is attached and the parent is sized.
            player.fitSurfaceToScreen()

            android.util.Log.d("VideoOverlayManager", "Video surface attached to view hierarchy")
        } catch (e: Exception) {
            android.util.Log.e("VideoOverlayManager", "Failed to attach video surface", e)
        }
    }

    /**
     * Detach the video SurfaceView from the view hierarchy.
     *
     * Must be called on the main thread.
     *
     * This had **no callers at all**, which made [attachVideoSurface] one-way:
     * `JellyTauPlayer.clearVideoSurface()` dropped its `surfaceView` reference
     * without removing the view, so every native video left its SurfaceView
     * parented to the content view for the life of the process and the next one
     * added another beneath it. The stack was invisible while the WebView was
     * opaque, and [isVideoSurfaceAttached] — which gates
     * `PictureInPictureManager.canEnterPip` — stayed true forever afterwards.
     *
     * Removes from the view's *own* parent rather than looking the content view
     * up from an Activity, so it cannot leave a view behind when the Activity
     * has been recreated under it.
     *
     * TRACES: UR-003, UR-041 | DR-184
     */
    fun detachVideoSurface() {
        try {
            removeLayoutListener()
            attachedSurfaceView?.let { surfaceView ->
                (surfaceView.parent as? ViewGroup)?.removeView(surfaceView)
                attachedSurfaceView = null
                android.util.Log.d("VideoOverlayManager", "Video surface detached from view hierarchy")
            }
        } catch (e: Exception) {
            android.util.Log.e("VideoOverlayManager", "Failed to detach video surface", e)
        }
    }

    /**
     * Check if a video surface is currently attached.
     *
     * @return true if a surface is attached, false otherwise
     */
    fun isVideoSurfaceAttached(): Boolean {
        return attachedSurfaceView != null
    }

    private fun removeLayoutListener() {
        contentLayoutListener?.let { listener ->
            listenerContentView?.removeOnLayoutChangeListener(listener)
        }
        contentLayoutListener = null
        listenerContentView = null
    }
}
