import { useEffect, useRef, useState } from 'react';
import { eventBus } from './lib/EventBus';
import { pmBridge } from './lib/PostMessageBridge';
import { useSetAtom, useAtomValue } from 'jotai'
import { openModalAction } from './store';
import { LoginIndex } from './components/login';
import { RealNameIndex } from './components/real-name';
import { PaymentIndex } from './components/payment';
import { report } from './components/report';
import { getH5GameLinkApi } from './api';
import { getURLparams } from './utils';
import { init } from './components/init';
import { nativeInit, nativeLogin, nativePay, nativeReport, nativeLogout, nativeOnLogout } from './native';
import SlideBarIndex from './components/slide-bar';
import { FloatingButton } from './components/FloatingButton';
import { userStateAtom } from './store/user-atom';
import { logoutApi } from './api/login';

function App() {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [iframeUrl, setIframeUrl] = useState<string>('');
  const [isSlideBarOpen, setIsSlideBarOpen] = useState(false);

  const openModal = useSetAtom(openModalAction);
  const userState = useAtomValue(userStateAtom);

  const getGameUrl = async () => {
    const res = await getH5GameLinkApi({ game_id: getURLparams('game_id') || '' })
    setIframeUrl(`${res.game_url}?game_id=${getURLparams('game_id') || ''}&time=${Math.round(new Date().getTime() / 1000)}`)
  }


  // 初始化通信桥
  useEffect(() => {
    if (iframeRef.current) {
      pmBridge.init(iframeRef.current);
    }
    return () => pmBridge.destroy();
  }, []);

  // EventBus 事件订阅
  useEffect(() => {
    // 处理登录请求
    const handleLoginReq = (payload: any) => {
      if (getURLparams('is_native') === 'true') {
        openModal({ name: 'login', item: { isOpen: false, requestId: payload.requestId, data: payload.data } })
        nativeLogin(payload)
      } else {
        openModal({ name: 'login', item: { isOpen: true, requestId: payload.requestId, data: payload.data } })
        console.log("登录")
      }

    };

    // 处理支付请求
    const handlePayReq = (payload: any) => {
      if (getURLparams('is_native') === 'true') {
        openModal({ name: 'payment', item: { isOpen: false, requestId: payload.requestId, data: payload.data } })
        nativePay(payload)
      } else {
        openModal({ name: 'payment', item: { isOpen: true, requestId: payload.requestId, data: payload.data } })
      }
    };

    // 处理上报请求
    const handleReportReq = (payload: any) => {
      openModal({ name: 'report', item: { isOpen: true, requestId: payload.requestId, data: payload.data } })
      if (getURLparams('is_native') === 'true') {
        nativeReport(payload)
      } else {
        report(payload)
      }
    };

    // 处理初始化请求
    const handleInitReq = (payload: any) => {
      openModal({ name: 'init', item: { isOpen: true, requestId: payload.requestId, data: payload.data } })
      // 微端是真
      if (getURLparams('is_native') === 'true') {
        nativeInit(payload)
      } else {
        init(payload)
      }
    }

    // 处理退出登录请求
    const handleLogoutReq = async (payload: any) => {
      openModal({ name: 'logout', item: { isOpen: true, requestId: payload.requestId, data: payload.data } })
      if (getURLparams('is_native') === 'true') {
        nativeLogout(payload)
      } else {
        await logoutApi()
        pmBridge.sendToIframe('LOGOUT_REQUEST', { success: true, message: "退出登录成功" }, payload.requestId);
      }
    }

    // 处理退出登录回调
    const handleOnLogoutReq = (payload: any) => {
      openModal({ name: 'onLogout', item: { isOpen: false, requestId: payload.requestId, data: payload.data } })
      if (getURLparams('is_native') === 'true') {
        nativeOnLogout(payload)
      }
    }

    eventBus.on('LOGIN_REQUEST', handleLoginReq);
    eventBus.on('PAY_REQUEST', handlePayReq);
    eventBus.on('REPORT_REQUEST', handleReportReq);
    eventBus.on('INIT_REQUEST', handleInitReq);
    eventBus.on('LOGOUT_REQUEST', handleLogoutReq);
    eventBus.on('ONLOGOUT', handleOnLogoutReq);

    return () => {
      eventBus.off('LOGIN_REQUEST', handleLoginReq);
      eventBus.off('PAY_REQUEST', handlePayReq);
      eventBus.off('REPORT_REQUEST', handleReportReq);
      eventBus.off('INIT_REQUEST', handleInitReq);
    };
  }, []);


  // 请求记载游戏链接
  useEffect(() => {
    getGameUrl()
  }, []);

  return (
    <div className="w-full h-screen relative bg-white font-sans overflow-hidden">

      {/* Iframe 游戏容器 */}
      <iframe
        ref={iframeRef}
        src={iframeUrl}
        title="Game Container"
        className="w-full h-full border-none"
        sandbox="allow-scripts allow-same-origin allow-forms"
      />
      {userState.token}

      {/* 渲染弹窗 */}
      <LoginIndex />
      <RealNameIndex />
      <PaymentIndex />

      {/* 登录后显示浮标球 */}
      {userState.token && (
        <FloatingButton onClick={() => setIsSlideBarOpen(true)} />
      )}

      {/* 侧边栏 */}
      {isSlideBarOpen && (
        <SlideBarIndex onClose={() => setIsSlideBarOpen(false)} />
      )}


    </div>
  );
}

export default App;
