"use client";

import { useEffect, useEffectEvent, useRef } from "react";
import { usePathname } from "next/navigation";
import type { PluginListenerHandle } from "@capacitor/core";
import { App } from "@capacitor/app";
import { Browser } from "@capacitor/browser";
import { SplashScreen } from "@capacitor/splash-screen";
import { useVersionedRouter } from "@/hooks/use-versioned-router";
import { HOME, navigateBack } from "@/lib/navigation/back";
import NativeUpdatePrompt from "@/lib/update/native/update-prompt";
import { getNativeUpdateState } from "@/lib/update/native/state";
import { routeForDeepLink } from "./deep-links";
import { onGatewayClosed, settlePayment } from "./payment-return";

// Back leaves the app from these.
const ROOT_ROUTES = ["/", HOME, "/auth/login"];
// Bottom-menu tabs: back goes to the home tab first.
const TAB_ROUTES = ["/explore", "/practice", "/submissions", "/profile"];

// Dialogs, sheets and menus that Escape closes.
const OVERLAY_SELECTOR = [
  '[role="dialog"][data-state="open"]',
  '[role="alertdialog"][data-state="open"]',
  "[data-radix-popper-content-wrapper]",
].join(",");

// The launch URL belongs to the process: handle it once per session, not per remount.
const LAUNCH_URL_KEY = "native-launch-url-handled";

/** App-only UI: splash, deep links, back button, update prompt. Rendered inside AuthProvider. */
export default function NativeShell() {
  const router = useVersionedRouter();
  const pathname = usePathname();

  // The first screen is ready: hide the splash.
  useEffect(() => {
    requestAnimationFrame(() => {
      SplashScreen.hide().catch(() => { });
    });
  }, []);

  // Effect events: the listeners are registered once but see the current route.
  const openDeepLink = useEffectEvent((url: string) => {
    const route = routeForDeepLink(url);
    if (!route) return;

    if (route.startsWith("/payment/result")) {
      settlePayment();
      Browser.close().catch(() => { });
    }
    router.push(route);
  });

  // The start screen ("/") moves on to home or login by itself and would override a link
  // opened while it shows (a cold start from a link), so the link waits for it.
  const pendingLink = useRef<string | null>(null);

  const openLink = useEffectEvent((url: string) => {
    if (normalize(pathname) === "/") pendingLink.current = url;
    else openDeepLink(url);
  });

  useEffect(() => {
    const url = pendingLink.current;
    if (!url || normalize(pathname) === "/") return;
    pendingLink.current = null;
    openDeepLink(url);
  }, [pathname]);

  const onGatewayTabClosed = useEffectEvent(() => {
    onGatewayClosed((route) => router.replace(route));
  });

  const onBackButton = useEffectEvent(() => {
    // Nothing behind a required update.
    if (getNativeUpdateState().kind === "required") {
      App.minimizeApp().catch(() => { });
      return;
    }

    if (closeTopOverlay()) return;

    const path = normalize(pathname);

    if (TAB_ROUTES.includes(path)) {
      router.replace(HOME);
      return;
    }

    if (ROOT_ROUTES.includes(path)) {
      // Like Android itself: background the app, keeping its state.
      App.minimizeApp().catch(() => { });
      return;
    }

    navigateBack(router);
  });

  useEffect(() => {
    const handles: Promise<PluginListenerHandle>[] = [];

    App.getLaunchUrl()
      .then((launch) => {
        if (!launch?.url) return;
        try {
          if (sessionStorage.getItem(LAUNCH_URL_KEY) === launch.url) return;
          sessionStorage.setItem(LAUNCH_URL_KEY, launch.url);
        } catch { }
        openLink(launch.url);
      })
      .catch(() => { });

    handles.push(App.addListener("appUrlOpen", ({ url }) => openLink(url)));
    handles.push(Browser.addListener("browserFinished", () => onGatewayTabClosed()));
    handles.push(App.addListener("backButton", () => onBackButton()));

    return () => {
      handles.forEach((handle) => {
        handle.then((h) => h.remove()).catch(() => { });
      });
    };
  }, []);

  return <NativeUpdatePrompt />;
}

function normalize(path: string | null): string {
  return (path ?? "/").replace(/\/+$/, "") || "/";
}

/** Close the top dialog/sheet/menu the way Escape does. False if none is open. */
function closeTopOverlay(): boolean {
  if (!document.querySelector(OVERLAY_SELECTOR)) return false;

  // Radix listens on the document, so this closes the top layer.
  document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", code: "Escape", bubbles: true, cancelable: true }));
  return true;
}
