import { useCallback, useEffect, useRef } from "react";
import { View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useUserStore } from "./store/user";
import { getToken } from "./utils/auth";
import { clearAdminTokens } from "./utils/adminAuth";
import { hapticFromTap, installTaroHaptics } from "./utils/haptics";
import { resumePendingOnboarding } from "./utils/onboarding";
import { ErrorBoundary } from "./components/ErrorBoundary";
import AgentBubble from "./components/AgentBubble";
import "./app.scss";

const PUBLIC_ROUTE_PREFIXES = [
  "pages/login",
  "pages/onboarding",
  "pages/agreement",
  "pages/privacy",
  "pages/search",
  "pages/about-intro",
  "pages/about-structure",
  "pages/home",
  "pages/news-list",
  "pages/learning-list",
  "pages/content-detail",
  "pages/member-showcase",
  "pages/branch-detail",
  "pages/media-matrix",
];

function isPublicRoute(route: string) {
  return PUBLIC_ROUTE_PREFIXES.some((prefix) => route === prefix || route.startsWith(`${prefix}/`));
}

function App(props) {
  const bootstrap = useUserStore((s) => s.bootstrap);
  const checkingOnboardingRef = useRef(false);

  const ensurePendingOnboarding = useCallback(async () => {
    if (checkingOnboardingRef.current || getToken()) return false;
    checkingOnboardingRef.current = true;
    try {
      return await resumePendingOnboarding(true);
    } finally {
      checkingOnboardingRef.current = false;
    }
  }, []);

  useEffect(() => {
    installTaroHaptics();
    clearAdminTokens();
    const run = async () => {
      const pages = Taro.getCurrentPages();
      const route = pages[pages.length - 1]?.route || "";
      if (await ensurePendingOnboarding()) return;
      const token = getToken();
      if (token) {
        void bootstrap();
        return;
      }
      if (!isPublicRoute(route)) {
        const pages = Taro.getCurrentPages();
        const page: any = pages[pages.length - 1];
        const options = page?.options || {};
        const query = Object.keys(options)
          .filter((key) => options[key] !== undefined && options[key] !== null && String(options[key]) !== "")
          .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(String(options[key]))}`)
          .join("&");
        const redirect = route ? `/${route}${query ? `?${query}` : ""}` : "";
        Taro.reLaunch({ url: redirect ? `/pages/login/index?redirect=${encodeURIComponent(redirect)}` : "/pages/login/index" });
      }
    };
    void run();
  }, [bootstrap, ensurePendingOnboarding]);

  useDidShow(() => {
    void ensurePendingOnboarding();
  });

  return (
    <ErrorBoundary>
      <View className="app-root" onClick={hapticFromTap}>
        {props.children}
        <AgentBubble unread={false} />
      </View>
    </ErrorBoundary>
  );
}

export default App;
