package com.gem.media.ad;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.ads.cal.notes.R;
import com.gem.media.InitA;
import com.google.android.gms.ads.nativead.NativeAdView;
import com.or.ange.dot.utils.LLog;

/**
 * VNA 专用广告展示 Activity。
 * 特性：5s autoClose + dismissReason 上报 + 沉浸式全屏 + 自定义关闭按钮。
 */
public class VNActivity extends Activity {
    private static final String TAG = "VNActivity";

    // 关闭原因常量
    public static final int DISMISS_AUTO_CLOSE = 1;
    public static final int DISMISS_USER_CLICK = 2;
    public static final int DISMISS_USER_CLOSE = 3;
    public static final int DISMISS_USER_LEAVE = 4;

    // 计时器参数
    private static final long AD_DISPLAY_DURATION_MS = 10_000L;          // Phase 1 时长
    private static final long AD_EXTENDED_DURATION_MS = 5_000L;         // Phase 2 延长时长
    private static final long MIN_DISPLAY_AFTER_EXPOSURE_MS = 3_000L;   // 曝光后最少展示时间

    private boolean isFinished;
    private int dismissReason = DISMISS_USER_LEAVE;
    private boolean isAdExposed;      // 是否收到曝光回调
    private boolean isExtended;       // 是否已进入 Phase 2
    private long adShowStartTime;     // 定时器启动时间戳

    private final Handler autoCloseHandler = new Handler(Looper.getMainLooper());
    private final Runnable autoCloseRunnable = this::handleAutoClose;

    // R1: 从 Intent 读取的可配置展示时长
    private long adDisplayDurationMs = AD_DISPLAY_DURATION_MS;

    // P1-2 fix: onPause 时暂停 autoClose 定时器，onResume 时恢复
    private long pauseElapsedRealtime = 0;
    /**
     * 两阶段定时器核心逻辑：
     * isAdExposed=T → 正常关闭（曝光后到期）
     * isExtended=T  → Phase2 到期，无条件关闭
     * 其余           → Phase1 到期无曝光，延长进入 Phase2
     */
    private void handleAutoClose() {
        if (isFinishing()) return;
        if (isAdExposed || isExtended) {
            dismissReason = DISMISS_AUTO_CLOSE;
            finish();
        } else {
            isExtended = true;
            autoCloseHandler.postDelayed(autoCloseRunnable, AD_EXTENDED_DURATION_MS);
            LLog.d(TAG, "No exposure in 5s, extending to 10s");
        }
    }

