import { isTestEnvInPixui, getUId, copyTextInPubgm } from 'pixui-runtime';
import { GameletAPI } from 'gamelet-pixui-frame';
import { h, Fragment } from 'preact';

import { useState, useEffect } from 'preact/hooks';


import DebugPopup from './debug-popup';
import { getBasicInfo } from './helper';
import { checkInWhite } from './white';

import type { AppWithDebugProps } from './types';


export const AppWithDebug = ({
  children,
  vconsoleEnabled = true,
  uid = '',
  copyText,
  contentList,
  whiteListUrl,
}: AppWithDebugProps) => {
  const [userInfo, setUserInfo] = useState<any>({});
  const [enabled, setEnabled] = useState<boolean>(false);

  useEffect(() => {
    onInit();
  }, []);

  const onInit = async () => {
    const userInfo = await GameletAPI.getUserData();

    setUserInfo(userInfo);
    const result = await checkEnabled(userInfo);
    setEnabled(!!result);
  };

  const checkEnabled = async (userInfo) => {
    if (!isTestEnvInPixui()) {
      const result = await checkInWhite({
        whiteListUrl,
        uid: uid || getUId(userInfo),
      });
      return result;
    }

    // 检查是否为开发环境或者 URL 参数中包含 vconsole=true
    const shouldEnableVConsole = vconsoleEnabled
    || (typeof window !== 'undefined' && (
      window.location.hostname === 'localhost'
      || window.location.hostname === '127.0.0.1'
      || window.location.search.includes('vconsole=true')
      || window.location.search.includes('debug=true')
    ));
    return shouldEnableVConsole;
  };

  const list = getBasicInfo(uid || getUId(userInfo));

  return (
    <Fragment>
      {children}
      {enabled && (
      <DebugPopup
        copyText={copyText || copyTextInPubgm}
        onHide={() => (setEnabled(false))}
        contentList={[
          ...list,
          ...(contentList || []),
        ]}
      />
      )}
    </Fragment>
  );
};

export default AppWithDebug;
