package io.kiotplugins.edgetoedge;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.view.WindowManager;

import android.graphics.Insets;


import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class EdgeToEdge extends CordovaPlugin {

    private static final String TAG = "EdgeToEdge";
    private Activity activity;
    private CordovaWebView webView;

    // Store system bar colors to prevent them from being overridden
    private String storedStatusBarColor = null;
    private String storedNavigationBarColor = null;
    private String storedStatusBarStyle = "light";
    private String storedNavigationBarStyle = "light";

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        this.activity = cordova.getActivity();
        this.webView = webView;
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        // Ensure all plugin methods run on the UI thread
        if (!cordova.getActivity().getMainLooper().getThread().equals(Thread.currentThread())) {
            cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        executeAction(action, args, callbackContext);
                    } catch (Exception e) {
                        callbackContext.error("Error executing action on UI thread: " + e.getMessage());
                    }
                }
            });
            return true;
        }

        return executeAction(action, args, callbackContext);
    }

    private boolean executeAction(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        switch (action) {
            case "detectEdgeToEdge":
                detectEdgeToEdge(callbackContext);
                return true;
            case "adjustViewForEdgeToEdge":
                adjustViewForEdgeToEdge(callbackContext);
                return true;
            case "getSystemBarHeights":
                getSystemBarHeights(callbackContext);
                return true;
            case "setSystemBarColors":
                setSystemBarColors(args, callbackContext);
                return true;
            case "forceStatusBarColor":
                forceStatusBarColor(args, callbackContext);
                return true;
            default:
                callbackContext.error("Invalid action: " + action);
                return false;
        }
    }

    private void detectEdgeToEdge(CallbackContext callbackContext) {
        try {
            boolean isEdgeToEdge = false;
            String detectionMethod = "none";
            String reason = "";

            // Height-based detection only - no other fallback methods
            
            // NEW: Compare total screen height vs WebView height to detect edge-to-edge
            boolean isEdgeToEdgeByHeight = false;
            int totalScreenHeight = 0;
            int webViewHeight = 0;
            int heightStatusBarHeight = 0;
            int heightNavigationBarHeight = 0;
            
            try {
                // Get total screen height
                android.graphics.Point screenSize = new android.graphics.Point();
                activity.getWindowManager().getDefaultDisplay().getRealSize(screenSize);
                totalScreenHeight = screenSize.y;
                
                // Get WebView height - try multiple methods
                if (webView != null) {
                    try {
                        // Method 1: Get the actual WebView from CordovaWebView
                        View webViewView = webView.getView();
                        if (webViewView != null) {
                            webViewHeight = webViewView.getHeight();
                            android.util.Log.d(TAG, "WebView height from getView(): " + webViewHeight);
                        }
                        
                        // Method 2: If height is 0, try to get it from the activity's content view
                        if (webViewHeight == 0) {
                            View contentView = activity.findViewById(android.R.id.content);
                            if (contentView != null) {
                                webViewHeight = contentView.getHeight();
                                android.util.Log.d(TAG, "WebView height from content view: " + webViewHeight);
                            }
                        }
                        
                        // Method 3: If still 0, try to get it from the decor view
                        if (webViewHeight == 0) {
                            View decorView2 = activity.getWindow().getDecorView();
                            if (decorView2 != null) {
                                webViewHeight = decorView2.getHeight();
                                android.util.Log.d(TAG, "WebView height from decor view: " + webViewHeight);
                            }
                        }
                        
                    } catch (Exception e) {
                        android.util.Log.e(TAG, "Could not get WebView height: " + e.getMessage());
                    }
                }
                
                // Get system bar heights
                heightStatusBarHeight = getStatusBarHeightFromResources();
                heightNavigationBarHeight = getActualNavigationBarHeight();
                
                // Calculate expected content height (screen height minus system bars)
                int expectedContentHeight = totalScreenHeight - heightStatusBarHeight - heightNavigationBarHeight;
                
                // Edge-to-edge detection: WebView should be larger than expected content height
                // This indicates the WebView is extending into system bar areas
                int heightDifference = Math.abs(webViewHeight - totalScreenHeight);
                int tolerance = 30; // Increased tolerance to 200px for better detection
                
                // Primary detection: WebView height >= expected content height (indicates edge-to-edge)
                // Secondary check: WebView height is close to total screen height (within tolerance)
                boolean isLargerThanExpected = webViewHeight >= expectedContentHeight;
                boolean isCloseToTotal = heightDifference <= tolerance;

                
                // Edge-to-edge if WebView is larger than expected content area OR close to total screen
//                isEdgeToEdgeByHeight = (webViewHeight > 0) && (isLargerThanExpected || isCloseToTotal);
                isEdgeToEdgeByHeight = isCloseToTotal;
                
                android.util.Log.d(TAG, "Height-based detection - Total: " + totalScreenHeight + 
                                   "px, WebView: " + webViewHeight + "px, Expected: " + expectedContentHeight + 
                                   "px, Difference: " + heightDifference + "px, Tolerance: " + tolerance + 
                                   "px, IsLargerThanExpected: " + isLargerThanExpected + 
                                   ", IsCloseToTotal: " + isCloseToTotal + 
                                   ", IsEdgeToEdge: " + isEdgeToEdgeByHeight);
                
            } catch (Exception e) {
                android.util.Log.e(TAG, "Error in height-based detection: " + e.getMessage());
            }
            
            // Edge-to-edge detection - HEIGHT-BASED ONLY (most reliable method)
            if (isEdgeToEdgeByHeight) {
                isEdgeToEdge = true;
                detectionMethod = "height_based";
                reason = "WebView height matches total screen height (edge-to-edge active)";
            } else {
                isEdgeToEdge = false;
                detectionMethod = "height_based";
                reason = "WebView height does not match total screen height (edge-to-edge not active)";
            }
            
            // Additional safety check: If we detect edge-to-edge but system bars have significant height,
            // it might not be properly configured
            if (isEdgeToEdge) {
                int statusBarHeight = getStatusBarHeightFromResources();
                int navigationBarHeight = getActualNavigationBarHeight();
                
                // If system bars are very large, it might indicate they're not properly transparent
                if (statusBarHeight > 100 || navigationBarHeight > 200) {
                    android.util.Log.w(TAG, "Edge-to-edge detected but system bars seem large - Status: " + 
                                      statusBarHeight + "px, Navigation: " + navigationBarHeight + "px");
                    reason += " (warning: large system bars detected)";
                }
            }

            JSONObject result = new JSONObject();
            result.put("isEdgeToEdge", isEdgeToEdge);
            result.put("apiLevel", Build.VERSION.SDK_INT);
            result.put("detectionMethod", detectionMethod);
            result.put("reason", reason);
            result.put("totalScreenHeight", totalScreenHeight);
            result.put("webViewHeight", webViewHeight);
            result.put("expectedContentHeight", totalScreenHeight - heightStatusBarHeight - heightNavigationBarHeight);
            result.put("heightDifference", Math.abs(webViewHeight - totalScreenHeight));
            result.put("statusBarHeight", heightStatusBarHeight);
            result.put("navigationBarHeight", heightNavigationBarHeight);
            float density = activity.getResources().getDisplayMetrics().density;
            result.put("density", density);
            result.put("totalHeight", totalScreenHeight);

            android.util.Log.d(TAG, "Edge-to-edge detection result: " + isEdgeToEdge + 
                               " (method: " + detectionMethod + ", reason: " + reason + ")");

            callbackContext.success(result);
        } catch (Exception e) {
            android.util.Log.e(TAG, "Error detecting edge-to-edge: " + e.getMessage());
            callbackContext.error("Error detecting edge-to-edge: " + e.getMessage());
        }
    }

    private void adjustViewForEdgeToEdge(CallbackContext callbackContext) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // Android 11+ (API 30+) - Full edge-to-edge support
                adjustViewForAndroid11Plus(callbackContext);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // Android 5.0+ (API 21+) - Limited edge-to-edge support
                adjustViewForAndroid21Plus(callbackContext);
            } else {
                // Legacy Android versions - Basic immersive mode
                adjustViewForLegacyAndroid(callbackContext);
            }
        } catch (Exception e) {
            callbackContext.error("Error adjusting view: " + e.getMessage());
        }
    }

    private void adjustViewForAndroid11Plus(CallbackContext callbackContext) {
        try {
            View decorView = activity.getWindow().getDecorView();

            // Set edge-to-edge display (API 30+)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                activity.getWindow().setDecorFitsSystemWindows(false);
            }

            // Set system UI flags for edge-to-edge
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            );

            // Set navigation bar color to transparent (only if no custom colors stored)
            if (storedStatusBarColor == null) {
                activity.getWindow().setStatusBarColor(android.graphics.Color.TRANSPARENT);
            }
            if (storedNavigationBarColor == null) {
                activity.getWindow().setNavigationBarColor(android.graphics.Color.TRANSPARENT);
            }

            // Make navigation bar icons visible on light backgrounds
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                decorView.setSystemUiVisibility(
                        decorView.getSystemUiVisibility() |
                                View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
                );
            }

            // Apply window insets to adjust WebView layout
            // Ensure we're on the UI thread when setting up the listener
            cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                        @Override
                        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                                Insets systemBarInsets = insets.getInsets(WindowInsets.Type.systemBars());
                                int statusBarHeight = systemBarInsets.top;
                                int navigationBarHeight = systemBarInsets.bottom;

                                // Adjust WebView layout parameters on UI thread
                                adjustWebViewLayout(statusBarHeight, navigationBarHeight);
                            }
                            return insets;
                        }
                    });
                }
            });

            // Apply stored system bar colors if they exist
            if (storedStatusBarColor != null || storedNavigationBarColor != null) {
                applySystemBarColors(storedStatusBarColor, storedNavigationBarColor,
                        storedStatusBarStyle, storedNavigationBarStyle);

                // Force refresh colors after a delay to ensure they're not overridden
                decorView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (storedStatusBarColor != null || storedNavigationBarColor != null) {
                            applySystemBarColors(storedStatusBarColor, storedNavigationBarColor,
                                    storedStatusBarStyle, storedNavigationBarStyle);
                            android.util.Log.d(TAG, "System bar colors reapplied after edge-to-edge setup");
                        }
                    }
                }, 500); // 500ms delay
            }

            callbackContext.success("View adjusted for Android 11+ edge-to-edge");
        } catch (Exception e) {
            callbackContext.error("Error adjusting view for Android 11+: " + e.getMessage());
        }
    }

    private void adjustViewForAndroid21Plus(CallbackContext callbackContext) {
        try {
            View decorView = activity.getWindow().getDecorView();

            // For Android 5.0+ (API 21+) but below Android 11 (API 30)
            // We use system UI flags and status/navigation bar color changes

            // Set system UI flags for edge-to-edge layout
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            );

            // Set transparent system bars (API 21+) - only if no custom colors stored
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (storedStatusBarColor == null) {
                    activity.getWindow().setStatusBarColor(android.graphics.Color.TRANSPARENT);
                }
                if (storedNavigationBarColor == null) {
                    activity.getWindow().setNavigationBarColor(android.graphics.Color.TRANSPARENT);
                }
            }

            // Apply window insets to adjust WebView layout
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                // Ensure we're on the UI thread when setting up the listener
                cordova.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                            @Override
                            public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                                int statusBarHeight = 0;
                                int navigationBarHeight = 0;

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                                    // Android 9+ (API 28+) - Use new WindowInsets API
                                    statusBarHeight = insets.getSystemWindowInsetTop();
                                    navigationBarHeight = insets.getSystemWindowInsetBottom();
                                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                                    // Android 4.4W+ (API 20+) - Use legacy WindowInsets API
                                    statusBarHeight = insets.getSystemWindowInsetTop();
                                    navigationBarHeight = insets.getSystemWindowInsetBottom();
                                }

                                // Adjust WebView layout parameters on UI thread
                                adjustWebViewLayout(statusBarHeight, navigationBarHeight);
                                return insets;
                            }
                        });
                    }
                });
            } else {
                // For devices that don't support WindowInsets listener, get heights from resources
                cordova.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            int statusBarHeight = getStatusBarHeightFromResources();
                            int navigationBarHeight = getActualNavigationBarHeight();
                            adjustWebViewLayout(statusBarHeight, navigationBarHeight);
                        } catch (Exception e) {
                            android.util.Log.e(TAG, "Error getting system bar heights: " + e.getMessage());
                        }
                    }
                });
            }

            // Apply stored system bar colors if they exist
            if (storedStatusBarColor != null || storedNavigationBarColor != null) {
                applySystemBarColors(storedStatusBarColor, storedNavigationBarColor,
                        storedStatusBarStyle, storedNavigationBarStyle);

                // Force refresh colors after a delay to ensure they're not overridden
                decorView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (storedStatusBarColor != null || storedNavigationBarColor != null) {
                            applySystemBarColors(storedStatusBarColor, storedNavigationBarColor,
                                    storedStatusBarStyle, storedNavigationBarStyle);
                            android.util.Log.d(TAG, "System bar colors reapplied after edge-to-edge setup");
                        }
                    }
                }, 500); // 500ms delay
            }

            callbackContext.success("View adjusted for Android 5.0+ edge-to-edge");
        } catch (Exception e) {
            callbackContext.error("Error adjusting view for Android 5.0+: " + e.getMessage());
        }
    }

    private void adjustViewForLegacyAndroid(CallbackContext callbackContext) {
        try {
            View decorView = activity.getWindow().getDecorView();

            // Set system UI flags for immersive mode
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            );

            // For legacy Android, get system bar heights from resources and adjust WebView
            cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        int statusBarHeight = getStatusBarHeightFromResources();
                        int navigationBarHeight = getActualNavigationBarHeight();

                        // Adjust WebView layout parameters
                        adjustWebViewLayout(statusBarHeight, navigationBarHeight);
                    } catch (Exception e) {
                        android.util.Log.e(TAG, "Error getting system bar heights for legacy Android: " + e.getMessage());
                    }
                }
            });

            // Apply stored system bar colors if they exist
            if (storedStatusBarColor != null || storedNavigationBarColor != null) {
                applySystemBarColors(storedStatusBarColor, storedNavigationBarColor,
                        storedStatusBarStyle, storedNavigationBarStyle);

                // Force refresh colors after a delay to ensure they're not overridden
                decorView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (storedStatusBarColor != null || storedNavigationBarColor != null) {
                            applySystemBarColors(storedStatusBarColor, storedNavigationBarColor,
                                    storedStatusBarStyle, storedNavigationBarStyle);
                            android.util.Log.d(TAG, "System bar colors reapplied after edge-to-edge setup");
                        }
                    }
                }, 500); // 500ms delay
            }

            callbackContext.success("View adjusted for legacy Android edge-to-edge");
        } catch (Exception e) {
            callbackContext.error("Error adjusting view for legacy Android: " + e.getMessage());
        }
    }

    /**
     * Adjust the WebView layout parameters to account for system bars
     * This ensures the WebView content is fully visible and not hidden behind system bars
     */
    private void adjustWebViewLayout(final int statusBarHeight, final int navigationBarHeight) {
        try {
            // Double-check we're on the UI thread
            if (!cordova.getActivity().getMainLooper().getThread().equals(Thread.currentThread())) {
                cordova.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adjustWebViewLayout(statusBarHeight, navigationBarHeight);
                    }
                });
                return;
            }

            try {
                // Only adjust the main activity content view to avoid excessive padding
                // The WebView will automatically adjust to its parent's layout
                View contentView = activity.findViewById(android.R.id.content);
                if (contentView != null) {
                    ViewGroup.LayoutParams contentParams = contentView.getLayoutParams();
                    if (contentParams instanceof ViewGroup.MarginLayoutParams) {
                        ViewGroup.MarginLayoutParams contentMarginParams = (ViewGroup.MarginLayoutParams) contentParams;

                        // Set minimal margins to account for system bars
                        // Use a smaller value to avoid excessive padding
                        int topMargin = Math.max(0, statusBarHeight - 10); // Reduce by 10px
                        int bottomMargin = Math.max(0, navigationBarHeight - 10); // Reduce by 10px

                        contentMarginParams.topMargin = topMargin;
                        contentMarginParams.bottomMargin = bottomMargin;

                        // Apply the new layout parameters
                        contentView.setLayoutParams(contentMarginParams);

                        // Force layout update
                        contentView.requestLayout();

                        android.util.Log.d(TAG, "Content view adjusted - Top: " + topMargin + "px, Bottom: " + bottomMargin + "px");
                    }
                }

                // Log the adjustment
                android.util.Log.d(TAG, "WebView layout adjusted - Status bar: " + statusBarHeight +
                        "px, Navigation bar: " + navigationBarHeight + "px");

            } catch (Exception e) {
                android.util.Log.e(TAG, "Error adjusting WebView layout: " + e.getMessage());
            }
        } catch (Exception e) {
            android.util.Log.e(TAG, "Error in adjustWebViewLayout: " + e.getMessage());
        }
    }

    private void getSystemBarHeights(CallbackContext callbackContext) {
        try {
            JSONObject result = new JSONObject();

            // Log current window state for debugging
            View decorView = activity.getWindow().getDecorView();
            android.util.Log.d(TAG, "Getting system bar heights - API Level: " + Build.VERSION.SDK_INT +
                    ", Decor view attached: " + (decorView.getWindowToken() != null) +
                    ", View attached to window: " + decorView.isAttachedToWindow());

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // Android 11+ (API 30+)
                android.util.Log.d(TAG, "Using Android 11+ method for system bar heights");
                getSystemBarHeightsAndroid11Plus(result, callbackContext);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                // Android 4.4W+ (API 20+) - WindowInsets support
                android.util.Log.d(TAG, "Using Android 20+ method for system bar heights");
                getSystemBarHeightsAndroid20Plus(result, callbackContext);
            } else {
                // Legacy Android versions
                android.util.Log.d(TAG, "Using legacy method for system bar heights");
                getSystemBarHeightsLegacy(result, callbackContext);
            }
        } catch (Exception e) {
            android.util.Log.e(TAG, "Error in getSystemBarHeights: " + e.getMessage());
            callbackContext.error("Error getting system bar heights: " + e.getMessage());
        }
    }

    private void getSystemBarHeightsAndroid11Plus(JSONObject result, CallbackContext callbackContext) throws JSONException {
        View decorView = activity.getWindow().getDecorView();

        // Get immediate heights from resources as fallback
        int immediateStatusBarHeight = getStatusBarHeightFromResources();
        int immediateNavigationBarHeight = getActualNavigationBarHeight();
        
        // Get display density for dp conversion
        float density = activity.getResources().getDisplayMetrics().density;

        android.util.Log.d(TAG, "Setting up Android 11+ window insets listener with fallback heights - Status: " +
                immediateStatusBarHeight + "px (" + Math.round(immediateStatusBarHeight / density) + "dp), Navigation: " + 
                immediateNavigationBarHeight + "px (" + Math.round(immediateNavigationBarHeight / density) + "dp)");

        // Ensure we're on the UI thread when setting up the listener
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                decorView.setOnApplyWindowInsetsListener((v, windowInsets) -> {
                    android.util.Log.d(TAG, "Window insets listener triggered - processing insets");
                    try {
                        int statusBarHeight = 0;
                        int navigationBarHeight = 0;

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                            Insets insets = windowInsets.getInsets(WindowInsets.Type.systemBars());
                            statusBarHeight = insets.top;
                            navigationBarHeight = insets.bottom;
                        }

                        // Use the insets values if available, otherwise fall back to resource values
                        if (statusBarHeight == 0) statusBarHeight = immediateStatusBarHeight;
                        if (navigationBarHeight == 0) navigationBarHeight = immediateNavigationBarHeight;
                        
                        // Convert to dp for more reasonable values
                        int statusBarHeightDp = Math.round(statusBarHeight / density);
                        int navigationBarHeightDp = Math.round(navigationBarHeight / density);

                        android.util.Log.d(TAG, "Final heights from insets - Status: " + statusBarHeight +
                                "px (" + statusBarHeightDp + "dp), Navigation: " + navigationBarHeight + 
                                "px (" + navigationBarHeightDp + "dp)");

                        // Create a new result object to avoid concurrency issues
                        JSONObject threadSafeResult = new JSONObject();
                        threadSafeResult.put("statusBarHeight", statusBarHeight);
                        threadSafeResult.put("navigationBarHeight", navigationBarHeight);
                        threadSafeResult.put("totalSystemBarHeight", statusBarHeight + navigationBarHeight);
                        threadSafeResult.put("statusBarHeightDp", statusBarHeightDp);
                        threadSafeResult.put("navigationBarHeightDp", navigationBarHeightDp);
                        threadSafeResult.put("totalSystemBarHeightDp", statusBarHeightDp + navigationBarHeightDp);
                        threadSafeResult.put("density", density);
                        
                        // Add navigation mode information
                        addNavigationModeInfo(threadSafeResult);

                        // Ensure callback is executed on the main thread
                        cordova.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!callbackContext.isFinished()) {
                                    callbackContext.success(threadSafeResult);
                                    android.util.Log.d(TAG, "Success callback sent from window insets listener");
                                    android.util.Log.d(TAG, "Callback context state after success: isFinished=" + callbackContext.isFinished());
                                } else {
                                    android.util.Log.w(TAG, "Callback context already finished, cannot send success response");
                                }
                            }
                        });

                    } catch (Exception e) {
                        android.util.Log.e(TAG, "Error in window insets listener: " + e.getMessage());
                        // Ensure error callback is executed on the main thread
                        cordova.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!callbackContext.isFinished()) {
                                    callbackContext.error("Error getting system bar heights: " + e.getMessage());
                                } else {
                                    android.util.Log.w(TAG, "Callback context already finished, cannot send error response");
                                }
                            }
                        });
                    }
                    return windowInsets;
                });

                // Force the insets to be processed
                decorView.requestApplyInsets();
                android.util.Log.d(TAG, "Requested apply insets for decor view");

                // If the listener doesn't fire within a reasonable time, use fallback values
                decorView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // Check if callback was already sent
                        if (!callbackContext.isFinished()) {
                            android.util.Log.d(TAG, "Window insets listener timeout - using fallback resource values");
                            try {
                                // Convert to dp for more reasonable values
                                int statusBarHeightDp = Math.round(immediateStatusBarHeight / density);
                                int navigationBarHeightDp = Math.round(immediateNavigationBarHeight / density);
                                
                                JSONObject fallbackResult = new JSONObject();
                                fallbackResult.put("statusBarHeight", immediateStatusBarHeight);
                                fallbackResult.put("navigationBarHeight", immediateNavigationBarHeight);
                                fallbackResult.put("totalSystemBarHeight", immediateStatusBarHeight + immediateNavigationBarHeight);
                                fallbackResult.put("statusBarHeightDp", statusBarHeightDp);
                                fallbackResult.put("navigationBarHeightDp", navigationBarHeightDp);
                                fallbackResult.put("totalSystemBarHeightDp", statusBarHeightDp + navigationBarHeightDp);
                                fallbackResult.put("density", density);
                                
                                // Add navigation mode information
                                addNavigationModeInfo(fallbackResult);
                                
                                if (!callbackContext.isFinished()) {
                                    callbackContext.success(fallbackResult);
                                    android.util.Log.d(TAG, "Fallback callback sent with resource heights");
                                } else {
                                    android.util.Log.w(TAG, "Callback context already finished, cannot send fallback response");
                                }
                            } catch (Exception e) {
                                android.util.Log.e(TAG, "Error with fallback values: " + e.getMessage());
                                if (!callbackContext.isFinished()) {
                                    callbackContext.error("Error with fallback values: " + e.getMessage());
                                }
                            }
                        } else {
                            android.util.Log.d(TAG, "Callback already sent, skipping fallback");
                        }
                    }
                }, 100); // 100ms timeout
            }
        });
    }

    private void getSystemBarHeightsAndroid20Plus(JSONObject result, CallbackContext callbackContext) throws JSONException {
        View decorView = activity.getWindow().getDecorView();

        // Get immediate heights from resources as fallback
        int immediateStatusBarHeight = getStatusBarHeightFromResources();
        int immediateNavigationBarHeight = getActualNavigationBarHeight();

        // Get display density for dp conversion
        float density = activity.getResources().getDisplayMetrics().density;

        android.util.Log.d(TAG, "Setting up Android 20+ window insets listener with fallback heights - Status: " +
                immediateStatusBarHeight + "px (" + Math.round(immediateStatusBarHeight / density) + "dp), Navigation: " +
                immediateNavigationBarHeight + "px (" + Math.round(immediateNavigationBarHeight / density) + "dp)");

        // Ensure we're on the UI thread when setting up the listener
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                decorView.setOnApplyWindowInsetsListener((v, windowInsets) -> {
                    android.util.Log.d(TAG, "Window insets listener triggered (Android 20+) - processing insets");
                    try {
                        int statusBarHeight = 0;
                        int navigationBarHeight = 0;

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                            statusBarHeight = windowInsets.getSystemWindowInsetTop();
                            navigationBarHeight = windowInsets.getSystemWindowInsetBottom();
                        }

                        // Use the insets values if available, otherwise fall back to resource values
                        if (statusBarHeight == 0) statusBarHeight = immediateStatusBarHeight;
                        if (navigationBarHeight == 0) navigationBarHeight = immediateNavigationBarHeight;

                        // Convert to dp for more reasonable values
                        int statusBarHeightDp = Math.round(statusBarHeight / density);
                        int navigationBarHeightDp = Math.round(navigationBarHeight / density);

                        android.util.Log.d(TAG, "Final heights from insets (Android 20+) - Status: " + statusBarHeight +
                                "px (" + statusBarHeightDp + "dp), Navigation: " + navigationBarHeight +
                                "px (" + navigationBarHeightDp + "dp)");

                        // Create a new result object to avoid concurrency issues
                        JSONObject threadSafeResult = new JSONObject();
                        threadSafeResult.put("statusBarHeight", statusBarHeight);
                        threadSafeResult.put("navigationBarHeight", navigationBarHeight);
                        threadSafeResult.put("totalSystemBarHeight", statusBarHeight + navigationBarHeight);
                        threadSafeResult.put("statusBarHeightDp", statusBarHeightDp);
                        threadSafeResult.put("navigationBarHeightDp", navigationBarHeightDp);
                        threadSafeResult.put("totalSystemBarHeightDp", statusBarHeightDp + navigationBarHeightDp);
                        threadSafeResult.put("density", density);
                        
                        // Add navigation mode information
                        addNavigationModeInfo(threadSafeResult);

                        // Ensure callback is executed on the main thread
                        cordova.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!callbackContext.isFinished()) {
                                    callbackContext.success(threadSafeResult);
                                    android.util.Log.d(TAG, "Success callback sent from Android 20+ window insets listener");
                                } else {
                                    android.util.Log.w(TAG, "Callback context already finished, cannot send success response");
                                }
                            }
                        });

                    } catch (Exception e) {
                        android.util.Log.e(TAG, "Error in Android 20+ window insets listener: " + e.getMessage());
                        // Ensure error callback is executed on the main thread
                        cordova.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!callbackContext.isFinished()) {
                                    callbackContext.error("Error getting system bar heights: " + e.getMessage());
                                } else {
                                    android.util.Log.w(TAG, "Callback context already finished, cannot send error response");
                                }
                            }
                        });
                    }
                    return windowInsets;
                });

                // Force the insets to be processed
                decorView.requestApplyInsets();
                android.util.Log.d(TAG, "Requested apply insets for Android 20+ decor view");

                // If the listener doesn't fire within a reasonable time, use fallback values
                decorView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // Check if callback was already sent
                        if (!callbackContext.isFinished()) {
                            android.util.Log.d(TAG, "Android 20+ window insets listener timeout - using fallback resource values");
                            try {
                                // Convert to dp for more reasonable values
                                int statusBarHeightDp = Math.round(immediateStatusBarHeight / density);
                                int navigationBarHeightDp = Math.round(immediateNavigationBarHeight / density);

                                JSONObject fallbackResult = new JSONObject();
                                fallbackResult.put("statusBarHeight", immediateStatusBarHeight);
                                fallbackResult.put("navigationBarHeight", immediateNavigationBarHeight);
                                fallbackResult.put("totalSystemBarHeight", immediateStatusBarHeight + immediateNavigationBarHeight);
                                fallbackResult.put("statusBarHeightDp", statusBarHeightDp);
                                fallbackResult.put("navigationBarHeightDp", navigationBarHeightDp);
                                fallbackResult.put("totalSystemBarHeightDp", statusBarHeightDp + navigationBarHeightDp);
                                fallbackResult.put("density", density);
                                
                                // Add navigation mode information
                                addNavigationModeInfo(fallbackResult);

                                if (!callbackContext.isFinished()) {
                                    callbackContext.success(fallbackResult);
                                    android.util.Log.d(TAG, "Fallback callback sent with Android 20+ resource heights");
                                } else {
                                    android.util.Log.w(TAG, "Callback context already finished, cannot send fallback response");
                                }
                            } catch (Exception e) {
                                android.util.Log.e(TAG, "Error with Android 20+ fallback values: " + e.getMessage());
                                if (!callbackContext.isFinished()) {
                                    callbackContext.error("Error with fallback values: " + e.getMessage());
                                }
                            }
                        } else {
                            android.util.Log.d(TAG, "Android 20+ callback already sent, skipping fallback");
                        }
                    }
                }, 100); // 100ms timeout
            }
        });
    }

    private void getSystemBarHeightsLegacy(JSONObject result, CallbackContext callbackContext) throws JSONException {
        try {
            // Get system bar heights from resources
            int statusBarHeight = getStatusBarHeightFromResources();
            int navigationBarHeight = getActualNavigationBarHeight();

            result.put("statusBarHeight", statusBarHeight);
            result.put("navigationBarHeight", navigationBarHeight);
            result.put("totalSystemBarHeight", statusBarHeight + navigationBarHeight);
            
            // Add navigation mode information
            addNavigationModeInfo(result);

            callbackContext.success(result);
        } catch (Exception e) {
            callbackContext.error("Error getting system bar heights: " + e.getMessage());
        }
    }

    /**
     * Get status bar height from system resources
     */
    private int getStatusBarHeightFromResources() {
        int statusBarHeight = 0;
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = activity.getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight;
    }

    /**
     * Get navigation bar height from system resources
     */
    private int getNavigationBarHeightFromResources() {
        int navigationBarHeight = 0;
        int resourceId = activity.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            navigationBarHeight = activity.getResources().getDimensionPixelSize(resourceId);
        }
        return navigationBarHeight;
    }

    /**
     * Get actual navigation bar height considering gesture navigation mode
     */
    private int getActualNavigationBarHeight() {
        try {
            // Check if gesture navigation is enabled first (more reliable than WindowInsets timing)
            if (isGestureNavigationEnabled()) {
                // For gesture navigation, return a smaller height (typically 8-16dp)
                float density = activity.getResources().getDisplayMetrics().density;
                int gestureNavHeight = Math.round(12 * density); // 12dp converted to pixels
                return gestureNavHeight;
            } else {
                // For three-button navigation, use the full resource height
                return getNavigationBarHeightFromResources();
            }
            
        } catch (Exception e) {
            android.util.Log.e(TAG, "Error getting actual navigation bar height: " + e.getMessage());
            // Fallback to resource height
            return getNavigationBarHeightFromResources();
        }
    }

    /**
     * Add navigation mode information to the result object
     */
    private void addNavigationModeInfo(JSONObject result) {
        try {
            boolean isGestureNav = isGestureNavigationEnabled();
            int resourceNavHeight = getNavigationBarHeightFromResources();
            
            result.put("isGestureNavigation", isGestureNav);
            result.put("navigationMode", isGestureNav ? "gesture" : "three-button");
            result.put("resourceNavigationBarHeight", resourceNavHeight);
            
        } catch (Exception e) {
            android.util.Log.e(TAG, "Error adding navigation mode info: " + e.getMessage());
        }
    }

    // Cache navigation mode detection result to avoid repeated calls
    private Boolean cachedGestureNavigation = null;
    
    /**
     * Check if gesture navigation is enabled (cached result)
     */
    private boolean isGestureNavigationEnabled() {
        if (cachedGestureNavigation != null) {
            return cachedGestureNavigation;
        }
        
        try {
            // The key insight: WindowInsets returning 0px for navigation bar IS CORRECT for gesture navigation!
            // Gesture navigation doesn't consume layout space - it's an overlay
            
            int resourceHeight = getNavigationBarHeightFromResources();
            View decorView = activity.getWindow().getDecorView();
            
            if (decorView != null && decorView.getRootWindowInsets() != null && resourceHeight > 0) {
                WindowInsets insets = decorView.getRootWindowInsets();
                int actualHeight = 0;
                
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    Insets systemBarInsets = insets.getInsets(WindowInsets.Type.systemBars());
                    actualHeight = systemBarInsets.bottom;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    actualHeight = insets.getSystemWindowInsetBottom();
                }
                
                android.util.Log.d(TAG, "Navigation detection - WindowInsets: " + actualHeight + "px, Resource: " + resourceHeight + "px");
                
                // If WindowInsets shows 0px but resource shows significant height, it's likely gesture navigation
                if (actualHeight == 0 && resourceHeight > 50) {
                    android.util.Log.d(TAG, "WindowInsets=0 with large resource height suggests gesture navigation");
                    cachedGestureNavigation = true;
                    return true;
                }
                
                // If WindowInsets shows significant height, it's likely three-button navigation
                if (actualHeight > 50) {
                    android.util.Log.d(TAG, "WindowInsets shows significant height, suggests three-button navigation");
                    cachedGestureNavigation = false;
                    return false;
                }
            }
            
            // Fallback: Try settings
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                try {
                    int navMode = android.provider.Settings.Secure.getInt(activity.getContentResolver(), "navigation_mode", 0);
                    android.util.Log.d(TAG, "Settings navigation_mode = " + navMode);
                    if (navMode == 2) {
                        cachedGestureNavigation = true;
                        return true;
                    } else if (navMode == 0) {
                        cachedGestureNavigation = false;
                        return false;
                    }
                } catch (Exception ignored) {}
            }
            
            // Default to three-button navigation
            android.util.Log.d(TAG, "Cannot reliably detect navigation mode, defaulting to three-button");
            cachedGestureNavigation = false;
            return false;
            
        } catch (Exception e) {
            android.util.Log.e(TAG, "Error detecting gesture navigation: " + e.getMessage());
            cachedGestureNavigation = false;
            return false;
        }
    }

    /**
     * Set custom colors for system bars
     * @param args - JSONArray containing color configuration
     * @param callbackContext - Callback context for result
     */
    private void setSystemBarColors(JSONArray args, CallbackContext callbackContext) {
        try {
            if (args.length() > 0) {
                JSONObject colors = args.getJSONObject(0);

                String statusBarColor = colors.optString("statusBar", null);
                String navigationBarColor = colors.optString("navigationBar", null);
                String statusBarStyle = colors.optString("statusBarStyle", "light");
                String navigationBarStyle = colors.optString("navigationBarStyle", "light");

                // Store colors for later use
                storedStatusBarColor = statusBarColor;
                storedNavigationBarColor = navigationBarColor;
                storedStatusBarStyle = statusBarStyle;
                storedNavigationBarStyle = navigationBarStyle;

                // Apply colors on UI thread
                cordova.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            applySystemBarColors(statusBarColor, navigationBarColor, statusBarStyle, navigationBarStyle);
                            callbackContext.success("System bar colors applied successfully");
                        } catch (Exception e) {
                            callbackContext.error("Error applying system bar colors: " + e.getMessage());
                        }
                    }
                });
            } else {
                callbackContext.error("No color configuration provided");
            }
        } catch (Exception e) {
            callbackContext.error("Error parsing color configuration: " + e.getMessage());
        }
    }

    /**
     * Apply system bar colors to the window
     * @param statusBarColor - Status bar color (hex, rgb, or named color)
     * @param navigationBarColor - Navigation bar color (hex, rgb, or named color)
     * @param statusBarStyle - Status bar icon style ('light' or 'dark')
     * @param navigationBarStyle - Navigation bar icon style ('light' or 'dark')
     */
    private void applySystemBarColors(String statusBarColor, String navigationBarColor, String statusBarStyle, String navigationBarStyle) {
        try {
            View decorView = activity.getWindow().getDecorView();
            int currentFlags = decorView.getSystemUiVisibility();

            // Parse and apply status bar color
            if (statusBarColor != null && !statusBarColor.equals("null") && !statusBarColor.isEmpty()) {
                try {
                    int color = parseColor(statusBarColor);

                    // Use aggressive status bar color application
                    forceApplyStatusBarColor(statusBarColor);

                    // Set status bar icon style
                    if ("dark".equals(statusBarStyle)) {
                        decorView.setSystemUiVisibility(currentFlags | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                    } else {
                        decorView.setSystemUiVisibility(currentFlags & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                    }

                    android.util.Log.d(TAG, "Status bar color set to: " + statusBarColor + " (0x" + String.format("%08X", color) + ")");
                } catch (Exception e) {
                    android.util.Log.e(TAG, "Error setting status bar color '" + statusBarColor + "': " + e.getMessage());
                    // Fallback to transparent
                    activity.getWindow().setStatusBarColor(android.graphics.Color.TRANSPARENT);
                }
            } else {
                // Set transparent status bar
                activity.getWindow().setStatusBarColor(android.graphics.Color.TRANSPARENT);
                android.util.Log.d(TAG, "Status bar set to transparent");
            }

            // Parse and apply navigation bar color
            if (navigationBarColor != null && !navigationBarColor.equals("null") && !navigationBarColor.isEmpty()) {
                try {
                    int color = parseColor(navigationBarColor);
                    activity.getWindow().setNavigationBarColor(color);

                    // Set navigation bar icon style
                    if ("dark".equals(navigationBarStyle)) {
                        decorView.setSystemUiVisibility(currentFlags | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
                    } else {
                        decorView.setSystemUiVisibility(currentFlags & ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
                    }

                    android.util.Log.d(TAG, "Navigation bar color set to: " + navigationBarColor + " (0x" + String.format("%08X", color) + ")");
                } catch (Exception e) {
                    android.util.Log.e(TAG, "Error setting navigation bar color '" + navigationBarColor + "': " + e.getMessage());
                    // Fallback to transparent
                    activity.getWindow().setNavigationBarColor(android.graphics.Color.TRANSPARENT);
                }
            } else {
                // Set transparent navigation bar
                activity.getWindow().setNavigationBarColor(android.graphics.Color.TRANSPARENT);
                android.util.Log.d(TAG, "Navigation bar set to transparent");
            }

            // Force a final refresh of both colors
            forceRefreshSystemBarColors();

            android.util.Log.d(TAG, "System bar colors applied - Status: " + statusBarColor +
                    ", Navigation: " + navigationBarColor +
                    ", Status Style: " + statusBarStyle +
                    ", Navigation Style: " + navigationBarStyle);

        } catch (Exception e) {
            android.util.Log.e(TAG, "Error applying system bar colors: " + e.getMessage());
            throw e;
        }
    }

    /**
     * Force refresh system bar colors to ensure they are applied
     */
    private void forceRefreshSystemBarColors() {
        try {
            // Force refresh by temporarily changing and then restoring colors
            if (storedStatusBarColor != null && !storedStatusBarColor.equals("null") && !storedStatusBarColor.isEmpty()) {
                int color = parseColor(storedStatusBarColor);
                activity.getWindow().setStatusBarColor(color);

                // Force layout update
                View decorView = activity.getWindow().getDecorView();
                decorView.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            int refreshColor = parseColor(storedStatusBarColor);
                            activity.getWindow().setStatusBarColor(refreshColor);
                            android.util.Log.d(TAG, "Status bar color refreshed: " + storedStatusBarColor);
                        } catch (Exception e) {
                            android.util.Log.e(TAG, "Error refreshing status bar color: " + e.getMessage());
                        }
                    }
                });
            }

            if (storedNavigationBarColor != null && !storedNavigationBarColor.equals("null") && !storedNavigationBarColor.isEmpty()) {
                int color = parseColor(storedNavigationBarColor);
                activity.getWindow().setNavigationBarColor(color);

                android.util.Log.d(TAG, "Navigation bar color refreshed: " + storedNavigationBarColor);
            }
        } catch (Exception e) {
            android.util.Log.e(TAG, "Error forcing refresh of system bar colors: " + e.getMessage());
        }
    }

    /**
     * Parse color string to integer color value
     * @param colorString - Color string (hex, rgb, or named color)
     * @return int - Color value
     */
    private int parseColor(String colorString) {
        try {
            if (colorString.startsWith("#")) {
                // Hex color
                return android.graphics.Color.parseColor(colorString);
            } else if (colorString.startsWith("rgb")) {
                // RGB color - convert to hex
                String hexColor = convertRgbToHex(colorString);
                return android.graphics.Color.parseColor(hexColor);
            } else {
                // Named color or direct hex
                return android.graphics.Color.parseColor(colorString);
            }
        } catch (Exception e) {
            android.util.Log.w(TAG, "Could not parse color: " + colorString + ", using default");
            return android.graphics.Color.TRANSPARENT;
        }
    }

    /**
     * Convert RGB color string to hex
     * @param rgbString - RGB color string (e.g., "rgb(255, 0, 0)")
     * @return String - Hex color string
     */
    private String convertRgbToHex(String rgbString) {
        try {
            // Extract RGB values from "rgb(r, g, b)" format
            String values = rgbString.substring(rgbString.indexOf("(") + 1, rgbString.indexOf(")"));
            String[] rgb = values.split(",");

            int r = Integer.parseInt(rgb[0].trim());
            int g = Integer.parseInt(rgb[1].trim());
            int b = Integer.parseInt(rgb[2].trim());

            return String.format("#%02x%02x%02x", r, g, b);
        } catch (Exception e) {
            android.util.Log.w(TAG, "Could not convert RGB to hex: " + rgbString);
            return "#000000"; // Default to black
        }
    }

    /**
     * Force apply status bar color with multiple attempts to ensure it persists
     */
    private void forceApplyStatusBarColor(String colorString) {
        if (colorString == null || colorString.equals("null") || colorString.isEmpty()) {
            return;
        }

        try {
            int color = parseColor(colorString);
            View decorView = activity.getWindow().getDecorView();

            // Method 1: Temporarily disable edge-to-edge mode
            decorView.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        // Clear edge-to-edge flags temporarily
                        int currentFlags = decorView.getSystemUiVisibility();
                        int newFlags = currentFlags & ~View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                & ~View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                & ~View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;

                        decorView.setSystemUiVisibility(newFlags);

                        // Set the status bar color
                        activity.getWindow().setStatusBarColor(color);

                        // Re-enable edge-to-edge mode after a short delay
                        decorView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    // Re-enable edge-to-edge flags
                                    decorView.setSystemUiVisibility(currentFlags);

                                    // Reapply the color
                                    activity.getWindow().setStatusBarColor(color);

                                    android.util.Log.d(TAG, "Status bar color applied with edge-to-edge toggle: " + colorString);
                                } catch (Exception e) {
                                    android.util.Log.e(TAG, "Error re-enabling edge-to-edge: " + e.getMessage());
                                }
                            }
                        }, 200);

                    } catch (Exception e) {
                        android.util.Log.e(TAG, "Error in edge-to-edge toggle method: " + e.getMessage());
                    }
                }
            });

            // Method 2: Direct application
            activity.getWindow().setStatusBarColor(color);

            // Method 3: Force on UI thread
            decorView.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        activity.getWindow().setStatusBarColor(color);
                        android.util.Log.d(TAG, "Status bar color forced (UI thread): " + colorString);
                    } catch (Exception e) {
                        android.util.Log.e(TAG, "Error forcing status bar color on UI thread: " + e.getMessage());
                    }
                }
            });

            // Method 4: Delayed reapplication to override any system changes
            decorView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        activity.getWindow().setStatusBarColor(color);
                        android.util.Log.d(TAG, "Status bar color reapplied after delay: " + colorString);
                    } catch (Exception e) {
                        android.util.Log.e(TAG, "Error reapplying status bar color: " + e.getMessage());
                    }
                }
            }, 100);

            // Method 5: Another delay to catch late overrides
            decorView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        activity.getWindow().setStatusBarColor(color);
                        android.util.Log.d(TAG, "Status bar color final reapplication: " + colorString);
                    } catch (Exception e) {
                        android.util.Log.e(TAG, "Error in final status bar color reapplication: " + e.getMessage());
                    }
                }
            }, 500);

            // Method 6: Set flags to prevent system from overriding
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                decorView.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            // Clear any flags that might interfere with status bar color
                            int currentFlags = decorView.getSystemUiVisibility();
                            currentFlags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                            decorView.setSystemUiVisibility(currentFlags);

                            // Reapply the color
                            activity.getWindow().setStatusBarColor(color);
                            android.util.Log.d(TAG, "Status bar color applied with flag clearing: " + colorString);
                        } catch (Exception e) {
                            android.util.Log.e(TAG, "Error applying status bar color with flag clearing: " + e.getMessage());
                        }
                    }
                });
            }

            android.util.Log.d(TAG, "Status bar color force application initiated: " + colorString);

        } catch (Exception e) {
            android.util.Log.e(TAG, "Error in forceApplyStatusBarColor: " + e.getMessage());
        }
    }

    /**
     * Force status bar color action handler
     */
    private void forceStatusBarColor(JSONArray args, CallbackContext callbackContext) {
        try {
            if (args.length() < 1) {
                callbackContext.error("Missing status bar color parameter");
                return;
            }

            String statusBarColor = args.getString(0);
            String statusBarStyle = "light"; // Default to light icons

            if (args.length() >= 2) {
                statusBarStyle = args.getString(1);
            }

            // Store the color for future use
            storedStatusBarColor = statusBarColor;
            storedStatusBarStyle = statusBarStyle;

            // Force apply the status bar color
            forceApplyStatusBarColor(statusBarColor);

            // Set the icon style
            View decorView = activity.getWindow().getDecorView();
            int currentFlags = decorView.getSystemUiVisibility();

            if ("dark".equals(statusBarStyle)) {
                decorView.setSystemUiVisibility(currentFlags | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            } else {
                decorView.setSystemUiVisibility(currentFlags & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }

            callbackContext.success("Status bar color forced to: " + statusBarColor);

        } catch (Exception e) {
            callbackContext.error("Error forcing status bar color: " + e.getMessage());
        }
    }
}
