package com.nadi.player;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import com.getcapacitor.BridgeActivity;
import com.nadi.player.nativeplayer.NativePlayerPlugin;
import com.nadi.player.deviceidentity.DeviceIdentityPlugin;
import com.nadi.player.nativeads.NativeAdsPlugin;

/**
 * Capacitor host activity. Also responsible for:
 * - Creating the notification channel (Android 8+ requirement)
 * - Forwarding notification deep-links into the React app
 */
public class MainActivity extends BridgeActivity {

    private static final String CHANNEL_ID = "nadiplayer_default";
    private static final String CHANNEL_NAME = "Nadiplayer Notifications";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        registerPlugin(NativePlayerPlugin.class);
        registerPlugin(DeviceIdentityPlugin.class);
        registerPlugin(NativeAdsPlugin.class);
        super.onCreate(savedInstanceState);

        // Create notification channel BEFORE any permission request or
        // FCM registration — Android 8+ requires a channel to exist
        // before notifications can be posted.
        createNotificationChannel();

        forwardNotificationRoute(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        forwardNotificationRoute(intent);
    }

    /**
     * Create the default notification channel for FCM push messages.
     * Safe to call multiple times — the system ignores duplicates.
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            try {
                NotificationChannel channel = new NotificationChannel(
                        CHANNEL_ID,
                        CHANNEL_NAME,
                        NotificationManager.IMPORTANCE_DEFAULT
                );
                channel.setDescription("Notifications from Nadiplayer");
                channel.enableVibration(true);
                channel.setShowBadge(true);

                NotificationManager manager = getSystemService(NotificationManager.class);
                if (manager != null) {
                    manager.createNotificationChannel(channel);
                }
            } catch (Exception e) {
                // Never crash the app over notification channel setup
                android.util.Log.w("Nadiplayer", "Failed to create notification channel", e);
            }
        }
    }

    private void forwardNotificationRoute(Intent intent) {
        if (intent == null || intent.getExtras() == null) return;
        final String route = intent.getStringExtra("route");
        if (route == null || route.isEmpty()) return;
        try {
            if (getBridge() == null || getBridge().getWebView() == null) return;
            getBridge().getWebView().post(new Runnable() {
                @Override public void run() {
                    try {
                        String safe = route.replace("\\", "\\\\").replace("'", "\\'");
                        getBridge().getWebView().evaluateJavascript(
                                "window.dispatchEvent(new CustomEvent('nadiplay:notification-route', " +
                                        "{ detail: { route: '" + safe + "' } }));",
                                null
                        );
                    } catch (Exception e) {
                        android.util.Log.w("Nadiplayer", "Failed to forward notification route", e);
                    }
                }
            });
        } catch (Exception e) {
            android.util.Log.w("Nadiplayer", "forwardNotificationRoute error", e);
        }
    }
}
