package com.capacitorjs.plugins.statusbar;

import android.os.Build;
import android.graphics.Color;
import android.view.Window;

import androidx.activity.EdgeToEdge;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsControllerCompat;

import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.JSObject;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.annotation.PluginMethod;

@CapacitorPlugin(name = "StatusBar")
public class StatusBar extends Plugin {

    private boolean overlaysWebView = true;

    @Override
    public void load() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
            // Android 15+ — Use new API
            getActivity().runOnUiThread(() -> {
                EdgeToEdge.enable(getActivity());
            });
        } else {
            // Older Android — Manual edge-to-edge
            getActivity().runOnUiThread(() -> {
                Window window = getActivity().getWindow();
                WindowCompat.setDecorFitsSystemWindows(window, false);
                WindowInsetsControllerCompat controller =
                        new WindowInsetsControllerCompat(window, window.getDecorView());
                controller.setAppearanceLightStatusBars(true);
            });
        }
    }

    @PluginMethod
    public void setOverlaysWebView(PluginCall call) {
        overlaysWebView = call.getBoolean("overlay", true);
        call.resolve(); // No-op in Android 15+, handled by EdgeToEdge
    }

    @PluginMethod
    public void setBackgroundColor(PluginCall call) {
        String color = call.getString("color", "#000000");

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.VANILLA_ICE_CREAM) {
            // ✅ Only set status bar color on Android ≤ 14
            try {
                int parsedColor = Color.parseColor(color);
                getActivity().runOnUiThread(() -> {
                    getActivity().getWindow().setStatusBarColor(parsedColor);
                });
            } catch (IllegalArgumentException e) {
                call.reject("Invalid color format: " + color);
                return;
            }
        }
        // Android 15+ → Ignored

        call.resolve();
    }

    @PluginMethod
    public void getInfo(PluginCall call) {
        JSObject ret = new JSObject();
        ret.put("visible", true);
        ret.put("overlaysWebView", overlaysWebView);
        call.resolve(ret);
    }
}