    public void setDismissReason(int reason) {
        this.dismissReason = reason;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(0, 0);
        try {
            setFinishOnTouchOutside(false);
            if (getWindow() != null) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
            }
        } catch (Exception e) {
            // ignore
        }
        setContentView(R.layout.vna_n_layout);
        // VNA V2: 从 Intent 读取展示配置
        adDisplayDurationMs = getIntent().getLongExtra("showDurationMs", 10_000L);
        enableImmersiveFullScreen();
        adjustContainerForOrientation();
        report("onCreate", "");
        start();
    }

    /**
     * 广告曝光确认回调。
     * Option C 逻辑：剩余时间 < 3s 时补到 3s，否则让原始定时器自然到期。
     */
    public void onExposureConfirmed() {
        if (isFinishing() || isAdExposed) return;
        isAdExposed = true;

        long elapsed = SystemClock.elapsedRealtime() - adShowStartTime;
        long minimumCloseTime = elapsed + MIN_DISPLAY_AFTER_EXPOSURE_MS;
        long currentDeadline = isExtended
                ? (adDisplayDurationMs + AD_EXTENDED_DURATION_MS)
                : adDisplayDurationMs;

        if (minimumCloseTime > currentDeadline) {
            // 剩余时间不足 3s → 取消旧 timer，重新调度 3s
            autoCloseHandler.removeCallbacks(autoCloseRunnable);
            autoCloseHandler.postDelayed(autoCloseRunnable, MIN_DISPLAY_AFTER_EXPOSURE_MS);
            LLog.d(TAG, "Exposure at +" + elapsed + "ms, extending display by 3s");
        } else {
            // 剩余时间充足，让原始 timer 自然到期
            LLog.d(TAG, "Exposure at +" + elapsed + "ms, remaining time sufficient");
        }
    }

    private void start() {
        if (VNANativeAdManager.getInstance().isNativeAdReady()) {
            try {
                NativeAdView nativeAdView = findViewById(R.id.vna_native_ad_view);
                int result = VNANativeAdManager.getInstance().showAd(nativeAdView);
                if (result != 0) {
                    report("show_fail", "result=" + result);
                    finish();
                    return;
                }

                // 设置关闭按钮
                ImageView closeBtn = findViewById(R.id.vna_close_button);
                if (closeBtn != null) {
                    closeBtn.setOnClickListener(v -> {
                        dismissReason = DISMISS_USER_CLOSE;
                        finish();
                    });
                }

                // 启动曝光感知的自适应关闭计时器
                adShowStartTime = SystemClock.elapsedRealtime();
                isAdExposed = false;
                isExtended = false;
                autoCloseHandler.removeCallbacks(autoCloseRunnable);
                autoCloseHandler.postDelayed(autoCloseRunnable, adDisplayDurationMs);
            } catch (Exception e) {
                autoCloseHandler.removeCallbacksAndMessages(null);
                report("ex", Log.getStackTraceString(e));
                finish();
            }
        } else {
            autoCloseHandler.removeCallbacksAndMessages(null);
            report("not_cache", "");
            finish();
        }
    }

    @Override
    public void finish() {
        if (isFinished) {
            super.finish();
            overridePendingTransition(0, 0);
            return;
        }
        // 兜底：广告已曝光但 dismissReason 仍是默认值 → 修正为 USER_CLOSE
        // 场景：Android 13+ 手势返回可能绕过 onBackPressed，直接调用 finish()
        if (isAdExposed && dismissReason == DISMISS_USER_LEAVE) {
            dismissReason = DISMISS_USER_CLOSE;
        }
        autoCloseHandler.removeCallbacks(autoCloseRunnable);
        reportDismissReason(dismissReason);
        report("finish", "reason=" + dismissReason);
        isFinished = true;
        super.finish();
        overridePendingTransition(0, 0);
    }

    @Override
    protected void onDestroy() {
        autoCloseHandler.removeCallbacksAndMessages(null);
        VNANativeAdManager.getInstance().destroyAd();
        report("destroy", "");
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        dismissReason = DISMISS_USER_CLOSE;
        finish();
    }

    /**
     * 通过 5002 Messenger 向 core 上报 dismissReason。
     */
    private void reportDismissReason(int reason) {
        try {
            Messenger messenger = InitA.getInstance().getMessenger();
            if (messenger == null) {
                LLog.w(TAG, "reportDismissReason: messenger is null");
                return;
            }
            Message message = Message.obtain();
            message.what = 5002;
            message.arg1 = reason;
            Bundle bundle = new Bundle();
            bundle.putString("type", "vna_dismiss");
            bundle.putInt("dismissReason", reason);
            bundle.putString("ad_format", "native");
            message.setData(bundle);
            messenger.send(message);
            LLog.d(TAG, "reportDismissReason: " + reason);
        } catch (Exception e) {
            LLog.e(TAG, "reportDismissReason error: " + e.getMessage());
        }
    }

    /**
     * 通用事件上报（通过 5002 Messenger）。
     */
    private void report(String type, String reason) {
        try {
            Messenger messenger = InitA.getInstance().getMessenger();
            if (messenger == null) {
                return;
            }
            Message message = Message.obtain();
            message.what = 5002;
            Bundle bundle = new Bundle();
            bundle.putString("type", type);
            bundle.putString("reason", reason);
            bundle.putString("ad_format", "native");
            message.setData(bundle);
            messenger.send(message);
        } catch (Exception e) {
            LLog.e(TAG, "report error: " + e.getMessage());
        }
    }

    /**
     * 横屏沉浸式：仅在横屏时隐藏状态栏 + 导航栏。
     * 竖屏不做处理，保持系统栏正常显示。
     */
    private void enableImmersiveFullScreen() {
        if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
            return;
        }
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.setDecorFitsSystemWindows(false);
            WindowInsetsController controller = window.getInsetsController();
            if (controller != null) {
                controller.hide(android.view.WindowInsets.Type.statusBars()
                        | android.view.WindowInsets.Type.navigationBars());
                controller.setSystemBarsBehavior(
                        WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
            }
        } else {
            View decorView = window.getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                            | 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);
        }
    }

    /**
     * 根据当前方向调整广告容器宽度：
     * 横屏 → 限制为 shortSide - 2*margin（与竖屏视觉一致）
     * 竖屏 → 限制为屏幕宽度的 75%（等比缩小广告内容）
     */
    private void adjustContainerForOrientation() {
        View wrapper = findViewById(R.id.vna_ad_wrapper);
        if (wrapper == null) return;
        ViewGroup.LayoutParams params = wrapper.getLayoutParams();
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            int shortSidePx = Math.min(
                    getResources().getDisplayMetrics().widthPixels,
                    getResources().getDisplayMetrics().heightPixels);
            int marginPx = (int) (16 * getResources().getDisplayMetrics().density + 0.5f) * 2;
            params.width = shortSidePx - marginPx;
        } else {
            int screenWidth = getResources().getDisplayMetrics().widthPixels;
            params.width = (int) (screenWidth * 0.75);
        }
        wrapper.setLayoutParams(params);
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            enableImmersiveFullScreen();
        } catch (Exception e) {
            // ignore
        }
        if (pauseElapsedRealtime > 0 && adShowStartTime > 0) {
            long pauseDuration = SystemClock.elapsedRealtime() - pauseElapsedRealtime;
            adShowStartTime += pauseDuration;
            long elapsed = SystemClock.elapsedRealtime() - adShowStartTime;
            long deadline = isExtended
                    ? (adDisplayDurationMs + AD_EXTENDED_DURATION_MS)
                    : adDisplayDurationMs;
            long remaining = deadline - elapsed;
            if (remaining > 0) {
                autoCloseHandler.removeCallbacks(autoCloseRunnable);
                autoCloseHandler.postDelayed(autoCloseRunnable, remaining);
            } else {
                autoCloseHandler.post(autoCloseRunnable);
            }
            pauseElapsedRealtime = 0;
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        enableImmersiveFullScreen();
        adjustContainerForOrientation();
    }
}
