// Player auth modal component
const { useState, useEffect } = React;

function PlayerAuthModal({ isOpen, onClose, onLoginSuccess, currentPlayer, onLogout, viewOtherPlayer, lang }) {
  const str = window.UI_STRINGS[lang] || window.UI_STRINGS.zh;

  const [mode, setMode] = useState('login');
  const [isEdit, setIsEdit] = useState(false);
  const [qq, setQq] = useState('');
  const [gameId, setGameId] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPw, setConfirmPw] = useState('');
  const [externalContact, setExternalContact] = useState('');
  const [userRegionMode, setUserRegionMode] = useState('cn');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [loading, setLoading] = useState(false);
  const [showIdConfirm, setShowIdConfirm] = useState(false);

  const isViewOther = !!viewOtherPlayer;
  const targetPlayer = isViewOther ? viewOtherPlayer : currentPlayer;

  useEffect(() => {
    if (isOpen) {
      setError(''); setSuccess('');
      setIsEdit(false);
      setShowIdConfirm(false);
      setUserRegionMode('cn');
      setExternalContact('');
      if (targetPlayer) {
        setMode('profile');
        setQq(targetPlayer.qq || '');
        setGameId(targetPlayer.gameId || '');
        setExternalContact(targetPlayer.contactExternal || '');
      } else {
        setMode('login');
        setQq(''); setGameId(''); setPassword(''); setConfirmPw('');
      }
    }
  }, [isOpen, targetPlayer]);

  if (!isOpen) return null;

  const handleLogin = async (e) => {
    e.preventDefault();
    setError(''); setSuccess('');
    setLoading(true);
    const data = await window.api.playerLogin(qq, password);
    setLoading(false);
    if (data.success) {
      localStorage.setItem('player_token', data.token);
      onLoginSuccess(data.player);
      onClose();
    } else {
      setError(data.error || '登录失败');
    }
  };

  const onClickRegisterCheck = (e) => {
    e.preventDefault();
    setError('');
    if (!/^\d{6,12}$/.test(gameId)) {
      return setError('游戏ID只能填写6‑12位纯数字！');
    }
    if (password !== confirmPw) {
      return setError('两次输入的密码不一致');
    }
    if (userRegionMode === 'cn') {
      if (!qq) return setError('国内模式请填写QQ号');
    } else {
      if (!externalContact) return setError('海外模式请填写Discord纯数字ID或者联系邮箱');
    }
    setShowIdConfirm(true);
  };

  const doRealRegister = async () => {
    setShowIdConfirm(false);
    setLoading(true);
    const registerPayload = {
      qq: userRegionMode === 'cn' ? qq : '',
      contactExternal: userRegionMode === 'intl' ? externalContact : '',
      gameId: gameId,
      password: password,
      regionMode: userRegionMode
    };
    const data = await window.api.playerRegister(registerPayload);
    setLoading(false);
    if (data.success) {
      if (data.needConfirmation) {
        setSuccess(data.message || '注册成功！请检查邮箱确认。');
        // 不清除表单，让用户看到自己填的内容
      } else {
        localStorage.setItem('player_token', data.token);
        onLoginSuccess(data.player);
        onClose();
      }
    } else {
      setError(data.error || '注册失败');
    }
  };

  const handleUpdateProfile = async (e) => {
    e.preventDefault();
    setError(''); setSuccess('');
    setLoading(true);
    const payload = {};
    if (password) {
      if (!confirmPw) return setError('请填写原密码');
      payload.current_password = confirmPw;
      payload.new_password = password;
    }
    const data = await window.api.playerUpdate(payload);
    setLoading(false);
    if (data.success) {
      setSuccess('密码修改成功！');
      onLoginSuccess(data.player);
      setPassword(''); setConfirmPw('');
      setIsEdit(false);
    } else {
      setError(data.error || '修改失败');
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('player_token');
    onLogout();
    onClose();
  };

  // ===== 样式对象（与之前一致）=====
  const modalStyle = {
    position: 'fixed', inset: 0, zIndex: 1000,
    background: 'rgba(0,0,0,0.6)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    backdropFilter: 'blur(2px)',
  };
  const boxStyle = {
    background: 'linear-gradient(180deg, var(--bg-1), var(--bg-2))',
    border: '1px solid var(--border-0)',
    borderRadius: 6, padding: 28,
    width: 420, maxWidth: '90vw',
    boxShadow: '0 20px 60px rgba(0,0,0,0.5), 0 0 40px rgba(196,90,58,0.08)',
  };
  const confirmOverlayStyle = {
    position: 'fixed', inset: 0, zIndex: 2000,
    background: 'rgba(0,0,0,0.7)',
    display: 'flex', alignItems: 'center', justifyContent: 'center'
  };
  const confirmBoxStyle = {
    background: 'var(--bg-1)', border: '1px solid var(--border-0)',
    borderRadius: 6, padding: 22, width: 340, maxWidth: '90vw'
  };
  const btnPrimary = {
    width: '100%', padding: '10px 0',
    background: 'linear-gradient(135deg, var(--accent-rust), var(--accent-rust-dim))',
    border: '1px solid var(--accent-rust)',
    borderRadius: 3, color: '#fff', cursor: 'pointer',
    fontSize: 13, fontWeight: 500,
    boxShadow: '0 2px 6px rgba(196,90,58,0.3)',
    fontFamily: 'var(--sans)',
    marginTop: 6,
    opacity: loading ? 0.6 : 1,
  };
  const btnSecondary = {
    padding: '6px 0', background: 'transparent', border: 'none',
    color: 'var(--accent-mustard)', cursor: 'pointer',
    fontSize: 12, fontFamily: 'var(--sans)',
  };
  const btnRow = { display: 'flex', gap: 10, marginTop: 16 };
  const inputSt = {
    width: '100%', height: 38, padding: '0 10px',
    background: 'var(--bg-0)', border: '1px solid var(--border-1)',
    borderRadius: 3, color: 'var(--text-0)',
    fontSize: 13, fontFamily: 'var(--sans)',
    outline: 'none',
  };
  const inputDisabled = { ...inputSt, opacity: 0.5, cursor: "not-allowed" };
  const labelSt = {
    display: 'block', color: 'var(--text-2)', fontSize: 11,
    marginBottom: 5, letterSpacing: 0.5,
  };
  const radioWrap = { display: "flex", gap: "16px", margin: "6px 0 12px 0" };

  return (
    <div style={modalStyle} onClick={onClose}>
      <div style={boxStyle} onClick={(e) => e.stopPropagation()}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
          <h3 style={{ margin: 0, color: 'var(--text-0)', fontSize: 17 }}>
            {mode === 'login' && str.playerLogin}
            {mode === 'register' && str.playerRegister}
            {mode === 'profile' && (isViewOther ? str.playerViewProfile : str.playerProfile)}
          </h3>
          <button onClick={onClose} style={{
            background: 'transparent', border: 'none', color: 'var(--text-3)',
            cursor: 'pointer', fontSize: 20, padding: 0, lineHeight: 1,
          }}>×</button>
        </div>

        {mode === 'login' && (
          <form onSubmit={handleLogin} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div>
              <label style={labelSt}>{str.accountLabel}</label>
              <input type="text" style={inputSt} value={qq}
                     onChange={(e) => setQq(e.target.value)} placeholder={str.accountLabel} required autoFocus />
            </div>
            <div>
              <label style={labelSt}>{str.passwordLabel}</label>
              <input type="password" style={inputSt} value={password}
                     onChange={(e) => setPassword(e.target.value)} placeholder={str.passwordPlaceholder} required />
            </div>
            {error && <div style={{ color: 'var(--danger)', fontSize: 12, padding: 8, background: 'rgba(214,69,69,0.1)', borderRadius: 3, border: '1px solid rgba(214,69,69,0.3)' }}>{error}</div>}
            <button type="submit" style={btnPrimary} disabled={loading}>
              {loading ? str.loading : str.loginButton}
            </button>
            <div style={{ textAlign: 'center' }}>
              <span style={{ fontSize: 12, color: 'var(--text-2)' }}>{str.noAccountYet}</span>
              <button type="button" style={btnSecondary} onClick={() => setMode('register')}>{str.registerNow}</button>
            </div>
          </form>
        )}

        {mode === 'register' && (
          <form onSubmit={onClickRegisterCheck} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <label style={labelSt}>{str.playerTypeLabel}</label>
            <div style={radioWrap}>
              <label style={{ fontSize: 12, color: 'var(--text-2)' }}>
                <input type="radio" checked={userRegionMode === 'cn'} onChange={() => setUserRegionMode('cn')} />
                {str.cnPlayer}
              </label>
              <label style={{ fontSize: 12, color: 'var(--text-2)' }}>
                <input type="radio" checked={userRegionMode === 'intl'} onChange={() => setUserRegionMode('intl')} />
                {str.intlPlayer}
              </label>
            </div>

            {userRegionMode === 'cn' && (
              <div>
                <label style={labelSt}>QQ 号</label>
                <input type="text" style={inputSt} value={qq}
                       onChange={(e) => setQq(e.target.value)} placeholder={str.qqPlaceholder} required autoFocus />
              </div>
            )}
            {userRegionMode === 'intl' && (
              <div>
                <label style={labelSt}>Discord纯数字ID / 联系邮箱</label>
                <input type="text" style={inputSt} value={externalContact}
                       onChange={(e) => setExternalContact(e.target.value)} placeholder={str.externalContactPlaceholder} required autoFocus />
              </div>
            )}

            <div>
              <label style={labelSt}>{str.gameIdLabel}</label>
              <input type="text" style={inputSt} value={gameId}
                     onChange={(e) => setGameId(e.target.value)} placeholder={str.gameIdPlaceholder} required />
            </div>
            <div>
              <label style={labelSt}>{str.passwordLabel}</label>
              <input type="password" style={inputSt} value={password}
                     onChange={(e) => setPassword(e.target.value)} placeholder={str.passwordPlaceholder} required />
            </div>
            <div>
              <label style={labelSt}>{str.confirmPasswordLabel}</label>
              <input type="password" style={inputSt} value={confirmPw}
                     onChange={(e) => setConfirmPw(e.target.value)} placeholder={str.confirmPasswordPlaceholder} required />
            </div>
            {error && <div style={{ color: 'var(--danger)', fontSize: 12, padding: 8, background: 'rgba(214,69,69,0.1)', borderRadius: 3, border: '1px solid rgba(214,69,69,0.3)' }}>{error}</div>}
            {success && <div style={{ color: 'var(--success)', fontSize: 12, padding: 8, background: 'rgba(90,154,85,0.1)', borderRadius: 3 }}>{success}</div>}
            <button type="submit" style={btnPrimary} disabled={loading}>
              {loading ? str.loading : str.registerButton}
            </button>
            <div style={{ textAlign: 'center' }}>
              <span style={{ fontSize: 12, color: 'var(--text-2)' }}>{str.alreadyHaveAccount}</span>
              <button type="button" style={btnSecondary} onClick={() => setMode('login')}>{str.backToLogin}</button>
            </div>
          </form>
        )}

        {mode === 'profile' && targetPlayer && (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', marginBottom: 6 }}>
              <div style={{
                width: 48, height: 48, borderRadius: '50%',
                background: 'linear-gradient(135deg, var(--accent-green), var(--accent-green-dim))',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 20, fontWeight: 700, color: '#fff',
                boxShadow: '0 2px 8px rgba(106,138,74,0.3)',
              }}>
                {targetPlayer.gameId?.charAt(0) || '?'}
              </div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text-0)' }}>游戏ID：{targetPlayer.gameId}</div>
                {!isViewOther && targetPlayer.qq && <div style={{ fontSize: 11, color: 'var(--text-2)', fontFamily: 'var(--mono)' }}>QQ: {targetPlayer.qq}</div>}
                {!isViewOther && targetPlayer.contactExternal && <div style={{ fontSize: 11, color: 'var(--text-2)', fontFamily: 'var(--mono)' }}>外部联系: {targetPlayer.contactExternal}</div>}
              </div>
            </div>

            {isViewOther && (
              <div style={{ textAlign: "center", padding: "12px 0", fontSize: 12, color: "var(--text-3)" }}>
                {str.viewOnlyPublic}
              </div>
            )}

            {!isViewOther && (
              <>
                {!isEdit ? (
                  <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                    <div style={{ fontSize: 12, color: "var(--text-3)" }}>{str.gameIdLocked}</div>
                    <button type="button" style={btnPrimary} onClick={() => setIsEdit(true)}>{str.editProfile}</button>
                    <button type="button" onClick={handleLogout} style={{
                      ...btnPrimary,
                      background: 'transparent',
                      borderColor: 'var(--danger)',
                      color: 'var(--danger)',
                      boxShadow: 'none',
                    }}>
                      {str.logout}
                    </button>
                  </div>
                ) : (
                  <form onSubmit={handleUpdateProfile} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                    <div>
                      <label style={labelSt}>{str.gameIdLabel}</label>
                      <input type="text" style={inputDisabled} value={gameId} disabled />
                    </div>
                    {targetPlayer.qq && (
                      <div>
                        <label style={labelSt}>QQ账号</label>
                        <input type="text" style={inputDisabled} value={qq} disabled />
                      </div>
                    )}
                    {targetPlayer.contactExternal && (
                      <div>
                        <label style={labelSt}>外部联系方式</label>
                        <input type="text" style={inputDisabled} value={externalContact} disabled />
                      </div>
                    )}

                    <div style={{ padding: '6px 0', borderTop: '1px dashed var(--border-0)', marginTop: 6 }}>
                      <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 8 }}>修改密码</div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                        <div>
                          <label style={labelSt}>{str.currentPasswordLabel}</label>
                          <input type="password" style={inputSt} value={confirmPw}
                                 onChange={(e) => setConfirmPw(e.target.value)} />
                        </div>
                        <div>
                          <label style={labelSt}>{str.newPasswordLabel}</label>
                          <input type="password" style={inputSt} value={password}
                                 onChange={(e) => setPassword(e.target.value)} />
                        </div>
                      </div>
                    </div>

                    {error && <div style={{ color: 'var(--danger)', fontSize: 12, padding: 8, background: 'rgba(214,69,69,0.1)', borderRadius: 3 }}>{error}</div>}
                    {success && <div style={{ color: 'var(--success)', fontSize: 12, padding: 8, background: 'rgba(90,154,85,0.1)', borderRadius: 3 }}>{success}</div>}
                    <button type="submit" style={btnPrimary} disabled={loading}>{str.saveChanges}</button>
                  </form>
                )}
              </>
            )}
          </>
        )}
      </div>

      {showIdConfirm && (
        <div style={confirmOverlayStyle} onClick={() => setShowIdConfirm(false)}>
          <div style={confirmBoxStyle} onClick={e => e.stopPropagation()}>
            <h4 style={{ margin: 0, color: 'var(--text-0)' }}>{str.confirmGameId}</h4>
            <div style={{ marginTop: 12, fontSize: 13, color: 'var(--text-2)', lineHeight: 1.6 }}>
              你填写的游戏ID：<b style={{ color: "var(--accent-mustard)" }}>{gameId}</b>
              <br /><br />
              {str.gameIdConfirmWarning}
              <br />
              {str.gameIdConfirmDesc}
            </div>
            <div style={btnRow}>
              <button style={{ ...btnPrimary, flex: 1, background: "transparent", borderColor: "var(--text-2)" }} onClick={() => setShowIdConfirm(false)}>{str.cancel}</button>
              <button style={{ ...btnPrimary, flex: 1 }} onClick={doRealRegister} disabled={loading}>{str.confirmSubmit}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
