import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Text, View } from '@tarojs/components';
import { appEnv, assertFrontendSecretsAreAbsent, ensureRuntimeConfigLoaded } from '@/env';
import { resolveTenant } from '@/services/api';
import './index.css';

function hostFromRuntime() {
  if (process.env.TARO_ENV === 'h5' && typeof window !== 'undefined') return window.location.host;
  return '';
}

function landingPath() {
  if (appEnv.portal === 'tenant-admin') return '/pages/tenant-admin/workbench/index';
  if (appEnv.portal === 'platform-admin') return '/pages/platform-admin/workbench/index';
  return '/pages/student/home/index';
}

export default function BootstrapPage() {
  const [status, setStatus] = useState('正在解析租户');
  const [error, setError] = useState('');

  useEffect(() => {
    assertFrontendSecretsAreAbsent();
    ensureRuntimeConfigLoaded()
      .then(() => resolveTenant({ host: hostFromRuntime() }))
      .then(() => {
        setStatus('租户解析完成');
        Taro.redirectTo({ url: landingPath() });
      })
      .catch((nextError: Error) => {
        setError(nextError.message);
        setStatus('租户解析失败');
      });
  }, []);

  return (
    <View className='bootstrap-page'>
      <View className='bootstrap-shell'>
        <Text className='eyebrow'>Tiku SaaS</Text>
        <Text className='title'>正在进入题库系统</Text>
        <Text className='status'>{status}</Text>
        {error ? <Text className='error'>{error}</Text> : null}
        {error ? (
          <Button className='primary-button' onClick={() => Taro.reLaunch({ url: '/pages/bootstrap/index' })}>
            重新尝试
          </Button>
        ) : null}
      </View>
    </View>
  );
}
