import { WebView } from "@tarojs/components";
import { useState } from "react";
import { useDidShow } from "@tarojs/taro";
import { createH5Ticket, getToken } from "../../services/api";

const H5_URL = String(process.env.TARO_APP_H5_URL ?? "https://wanderq.nianxx.com");
const H5_CACHE_VERSION = "auth-20260724-v1";

function buildH5Src(ticket?: string) {
  const separator = H5_URL.includes("?") ? "&" : "?";
  return H5_URL
    + separator
    + "v="
    + encodeURIComponent(H5_CACHE_VERSION)
    + (ticket ? "&h5_ticket=" + encodeURIComponent(ticket) : "");
}

export default function Index() {
  const [h5Src, setH5Src] = useState(buildH5Src);
  const [initialized, setInitialized] = useState(false);
  const [lastToken, setLastToken] = useState<string | null>(null);

  useDidShow(() => {
    const token = getToken();
    if (initialized && token === lastToken) return;
    setInitialized(true);
    setLastToken(token);

    if (!token) {
      setH5Src(buildH5Src());
      return;
    }

    createH5Ticket()
      .then(({ ticket }) => setH5Src(buildH5Src(ticket)))
      .catch(() => setH5Src(buildH5Src()));
  });

  return <WebView src={h5Src} />;
}
