package com.gnexus.shserv;

import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.CapConfig;

public class MainActivity extends BridgeActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme_NoActionBar);

        // If a server URL has been configured via /mobile-setup, load the SPA
        // from the remote server instead of the bundled assets. This allows
        // updating the UI without rebuilding the APK.
        SharedPreferences prefs = getSharedPreferences("CapacitorStorage", MODE_PRIVATE);
        String serverUrl = prefs.getString("shserv_server_url", null);

        if (serverUrl != null && !serverUrl.isEmpty()) {
            this.config = new CapConfig.Builder(this)
                .setServerUrl(serverUrl)
                .create();
        }

        super.onCreate(savedInstanceState);

        // When loading from a remote server, clear WebView cache so updated
        // JS/CSS assets are always fetched fresh instead of served from disk.
        if (serverUrl != null && !serverUrl.isEmpty()) {
            WebView webView = (WebView) findViewById(com.getcapacitor.android.R.id.webview);
            if (webView != null) {
                webView.clearCache(true);
            }
        }

        // Prevent edge-to-edge: content must NOT draw behind status bar
        Window window = getWindow();
        WindowCompat.setDecorFitsSystemWindows(window, true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        // Capacitor SystemBars plugin installs an OnApplyWindowInsetsListener
        // that intercepts system bars insets and returns them as 0. This breaks
        // fitsSystemWindows. We reset it and force the CoordinatorLayout
        // (WebView parent) to handle insets natively.
        View webView = findViewById(com.getcapacitor.android.R.id.webview);
        if (webView != null) {
            ViewGroup parent = (ViewGroup) webView.getParent();
            if (parent != null) {
                ViewCompat.setOnApplyWindowInsetsListener(parent, null);
                parent.setFitsSystemWindows(true);
            }
        }
    }
}
