import Taro from "@tarojs/taro";
import { onboardingStatus } from "../api/auth";

export const ONBOARDING_TOKEN_KEY = "xlh_onboarding_token";
export const PC_LOGIN_ID_KEY = "xlh_pc_login_id";

export function getOnboardingToken() {
  return Taro.getStorageSync(ONBOARDING_TOKEN_KEY) || "";
}

export function getOnboardingPcLoginId() {
  return Taro.getStorageSync(PC_LOGIN_ID_KEY) || "";
}

export function saveOnboardingSession(onboardingToken: string, pcLoginId?: string) {
  Taro.setStorageSync(ONBOARDING_TOKEN_KEY, onboardingToken);
  if (pcLoginId) Taro.setStorageSync(PC_LOGIN_ID_KEY, pcLoginId);
}

export function clearOnboardingSession() {
  Taro.removeStorageSync(ONBOARDING_TOKEN_KEY);
  Taro.removeStorageSync(PC_LOGIN_ID_KEY);
}

export function isOnboardingRoute(route: string) {
  return route === "pages/onboarding"
    || route.startsWith("pages/onboarding/")
    || route.startsWith("pages/onboarding-");
}

export async function resumePendingOnboarding(showToast = false) {
  const onboardingToken = getOnboardingToken();
  if (!onboardingToken) return false;

  const pages = Taro.getCurrentPages();
  const route = pages[pages.length - 1]?.route || "";
  if (isOnboardingRoute(route)) return true;

  try {
    await onboardingStatus(onboardingToken);
  } catch {
    clearOnboardingSession();
    return false;
  }

  if (showToast) {
    Taro.showToast({ title: "继续完成注册补全", icon: "none" });
  }
  await Taro.reLaunch({ url: "/pages/onboarding/index" });
  return true;
}

export function currentPageUrl() {
  const pages = Taro.getCurrentPages();
  const page: any = pages[pages.length - 1];
  const route = page?.route ? `/${page.route}` : "";
  if (!route) return "";
  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("&");
  return `${route}${query ? `?${query}` : ""}`;
}

export function normalizeInternalUrl(raw: unknown, fallback = "") {
  let value = Array.isArray(raw) ? String(raw[0] || "") : String(raw || "");
  if (!value) return fallback;
  try {
    value = decodeURIComponent(value);
  } catch {
    // keep original value
  }
  if (!value.startsWith("/pages/") || value.startsWith("//")) return fallback;
  return value;
}

export async function navigateAfterAuth(rawRedirect: unknown, fallback = "/pages/home/index") {
  const target = normalizeInternalUrl(rawRedirect, fallback);
  await Taro.reLaunch({ url: target });
}
